python - 我可以用其他装置参数化 pytest 装置吗?

标签 python pytest fixtures

我有一个 python 测试,它使用固定装置作为凭据(用户 ID 和密码的元组)

def test_something(credentials)
   (userid, password) = credentials
   print("Hello {0}, welcome to my test".format(userid))

我有用于凭证的 pytest 固定装置:

@pytest.fixture()
def credentials():
   return ("my_userid", "my_password")

效果很好

现在我想将其扩展到多个凭据(例如登台和生产),以便我的测试将运行两次(登台和生产各运行一次)。

我认为参数化是答案,但似乎我无法使用装置进行参数化。

我想做这样的事情:

@pytest.fixture(params=[staging_credentials, production_credentials])
def credentials(request):
    return request.param

其中 staging_credentials 和 production_credentials 都是固定装置:

@pytest.fixture()
def staging_credentials():
   return ("staging_userid", "staging_password")

@pytest.fixture()
def production_credentials():
   return ("prod_userid", "prod_password")

但显然该灯具的参数不能是其他灯具。

关于如何优雅地处理这个问题有什么建议吗?我看过https://docs.pytest.org/en/latest/proposals/parametrize_with_fixtures.html但这似乎太暴力了。

谢谢! 史蒂夫

最佳答案

间接参数化就是答案。因此,灯具的参数可以是其他灯具(按名称/代码)。

import pytest

all_credentials = {
    'staging': ('user1', 'pass1'),
    'prod': ('user2', 'pass2'),
}

@pytest.fixture
def credentials(request):
    return all_credentials[request.param]

@pytest.mark.parametrize('credentials', ['staging', 'prod'], indirect=True)
def test_me(credentials):
    pass

从技术上讲,您不仅可以通过其键获取字典值,还可以根据 request.param 生成 credentials 结果,并且此参数将是传递的值到测试的同名参数。

如果您想使用其他灯具(可能是因为安装/拆卸阶段,因为这是这样做的唯一原因):

import pytest

@pytest.fixture
def credentials(request):
    return request.getfuncargvalue(request.param)

@pytest.fixture()
def staging_credentials():
   return ("staging_userid", "staging_password")

@pytest.fixture()
def production_credentials():
   return ("prod_userid", "prod_password")

@pytest.mark.parametrize('credentials', ['staging_credentials', 'production_credentials'], indirect=True)
def test_me(credentials):
    pass

这里,request.getfuncargvalue(...) 将通过 fixture 名称动态返回 fixture 值。

关于python - 我可以用其他装置参数化 pytest 装置吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46941838/

相关文章:

Python:在键相同的字典列表中组合唯一值?

python - 如何在 Eclipse 上运行 pytest?

python - 测试数据库在 Django Channels Pytest 测试期间不保留数据

python - 单元测试模拟 AWS Lambda 函数、Python

ruby-on-rails - 在 Rails 中使用固定装置分配 attr_accessor

unit-testing - 将 html 与 testacularjs 集成时出错

python - 在参数化中传递 pytest fixture

Python 无法放置模块

Python - 如何将文本写入 GTK+ Vte 终端小部件?

python - 如何在 Google Colab 中的另一个虚拟机上拍摄和恢复模型训练的快照?