Pytest Generate Tests Based on Arguments

别说谁变了你拦得住时间么 提交于 2019-12-04 04:45:00

The problem with your setup is that you want to parameterize on conf[team], but conf needs to be defined at import time, because that's when the decorator executes.

So, you'll have to go about this parameterization differently, using pytest's metafunc parametrization features.

.
├── conftest.py
├── teams.yml
└── test_bobs.py

In the yaml file:

# teams.yml
bobs: [bob1, bob2, potato]
pauls: [paultato]

In the test module:

# test_bobs.py
def test_player(player):
    assert 'bob' in player

In the pytest conf:

import pytest
import yaml


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


def pytest_generate_tests(metafunc):
    if 'player' in metafunc.fixturenames:
        team_name = metafunc.config.getoption('team')

        # you can move this part out to module scope if you want
        with open('./teams.yml') as f:
            teams = yaml.load(f)

        metafunc.parametrize("player", teams.get(team_name, []))

Now execute:

pytest --team bobs

You should see three tests executed: two passing tests (bob1, bob2) and one failing test (potato). Using pytest --team pauls will make one failing test. Using pytest --team bogus will result in a skipped test. If you want a different behaviour there, change the teams.get(team_name, []) to, for example, teams[team_name].

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!