In the py.test 文档 https://docs.pytest.org/en/latest/fixture.html#factories-as-fixtures它描述了将工厂方法声明为固定装置,如下所示:
@pytest.fixture
def make_foo():
def __make_foo(name):
foo = Foo()
foo.name = name
return foo
return __make_foo
与仅定义 make_foo 函数并使用它相比,这样做有什么好处/权衡?我不明白为什么它是一个固定装置。
实际上,最重要的优点是能够使用其他固定装置,并使 pytest 的依赖注入为您工作。
另一个优点是允许您将参数传递给工厂,这些参数在普通夹具中必须是静态的。
看这个例子:
@pytest.fixture
def mocked_server():
with mock.patch('something'):
yield MyServer()
@pytest.fixture
def connected_client(mocked_server):
client = Client()
client.connect_to(mocked_server, local_port=123) # local_port must be static
return client
您现在可以编写一个测试来获取connected_client
,但您无法更改端口。
如果您需要对多个客户端进行测试怎么办?你也不能。
如果你现在写:
@pytest.fixture
def connect_client(mocked_server):
def __connect(local_port):
client = Client()
client.connect_to(mocked_server, local_port)
return client
return __connect
你可以编写测试来接收connect_client
工厂,并调用它以在任何端口获取初始化的客户端,并且您想要多少次!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)