Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Test is not executed when pytest.fixture is used

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.)

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading