Search code examples
pythonpytestfixtures

How can I use a pytest fixture as a parametrize argument?


I have a pytest test like so:

email_two = generate_email_two()

@pytest.mark.parametrize('email', ['[email protected]', email_two])
def test_email_thing(self, email):
        ... # Run some test with the email parameter

Now, as part of refactoring, I have moved the line:

email_two = generate_email_two()

into its own fixture (in a conftest.py file), as it is used in various other places. However, is there some way, other than importing the fixture function directly, of referencing it in this test? I know that funcargs are normally the way of calling a fixture, but in this context, I am not inside a test function when I am wanting to call the fixture.


Solution

  • I ended up doing this by having a for loop in the test function, looping over each of the emails. Not the best way, in terms of test output, but it does the job.

    import pytest
    import fireblog.login as login
    
    pytestmark = pytest.mark.usefixtures("test_with_one_theme")
    
    class Test_groupfinder:
        def test_success(self, persona_test_admin_login, pyramid_config):
            emails = ['[email protected]', persona_test_admin_login['email']]
            for email in emails:
                res = login.groupfinder(email)
                assert res == ['g:admin']
    
        def test_failure(self, pyramid_config):
            fake_email = '[email protected]'
            res = login.groupfinder(fake_email)
            assert res == ['g:commenter']