本文介绍了Python模拟修补程序无法按照公共方法的预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为我的烧瓶应用程序修补一个公共方法,但它似乎不工作。



这里是我的代码 mrss.feed_burner

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

这就是我使用它的方式

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

返回响应

这是我的测试,它不是解析。

  def test_feed(self):
with patch('mrss.feed_burner.get_feed',new = lambda:' < / xml>'):
response = self.app.get('/ feed')
self.assertEquals('< xml>< / xml>',response .data)


解决方案

我相信你的问题在于,不要在正确的命名空间中修补。有关 where_to_patch 文档> unittest.mock.patch 。



基本上,您正在修补 get_feed() in mrss.feed_burner ,但是您的视图处理程序 feed()已经引用了原来的 mrss.feed_burner.get_feed()。为了解决这个问题,你需要在你的视图文件中修改引用。



根据 get_feed 在你的视图函数中,我假设你正在导入 get_feed 像这样

view_file.py

  from mrss.feed_burner import get_feed 

如果是这样,你应该修补 view_file.get_feed ,如下所示:

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


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)
解决方案

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>'):
        ...

这篇关于Python模拟修补程序无法按照公共方法的预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-15 20:50