Pytest Generate Tests Based on Arguments

后端 未结 1 892
孤城傲影
孤城傲影 2021-02-15 01:13

New to pytest...

I have the following in conftest.py to collect a team argument from the command line, and read in a yaml config file:

import pytest
impo         


        
1条回答
  •  失恋的感觉
    2021-02-15 01:45

    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].

    0 讨论(0)
提交回复
热议问题