相关疑难解决方法(0)

pytest使用fixtures作为参数化中的参数

我想使用fixtures作为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
Run Code Online (Sandbox Code Playgroud)

夹具参数的问题在于夹具的每个参数都会在每次使用时运行,但我不希望这样.我希望能够根据测试选择使用哪种灯具.

python pytest

21
推荐指数
4
解决办法
5209
查看次数

Pytest基于参数生成测试

新的pytest ...

我在conftest.py中有以下内容从命令行收集团队参数,并读入yaml配置文件:

import pytest
import yaml


def pytest_addoption(parser):
    parser.addoption(
        '--team',
        action='store',
        )


@pytest.fixture
def team(request):
    return request.config.getoption('--team')


@pytest.fixture
def conf(request):
    with open('config.yml', 'r') as f:
        conf = yaml.load(f.read())
    return conf
Run Code Online (Sandbox Code Playgroud)

我想对conf [team] ['players'](列表)中的每个玩家进行测试.我可以在test_players.py中执行以下操作:

def test_players(team, conf):
    players = conf[team]['players']
    for p in players:
        assert p == something
Run Code Online (Sandbox Code Playgroud)

这种作品,因为它遍历玩家,但整个事情被视为一个单一的测试.如果有任何失败,整个测试将被视为失败.我想让每个玩家分别进行测试.

如果我手动插入玩家,我可以让它工作:

import pytest

class Test_Player():
    @pytest.mark.parametrize(
        'player', [
            'player1',
            'player2',
            'player3',
        ],
    )
    def test_player(self, player):
        assert player == something
Run Code Online (Sandbox Code Playgroud)

所以我的问题是我不知道怎么把conf [team]传递给pytest.mark.parametrize.我尝试过这些,但在这两种情况下都抱怨conf没有定义.

import pytest

class Test_Player():
    @pytest.mark.parametrize(
        'player', conf[team]['players'],
    )
    def …
Run Code Online (Sandbox Code Playgroud)

python pytest

8
推荐指数
1
解决办法
744
查看次数

标签 统计

pytest ×2

python ×2