Reputation: 983
I have a simple test as shown below:
# contents of test_example
def test_addition(numbers):
assert numbers < 5
And below is my conftest
# contents of conftest
import pytest
@pytest.fixture(params=[1, 2, 3, 4])
def numbers(request):
return request.param
However now I want to test the numbers 5 and 6but not have to explicitly hardcode that. On command line, I would like to override the numbers test fixture with the numbers 5 and 6 such that:
py.test test_example.py --numbers=[5, 6]
I would expect the result of the above invocation to overwrite the conftest numbers test fixture with my test fixture created at command line and run test_addition() on 5 and 6 only.
How would I go about doing this?
Upvotes: 1
Views: 1158
Reputation: 3806
reading here you can
tests/conftest.py
def pytest_addoption(parser):
parser.addoption("--numbers", action="store", dest="numbers",
default="1,2,3,4")
def pytest_generate_tests(metafunc):
if 'number' in metafunc.fixturenames:
metafunc.parametrize("number", metafunc.config.option.numbers.split(','))
tests/test_1.py
def test_numbers(number):
assert number
so:
$ py.test tests/ -vv
=========================================
collected 4 items
test_1.py::test_numbers[1] PASSED
test_1.py::test_numbers[2] PASSED
test_1.py::test_numbers[3] PASSED
test_1.py::test_numbers[4] PASSED
and
$ py.test tests/ -vv --numbers=10,11
=========================================
collected 2 items
test_1.py::test_numbers[10] PASSED
test_1.py::test_numbers[11] PASSED
anyway please note here:
Warning:
This function must be implemented in a plugin and is called once at the beginning of a test run.
Implementing this hook from conftest.py files is strongly discouraged because conftest.py files are lazily loaded and may give strange unknown option errors depending on the directory py.test is invoked from.
so this code works if you run
py.test tests/
but not if
cd tests
py.test
Upvotes: 2