仍然是python的新手,尤其是编写python单元测试。
找到http://tapioca-wrapper.readthedocs.io/en/stable/并在api周围写了一个简单的客户端。
模块基本上获取api的有效载荷的键/值对并将它们转换为对象。由于这是动态的并且由有效载荷生成,因此我在编写模拟单元测试时遇到了最好的方法。
示例包装器代码是:
api_client = APIClientAdapter()
vm_machine = api_client.vm_machine(vm_name='playdohvm').get()
print("vm name: {}".format(vm_machine.name().data)
我的模拟代码看起来像
self.mock_api_client = Mock(
spec=APIClientAdapter,
return_value=Mock(
get=Mock(
return_value=Mock(
name=Mock(
return_value=Mock(
data='playdohvm'))))))
这是否有更好的方法来模拟木薯包装模块?
答案 0 :(得分:0)
根据您要测试的内容,我认为它会改变模拟的方式。
例如,无需使用Mock对象表达所有内容,最好准备一个简单的对象并将其替换为mock.patch
。
class DummyAPIClientAdapter:
data = 'playdohvm'
def __call__(self, *args, **kwargs):
return self
def __getattr__(self, *args, **kwargs):
return self
with mock.patch('APIClientAdapter', new=DummyAPIClientAdapter):
api_client = APIClientAdapter()
vm_machine = api_client.vm_machine(vm_name='playdohvm').get()
print("vm name: {}".format(vm_machine.name().data))