Search code examples
pythonpytestpytest-cov

Pytest argument from command line with fixture


Code : Test1.py

import pytest

@pytest.fixture(scope='session', autouse=True)
def tc_setup(start):
    if start == "20d":
        print('20d is sent')
    else:
        print('not in list')

def pytest_addoption(parser):
    parser.addoption('--start')

@pytest.fixture(scope='session', autouse=True)
def start(request):
    return request.config.getoption('--start')

From Command Line

pytest -v test1.py --start=20d

Also tried,

pytest -v test1.py --start 20d

Error Message

ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...]
pytest: error: unrecognized arguments: --start=20d
  inifile: None

How can I send parameters from command line and pytest. I'm running this from bash shell on linux ubuntu terminal.

Version

pytest 7.1.0

Solution

  • Here's how it worked for me. Created two files : conftest.py and myso_test.py. You basically need to have a conftest file

    conftest.py

    import pytest
    
    
    def pytest_addoption(parser):
        parser.addoption("--start")
    
    @pytest.fixture(scope='session', autouse=True)
    def start(request):
        return request.config.getoption("--start")
    

    myso_test.py

    import pytest
    
    @pytest.fixture(scope='session', autouse=True)
    def tc_setup(start):
        if start == "20d":
            print('20d is sent')
        else:
            print('not in list')
    
    def test_var():
        assert True
    

    Running the command:

    pytest myso_test.py -s -v --start="20d"  
    

    Output:

    myso_test.py::test_var 20d is sent
    PASSED
    

    Running the command:

    pytest myso_test.py -s -v --start="20dw"
    

    Output:

    myso_test.py::test_var not in list
    PASSED