python-3.x - 如何模拟返回用户对象的函数
问题描述
我正在尝试模拟一个返回用户对象的方法,如下所示
@mock.patch('impersonate.helpers.which_user', return_value=self.user2)
def test_user_can_retrieve_favs_using_impersonation(self):
它因错误而失败:NameError: name 'self' is not defined
. 我self.user2
在测试类的 setup 方法中定义了。
解决方案
您不能self
在装饰器中使用 - 对象在解析时尚未定义。
相反,您可以将补丁移到方法中:
def test_user_can_retrieve_favs_using_impersonation(self):
with mock.patch('impersonate.helpers.which_user', return_value=self.user2):
...
或者
def test_user_can_retrieve_favs_using_impersonation(self):
with mock.patch('impersonate.helpers.which_user') as mocked:
mocked.return_value=self.user2
...
推荐阅读
- python - 全局变量 - 引用后如何分配变量?
- qt-designer - 在 qt 设计器中 QButtonGroup 在 Widget Box 中不可用。
- drop-down-menu - Dropdown select start spinner in Angular 6
- javascript - 类方法在哪里被调用?
- sql-server - SQL Server 中的最后订单日期和年初至今销售额
- google-analytics - 在 Google Analytics 中,如何过滤整个 ISP 但允许特定 IP 地址?
- javascript - 查询选择没有被点击的div来增加它的宽度
- c# - 是否有必要使用构造函数注入检查空值?
- dictionary - Delphi TObjectDictionary 继承
- postgresql - 为什么我的 Postgresql 实例不使用位图索引扫描?