对于公共方法,Python 模拟补丁无法按预期工作

Python mock patch doesn#39;t work as expected for public method(对于公共方法,Python 模拟补丁无法按预期工作)
本文介绍了对于公共方法,Python 模拟补丁无法按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在尝试为我的烧瓶应用程序修补公共方法,但它似乎不起作用.

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_burnerget_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 模拟补丁无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

patching a class yields quot;AttributeError: Mock object has no attributequot; when accessing instance attributes(修补类会产生“AttributeError:Mock object has no attribute;访问实例属性时)
How to mock lt;ModelClassgt;.query.filter_by() in Flask-SqlAlchemy(如何在 Flask-SqlAlchemy 中模拟 lt;ModelClassgt;.query.filter_by())
FTPLIB error socket.gaierror: [Errno 8] nodename nor servname provided, or not known(FTPLIB 错误 socket.gaierror: [Errno 8] nodename nor servname provided, or not known)
Weird numpy.sum behavior when adding zeros(添加零时奇怪的 numpy.sum 行为)
Why does the #39;int#39; object is not callable error occur when using the sum() function?(为什么在使用 sum() 函数时会出现 int object is not callable 错误?)
How to sum in pandas by unique index in several columns?(如何通过几列中的唯一索引对 pandas 求和?)