python - pytest 在参数化中使用固定装置作为参数

标签 python pytest

我想使用固定装置作为 pytest.mark.parametrize 的参数或具有相同结果的东西。

例如:

import pytest
import my_package

@pytest.fixture
def dir1_fixture():
    return '/dir1'

@pytest.fixture
def dir2_fixture():
    return '/dir2'

@pytest.parametrize('dirname, expected', [(dir1_fixture, 'expected1'), (dir2_fixture, 'expected2')])
def test_directory_command(dirname, expected):
    result = my_package.directory_command(dirname)
    assert result == expected

fixture 参数的问题是 fixture 的每个参数在每次使用时都会运行,但我不希望这样。我希望能够根据测试选择要使用的固定装置。

最佳答案

Will was on the right path ,您应该使用 request.getfixturevalue 来检索 fixture 。

但是你可以在测试中直接做,这样更简单。

@pytest.mark.parametrize('dirname, expected', [
    ('dir1_fixture', 'expected1'),
    ('dir2_fixture', 'expected2')])
def test_directory_command(dirname, expected, request):
    result = my_package.directory_command(request.getfixturevalue(dirname))
    assert result == expected

另一种方法是使用 lazy-fixture插件:

@pytest.mark.parametrize('dirname, expected', [
    (pytest.lazy_fixture('dir1_fixture'), 'expected1'),
    (pytest.lazy_fixture('dir2_fixture'), 'expected2')])
def test_directory_command(dirname, expected):
    result = my_package.directory_command(dirname)
    assert result == expected

关于python - pytest 在参数化中使用固定装置作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51439888/

相关文章:

python - 选择Python列表中的一些元素

python - 使用多处理创建两个 pygame 屏幕

python - 如何在 django TestCase 中使用 pytest 固定装置

python - 如何从另一个python文件执行 `if __name__ == "__main_ _"`中的代码

python - 如何使用 tox.ini 运行测试

python - NLTK panlex_lite 给我错误

python - 我应该学习 wxPython 代码还是 XRC 代码?

python - 导入 python 3 提示参数为 str/bytes

python - pytest:在每次循环失败运行时写入时间戳

flask - 对于在一个 View 中多次使用的函数,我可以将参数传递给monkeypatch.setattr 中的函数吗?