Search code examples
pythonpytestfixtures

I can have a generic fixture and call different values from that in my test?


I'm new on python and pytest, and at the momment I understand the basic of how work. But I can't find documentation to the below scenario:

I created a generic fixture that have the default mock values used in my project, and use this fixture in tests, it works fine. Something like:

#fixture
@pytest.fixture()
def generic_fixture(mocker):
    mocker.patch('project.some_class.url', "http://some_url:5002")

#test
def test_1(generic_fixture):
    do_something() # method that uses values from my generic fixture
    assert True

Now I want to know if have a way to pass a parameter in my test to my fixture call, to make some decision, something like:

#fixture
@pytest.fixture()
def generic_fixture(mocker, parameter_url):
    if parameter_url == None
        mocker.patch('project.some_class.url', "http://some_url:5002")
    else:
        mocker.patch('project.some_class.url', parameter_url)

#test
def test_1(generic_fixture(parameter_url)):
    do_something() # method that uses values from my generic fixture
    assert True

How I can do It properly? I looked at monkeypath, @pytest.mark.parametrize and some other structures, but none of them look to do what I want.


Solution

  • You can use Pytest's marks for this.

    #fixture
    @pytest.fixture()
    def generic_fixture(request, mocker):
        parameter_url = request.node.get_closest_marker("generic_fixture_url")
        ...
    
    #test
    @pytest.mark.generic_fixture_url("url")
    def test_1(generic_fixture):
        ...
    

    Other options are to turn your fixture into a factory or to set some attribute on the module of your test.