Search code examples
pythonjsonpytestfixture

pytest parametrized fixture - parameters from json?


Sample code from pytest.org, is it possible to load params from a json file?

# content of conftest.py 
import pytest
import smtplib

@pytest.fixture(scope="module",
            params=["smtp.gmail.com", "mail.python.org"])
def smtp(request):
    smtp = smtplib.SMTP(request.param)
    def fin():
        print ("finalizing %s" % smtp)
        smtp.close()
    request.addfinalizer(fin)
    return smtp

I would like to do something like

# conftest.py
@pytest.fixture(scope="module", params=a_list_var)
def fixture_a(request):

    # some.py or anywhere?
    a_list_var = load_json(parameter_file_path)

    # test_foo.py
    ... 
    def test_foo(fixture_a)
    ...

Solution

  • Given json file:

    ["smtp.gmail.com", "mail.python.org"]
    

    You may simply load it to Python object and pass that object to decorator.

    import json
    import pytest
    import smtplib
    
    def load_params_from_json(json_path):
        with open(json_path) as f:
            return json.load(f)
    
    @pytest.fixture(scope="module", params=load_params_from_json('path/to/file.json'))
    def smtp(request):
        smtp = smtplib.SMTP(request.param)
        def fin():
            print ("finalizing %s" % smtp)
            smtp.close()
        request.addfinalizer(fin)
        return smtp