python - 结合 mock 和 getattr
问题描述
我想制作一个适合我们团队测试的模拟对象。
但是,默认的getattr行为不是我想要的。请参阅下面的示例。
import mock
class A(mock.MagicMock):
pass
a = A()
print(a.something) # got a MagicMock without error
print(getattr(a, "something", False)) # False expected, but got a mock object
我试图覆盖__getattr__方法
import mock
class A(mock.MagicMock):
def __getattr__(self, name):
try:
return object.__getattribute__(self, name)
except:
return mock.MagicMock.__getattribute__(self, name)
a = A()
print(getattr(a, "something", False)) # got a False value
print(a.something) # got attribute error
我不允许更改源代码中的“getattr(...)”。
编辑:
The test flow may look like this
import mock
class A:
def foo(self):
# the "something" may not be initiated,
# and I want it to be 1 rather then a mock object
stat = getattr(self, "something", 1)
stat *= 100
# the client is valid only when a client connected,
# I want to mock it because this is a offline test.
# Since there all many attributes like "client",
# I don't want to overwrite every one in the MockA class
self.client.call("done")
return stat
class MockA(A, mock.MagicMock):
pass
def test_foo():
a = MockA()
assert a.foo() == 100
a.something = 4
assert a.foo() == 400
解决方案
推荐阅读
- mongodb - MongoDB 在数组中查找
- c# - C#中两个插件之间的通信
- php - 网络爬取网站返回空(使用 preg_match_all)
- java - LinkedList 移除元素之谜
- sql-server - 尝试 Catch 块未捕获 SQL Server 更新语句中的错误消息
- visual-studio-code - VS Code 中的更漂亮 - 在双引号内格式化双引号
- android - 减少导航抽屉图标和菜单文本之间的空间
- reactjs - VSCode 插件的 eCSSTractor 不适用于 className
- java - 引入命名参数会中断 jOOQ 查询
- java - 严重:Web 应用程序 [/restapp] 中的 Servlet [Jersey Web Application] 引发 load() 异常