【问题标题】:How can I use a pytest fixture as a parametrize argument?如何使用 pytest 夹具作为参数化参数?
【发布时间】:2015-09-22 16:06:06
【问题描述】:

我有一个像这样的 pytest 测试:

email_two = generate_email_two()

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

现在,作为重构的一部分,我已经移动了这一行:

email_two = generate_email_two()

放入它自己的固定装置(在 conftest.py 文件中),因为它用于其他各种地方。但是,除了直接导入fixture函数之外,还有其他方法可以在这个测试中引用它吗?我知道 funcargs 通常是调用夹具的方式,但在这种情况下,当我想调用夹具时,我不在测试函数中。

【问题讨论】:

  • 听起来像 session-fixture 可能会有所帮助:pytest.org/latest/example/special.html
  • @dm295 我可以做类似的事情......但这会将夹具耦合到它被调用的地方(我认为)。从某种意义上说,夹具会将自己附加到特定的类上。虽然,或者,夹具可以附加到 每个 类,或类似的东西,但这似乎是一个糟糕的解决方案。
  • 你不能在参数化中使用fixtue。 bitbucket.org/pytest-dev/pytest/issues/349/…

标签: python pytest fixtures


【解决方案1】:

我最终通过在测试函数中使用一个 for 循环来遍历每封电子邮件。就测试输出而言,这不是最好的方法,但它可以完成工作。

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 = ['id5489746@mockmyid.com', 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 = 'some_fake_address@example.com'
        res = login.groupfinder(fake_email)
        assert res == ['g:commenter']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-08
    相关资源
    最近更新 更多