Skip to content Skip to sidebar Skip to footer

Parametrize The Test Based On The List Test-data From A Json File

Is there a way to parametrize a test, when test has a list of different/multiple test-data? example_test_data.json { 'test_one' : [1,2,3], # this is the case, where the `test_one`

Solution 1:

I would handle the special parametrization case in pytest_generate_tests hook:

# conftest.pyimport json
import pathlib
import pytest


@pytest.fixture(scope="class")deftest_config(request):
    f = pathlib.Path(request.node.fspath.strpath)
    config = f.with_name("config.json")
    with config.open() as fd:
        testdata = json.loads(fd.read())
    yield testdata


@pytest.fixture(scope="function")defconfig_data(request, test_config):
    testdata = test_config
    test = request.function.__name__
    if test in testdata:
        test_args = testdata[test]
        yield test_args
    else:
        yield {}


defpytest_generate_tests(metafunc):
    if'config_data'notin metafunc.fixturenames:
        return
    config = pathlib.Path(metafunc.module.__file__).with_name('config.json')
    testdata = json.loads(config.read_text())
    param = testdata.get(metafunc.function.__name__, None)
    ifisinstance(param, list):
        metafunc.parametrize('config_data', param)

Some notes: yield_fixture is deprecated so I replaced it with plain fixture. Also, you don't need autouse=True in fixtures that return values - you call them anyway.

Example tests and configs I used:

# testcases/project_1/config.json
{
    "test_one": [1, 2, 3],
    "test_two": "split"
}

# testcases/project_1/test_suite_1.pydeftest_one(config_data):
    assert config_data >= 0deftest_two(config_data):
    assert config_data == 'split'# testcases/project_2/config.json
{
    "test_three": {"three": 3},
    "test_four": {"four": 4}
}

# testcases/project_2/test_suite_2.pydeftest_three(config_data):
    assert config_data['three'] == 3deftest_four(config_data):
    assert config_data['four'] == 4

Running the tests yields:

$ pytest -vs
============================== test session starts ================================
platform linux -- Python 3.6.5, pytest-3.4.1, py-1.5.3, pluggy-0.6.0 --
/data/gentoo64/usr/bin/python3.6
cachedir: .pytest_cache
rootdir: /data/gentoo64/home/u0_a82/projects/stackoverflow/so-50815777, inifile:
plugins: mock-1.6.3, cov-2.5.1
collected 6 items

testcases/project_1/test_suite_1.py::test_one[1] PASSED
testcases/project_1/test_suite_1.py::test_one[2] PASSED
testcases/project_1/test_suite_1.py::test_one[3] PASSED
testcases/project_1/test_suite_1.py::test_two PASSED
testcases/project_2/test_suite_2.py::test_three PASSED
testcases/project_2/test_suite_2.py::test_four PASSED

============================ 6 passed in 0.12 seconds =============================

Post a Comment for "Parametrize The Test Based On The List Test-data From A Json File"