Reputation: 147
I have a simple Python library, for which I use the following command to run tests:
python setup.py pytest
The following test works as expected:
def test_out():
assert 1 == 2
Test result:
platform linux -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /media/drive2/src
collected 1 item
tests/test_error.py F
However, when @pytest.fixture
is added, the test is not executed:
import pytest
@pytest.fixture
def test_out():
assert 1 == 2
Test result:
platform linux -- Python 3.10.4, pytest-7.1.2, pluggy-1.0.0
rootdir: /media/drive2/src
collected 0 items
What is the reason for this behavior, and how can @pytest.fixture
be added in a way that won't prevent the test from running?
(I want to use capsys.readouterr()
, so I believe @pytest.fixture
is needed.)
Upvotes: 2
Views: 961
Reputation: 1178
First of all, pytest.fixture
is a decorator, so it is affecting the function below, and the right way to use it is to put them together (no empty lines in between), like this:
import pytest
@pytest.fixture
def test_out():
assert 1 == 2 # This still makes no sense, see answer below
@pytest.fixture
just indicates that the return value of the decorated function will be use as parameter in other test function. (The decorated function will not run as a test).
From the pytest documentation:
“Fixtures”, in the literal sense, are each of the arrange steps and data. They’re everything that test needs to do its thing.
Here is an example similar to your test using a fixture:
import pytest
@pytest.fixture
def my_number():
return 2
def test_out(my_number):
assert 1 == my_number # This will fail
When you create the fixture my_number
the retorned value can be use as parameter in other test functions (in this case in test_out
).
This is usefull when you have to create the same stuff in several tests. Instead of repeating the code in each test you can make a fixture.
Upvotes: 2