Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
627 views
in Technique[技术] by (71.8m points)

unit testing - Python mock patch doesn't work as expected for public method

I'm trying to patch a public method for my flask application but it doesn't seem to work.

Here's my code in mrss.feed_burner

def get_feed(env=os.environ):
   return 'something'

And this is how I use it

@app.route("/feed")
    def feed():
        mrss_feed = get_feed(env=os.environ)
        response = make_response(mrss_feed)
        response.headers["Content-Type"] = "application/xml"

        return response

And this is my test which it's not parsing.

def test_feed(self):
    with patch('mrss.feed_burner.get_feed', new=lambda: '<xml></xml>'):
        response = self.app.get('/feed')
        self.assertEquals('<xml></xml>', response.data)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I believe your problem is that you're not patching in the right namespace. See where_to_patch documentation for unittest.mock.patch.

Essentially, you're patching the definition of get_feed() in mrss.feed_burner but your view handler feed() already has a reference to the original mrss.feed_burner.get_feed(). To solve this problem, you need to patch the reference in your view file.

Based on your usage of get_feed in your view function, I assume you're importing get_feed like so

view_file.py

from mrss.feed_burner import get_feed

If so, you should be patching view_file.get_feed like so:

def test_feed(self):
    with patch('view_file.get_feed', new=lambda: '<xml></xml>'):
        ...

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...