問題描述
我正在嘗試為我的燒瓶應用程序修補公共方法,但它似乎不起作用.
I'm trying to patch a public method for my flask application but it doesn't seem to work.
這是我在 mrss.feed_burner
def get_feed(env=os.environ):
return 'something'
這就是我使用它的方式
@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)
推薦答案
我相信您的問題是您沒有在正確的命名空間中進行修補.請參閱 where_to_patch 文檔了解 unittest.mock.patch
.
I believe your problem is that you're not patching in the right namespace. See where_to_patch documentation for unittest.mock.patch
.
本質上,您正在修補 mrss.feed_burner
中 get_feed()
的定義,但您的視圖處理程序 feed()
已經有一個參考原始 mrss.feed_burner.get_feed()
.要解決此問題,您需要修補視圖文件中的引用.
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.
根據您在視圖函數中對 get_feed
的使用,我假設您正在像這樣導入 get_feed
Based on your usage of get_feed
in your view function, I assume you're importing get_feed
like so
view_file.py
view_file.py
from mrss.feed_burner import get_feed
如果是這樣,您應該像這樣修補 view_file.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>'):
...
這篇關于對于公共方法,Python 模擬補丁無法按預期工作的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!