Why would a pytest factory as fixture be used over a factory function?

不羁的心 提交于 2019-12-07 17:55:25

问题


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

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.


回答1:


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.

Look at this example:

@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

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.

If you now write:

@pytest.fixture
def connect_client(mocked_server):
    def __connect(local_port):
        client = Client()
        client.connect_to(mocked_server, local_port)
        return client
    return __connect

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




回答2:


One example might be a session-level fixture, e.g.:

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

This way, Pytest will ensure that only one instance of the factory exists for the duration of your tests. This example in particular perhaps doesn't gain much from this, but if the outer function does a lot of processing, such as reading from a file or initialising data structures, then this can save you a lot of time overall.




回答3:


see below code, this gives ans to your questions..

import pytest
@pytest.fixture
def make_foo():
    def __make_foo(name):
        print(name)
    return __make_foo

def test_a(make_foo):
    make_foo('abc')

def test_b(make_foo):
    make_foo('def')

The output is shown below ::

tmp3.py::test_a abc
PASSED
tmp3.py::test_b def
PASSED

basically you can pass the arguments in factory fixture and can use according to your requirement.



来源:https://stackoverflow.com/questions/51663326/why-would-a-pytest-factory-as-fixture-be-used-over-a-factory-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!