pytest - 默认夹具参数值

Pro*_*e85 5 pytest python-3.x

我在 pytest 中编写了一个夹具,它没有参数化,但被很多测试使用。后来我需要参数化这个夹具。

为了不必进行mark.parametrize所有旧测试,我执行了以下操作:

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()
Run Code Online (Sandbox Code Playgroud)

现在我可以同时拥有:

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)
Run Code Online (Sandbox Code Playgroud)

该解决方案有几个缺点:

  • 我发现了一个任意的属性错误(可能还有另一个)
  • 它不考虑命名参数
  • 读者不清楚有默认值

是否有标准方法来定义夹具参数的默认值?

Sil*_*Guy -1

间接参数化很混乱。为了避免这种情况,我通常编写固定装置以使其返回一个函数。我最终会这样写:

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))
Run Code Online (Sandbox Code Playgroud)