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)
    ...
falsetru
  • 357,413
  • 63
  • 732
  • 636
Eric Chang
  • 83
  • 1
  • 1
  • 5

2 Answers2

13

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
Łukasz Rogalski
  • 22,092
  • 8
  • 59
  • 93
  • Thanks, I ended up using [pytest-generate-tests] (https://pytest.org/latest/parametrize.html#basic-pytest-generate-tests-example) for this. – Eric Chang Dec 17 '15 at 15:29
3

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)
Eric Chang
  • 83
  • 1
  • 1
  • 5