pytest - default fixture parameter value

Viewed 1503

I wrote a fixture in pytest which was not parametrized but is used by a lot of tests. Later I needed to parametrize this fixture.

In order to not to have to mark.parametrize all the old tests I did the following:

def ldap_con(request):
    try:
        server_name = request.param
    except AttributeError:
        server_name = "ldaps://my_default_server"
    c = Connection(server_name, use_ssl=True)
    yield c
    c.unbind()

Now I can have both:

def test_old(ldap_con):
    run_test_to_default_connection(ldap_con)


@pytest.mark.parametrize('ldap_con', ['mynewserver'], indirect=True)
def test_new(ldap_con):
    run_test_to_new_connection(ldap_con)

The solution has several drawbacks:

  • I am catching an arbitrary Attribute Error (there might be another)
  • It does not take into account named parameters
  • It is not clear to a reader that there is a default value

Is there a standard way to define a default value for a fixture parameter?

1 Answers

Indirect parametrization is messy. To avoid that, I usually write fixture so that it returns a function. I will end up writing it this way:

def ldap_con():
    def _ldap_con(server_name="ldaps://my_default_server"):
        c = Connection(server_name, use_ssl=True)
        yield c
        c.unbind()
    return _ldap_con

def test_old(ldap_con):
    run_test_to_default_connection(ldap_con())


@pytest.mark.parametrize('server', ['mynewserver'])
def test_new(server):
    run_test_to_new_connection(ldap_con(server))
Related