为什么要在工厂功能上使用pytest工厂作为固定装置? [英] Why would a pytest factory as fixture be used over a factory function?

查看:102
本文介绍了为什么要在工厂功能上使用pytest工厂作为固定装置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

py.test文档中进行了描述将工厂方法声明为fixture,就像这样:

In the py.test docs it describes declaring factory methods as fixtures, like-so:

@pytest.fixture
def make_foo():
    def __make_foo(name):
        foo = Foo()
        foo.name = name
        return foo
    return __make_foo

与仅定义make_foo函数并使用它相比,这样做有什么好处/缺点?我不明白为什么它是固定装置.

What are the benefits/tradeoffs of doing this over just defining a make_foo function and using that? I don't understand why it is a fixture.

推荐答案

实际上,最重要的优点是能够使用其他固定装置,并为您提供pytest的依赖项注入. 另一个优点是允许您将参数传递给工厂,而这些参数在普通灯具中必须是静态的.

Actually, the most important advantage is being able to use other fixtures, and make the dependency injection of pytest work for you. The other advantage is allowing you to pass parameters to the factory, which would have to be static in a normal fixture.

看这个例子:

@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的测试,但是您不能更改端口. 如果您需要与多个客户进行测试该怎么办?你也不能.

You could now write a test that gets a connected_client, but you can't change the port. What if you need a test with multiple clients? You can't either.

如果您现在写:

@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工厂的测试,并调用它以在任何端口中获取初始化的客户端,以及所需的次数!

You get to write tests receiving a connect_client factory, and call it to get an initialized client in any port, and how many times you want!

这篇关于为什么要在工厂功能上使用pytest工厂作为固定装置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆