I am trying to design pytest automation suite to rest REST APIs
In conftest.py I have:
def pytest_addoption(parser):
parser.addoption("--env", action="store", help="accepting dev,qa,stage")
def pytest_configure(config):
global base_path,execution_path,users,user_alpha,user_beta,user_gamma,psw_alpha,psw_beta,psw_gamma
cfg=ConfigParser()
cfg.read('config.ini')
base_path = cfg.get('base', 'path')
if config.getoption('env') in ['qa','stage','dev']:
environ = config.getoption('env')
execution_path = base_path.format(env=environ)
else:
sys.exit(1)
@pytest.fixture(scope='session')
def base():
global execution_path
return execution_path
def get_user():
global execution_path,users
cfg=ConfigParser()
cfg.read('config.ini')
user1 = cfg.get('users','user1')
psw_user1 = cfg.get('users','psw.user1')
user2 = cfg.get('users','user.user2')
psw_user2 = cfg.get('users','psw.user2')
user3 = cfg.get('users','user.user3')
psw_user3 = cfg.get('users','psw.user3')
users = [(user1, psw_user1,user1_token), (user2, psw_user2,user2_token), (user3, psw_user3,user3_token)]
return users
@pytest.fixture(params=get_user(),scope='session', ids=['user1','user2','user3'])
def return_user(request):
return request.param
in test_module.py:
def test_function1(base, return_user):
pass
def test_function2(base, return_user):
pass
output
test_upload.py::test_pass4[user1] PASSED [ 16%]
test_upload.py::test_pass5[user1] PASSED [ 33%]
test_upload.py::test_pass4[user2] PASSED [ 50%]
test_upload.py::test_pass5[user2] PASSED [ 66%]
test_upload.py::test_pass4[user3] PASSED [ 83%]
test_upload.py::test_pass5[user3] PASSED [100%]
Creating tokens can be accomplished with pytest_configure(metafunc). However with pytest_configure pytest runs test_pass4 for each user, then begins test_pass5 for each and thus generating a new token for every test. I'd like to have the same token for all tests in the same module for same user.
To get the token I need command line argument passed so that I can format the execution_path with env variable passed in command line. I can accomplish this by def get_user(config) to access env. However @pytest.fixture(params=get_user(config)) doesn't recognize config. Or I don't have other parameters to pass in get_user().
Is there a way to accomplish this?
UPDATE: I was able to access command line arguments inside the fixture with pytest.config.getoption('env')) and then do necessary transformation inside the fixture
@pytest.fixture(params=get_user(),scope='session', ids=['user1','user2','user3'])
def return_user(request):
cfg=ConfigParser()
cfg.read('config.ini')
base_path = cfg.get('base', 'path')
base_path = base_path.format(env=request.config.getoption('env'))
user = #payload to login user
user.token = #code to get token
temp = request.param
temp.append(user.token)
return temp