3

using python 3.8 and pytest 5.3.2

in conftest.py i have a fixture that read data from a json configuration file, in order to reuse data read from the json configuration file in a several test.

configuration.json

{"username":"user", "endpoints":["https://www.something.com/url1", "https://www.something.com/url2"]}

conftest.py


def pytest_addoption(parser):
    parser.addoption("--configuration", action="store", default="configuration.json")


@pytest.fixture(scope="session")
def configuration(request):
    configuration= None
    configuration= request.config.getoption("--configuration")
    with open(configuration, 'r') as f:
        configuration= json.load(f)
    return configuration

and this works fine :


class TestService():
   def test_something(configuration)
      assert configuration['username'] == 'user' 

in this case the test read data from configuration fixture that read data from configuration.json file.

the problem is when i want to use this data with @parametrize :

i want to convert this approach:


@mark.parametrize('endpoint', [
    "https://www.something.com/url1", "https://www.something.com/url2"
])
def test_endpoints_parametrizzato(endpoint):
    print(endpoint)
    assert requests.get(endpoint).status_code == 200

with this approach


@mark.parametrize('endpoint', configuration['endpoints'])
def test_endpoints_parametrizzato(endpoint):
    print(endpoint)
    assert requests.get(endpoint).status_code == 200

but this will not work because @parametrize will not "see" the fixture i want to use to parametrize it. i read a lot of articles but i'm not able to understand if i'm doing something wrong or i cannot parametrize reading data from a fixture. can someone help me explaining again? i read

Community
  • 1
  • 1
Andrea Bisello
  • 1,077
  • 10
  • 23

2 Answers2

1

as discussed here you can't.

you can use a custom test generator

Andrea Bisello
  • 1,077
  • 10
  • 23
0

Instead of using a fixture to pass as parametrize argument you can write a function and call it.

def get_configuration(key):
    with open("configuration.json", 'r') as f:
        configuration = json.load(f)
    return configuration.get('key')

    @mark.parametrize('endpoint', get_configuration('endpoints'))
def test_endpoints_parametrizzato(endpoint):
    print(endpoint)
    assert requests.get(endpoint).status_code == 200
Override12
  • 116
  • 1
  • 7