wolever / parameterized

Parameterized testing with any Python test framework
Other
833 stars 105 forks source link

How to define a dynamic filename for parametrized tests for py.test? #140

Open alex4200 opened 2 years ago

alex4200 commented 2 years ago

In a py.test code I can specify some file that can be used for some tests. So in the conftest.py I define

def pytest_addoption(parser):
    """Defines the extra options for the MOOC tests."""
    parser.addoption(
        "--tests",
        help="Defines the json files containing the test parameters.",
    )

@pytest.fixture
def testfile(request):
    """Returns True if driver should run headless."""
    return request.config.getoption("--tests")

so I have a fixture which represents a filename.

Now in the test itself I want to use this filename to parametrize a test as follows:

from parameterized import parameterized

    @parameterized(
        param.explicit(*json.loads(line))
        for line in open(testfile)
    )
    def test_1(testparam):
         ...

but that does not work as the fixture testfile does not seem to be defined/accessible in "front of" a test method. Is there any way to define testfile in a dynamic way?

alexlausz commented 1 year ago

In a py.test code I can specify some file that can be used for some tests. So in the conftest.py I define

def pytest_addoption(parser):
    """Defines the extra options for the MOOC tests."""
    parser.addoption(
        "--tests",
        help="Defines the json files containing the test parameters.",
    )

@pytest.fixture
def testfile(request):
    """Returns True if driver should run headless."""
    return request.config.getoption("--tests")

so I have a fixture which represents a filename.

Now in the test itself I want to use this filename to parametrize a test as follows:

from parameterized import parameterized

    @parameterized(
        param.explicit(*json.loads(line))
        for line in open(testfile)
    )
    def test_1(testparam):
         ...

but that does not work as the fixture testfile does not seem to be defined/accessible in "front of" a test method. Is there any way to define testfile in a dynamic way?

Facing the same problems

wolever commented 1 year ago

Hey! That's a great question, and I'm not sure I know of a good solution right now.

Getting pytest fixtures playing nicely with parameterized is an open issue, and I suspect that would solve this problem.

And in the meantime, a functional but potentially less good solution could be to pass in parameters with an environment variable:

$ cat test.py
…
@parameterized(json.loads(os.environ["DATA_FILE"]))
def test_data_file(…):
   …
…
$ DATA_FILE=foo.json pytest