pytest parametrized fixture - parameters from json?
Asked Answered
H

2

5

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)
    ...
Hinayana answered 17/12, 2015 at 9:19 Comment(0)
E
15

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
Embrocate answered 17/12, 2015 at 9:39 Comment(2)
Thanks, I ended up using [pytest-generate-tests] (pytest.org/latest/…) for this.Hinayana
This solution only partially worked for me. I had to pass params @pytest.fixture(scope="module", params=[load_params_from_json('path/to/file.json')]) as an array. Maybe this has to do with the fact that my json is not a simple list or pytest has changed.Cystitis
H
2

Thanks, I ended up using pytest-generate-tests for this, my json path will be changed depending on the test case.

# test_foo.py
def test_foo(param)

# conftest.py
def pytest_generate_tests(metafunc):
    ... my <same_name_as_test>.json
    ... get info from metafunc.module 
    with open(param_full_path,'r') as f:
        obj = json.load(f)
        metafunc.parametrize("param", obj)
Hinayana answered 17/12, 2015 at 15:38 Comment(2)
would be helpful if an example of using this in a test was shown.Koser
friends don't provide a sample code that is not codeCervix

© 2022 - 2024 — McMap. All rights reserved.