我在 pytest 中编写了一个 fixture ,它没有参数化,但被很多测试使用。后来我需要参数化这个 fixture 。
为了不用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()
现在我可以同时拥有:
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)
该解决方案有几个缺点:
是否有标准方法来定义 fixture 参数的默认值?
最佳答案
间接参数化很麻烦。为了避免这种情况,我通常编写fixture 以便它返回一个函数。我最终会这样写:
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))
关于python-3.x - pytest - 默认 fixture 参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54109759/