Can we print the command line arguments in setup_module() or setup_class in pytest?

Viewed 1629

I got to know how to pass command line parameters in pytest. I want to print or do some basic validation in my setup_class() or setup_module() against the variables passed as command line arguments.

I am able to access these variables in test methods but not in setup_class or setup_module. Is this even possible?

I want to do something like this...

conftest.py

def pytest_addoption(parser):
    parser.addoption('--user',action='store', help='email id Ex: abc@infoblox.com')

test_1.py

import pytest

def setup_module():
    print 'Setup Module'
def teardown_module():
    print "Teardown Module"

class Test_ABC:

    def setup_class(cls,request):
        user = request.config.option.user
        print user
        print 'Setup Class'

    def teardown_class(cls,request):
        print 'Teardown Class'

    def test_12(self,request):
        print "Test_12"
        assert 1==1
3 Answers

I had a similar use case and I ended up implementing it as follows:

In conftest.py

import pytest

def pytest_addoption(parser):
    parser.addoption("--testarg", action="store", dest="testarg", default="test", help="testarg help")

def pytest_configure(config):
    pytest.testarg = config.getoption('testarg')

In test_sample.py

import pytest
print pytest.testarg

Resources:

  1. https://docs.pytest.org/en/latest/reference.html#_pytest.hookspec.pytest_addoption

1.Add conftest.py at first and add 2 method in it.

def pytest_addoption(parser):
    parser.addoption(
        "--devicename", action="store", default="test1", help="test1"
    )

def pytest_configure(config):
    pytest.devicename = config.getoption('devicename')

2.Then call pytest. in your setupclass or setupmethod. like print(pytest.devicename)

Related