Autousing pytest fixtures defined in a separate module

Question:

I have the following file tree in my project:

...
tests/
    __init__.py
    test_abc.py
...

I have a fixture defined in __init__.py:

@pytest.fixture(autouse=True)
def client():
    return TestClient()

I want to use this fixture in test_abc.py:

from . import client

def test_def():
    client.get(...) # Throws an error

How can I use my autouse fixture in my test methods from another modules without passing an explicit reference to the fixture, or using a pytest decorator?

Asked By: linkyndy

||

Answers:

Autouse is meant for fixtures which do some setup required by all tests, and may or may not return something still useful as a fixture to be used by tests.

Tests which want to access what is returned by the fixture have to declare the fixture as a parameter, so they can access it. So if your tests want to access the fixture, they have to declare it as a parameter, that’s how pytest works. Hope this helps.

Answered By: Bruno Oliveira

You will have to put your fixture into the conftest.py file and set the scope to something like @pytest.fixture(scope="module") so that it’s invoked once per test module.

From the pytest docs on sharing fixtures across classes, modules, packages or session, it says:

"The next example puts the fixture function into a separate conftest.py file so that tests from multiple test modules in the directory can access the fixture function"

# content of conftest.py
import pytest
import smtplib


@pytest.fixture(scope="module")
def smtp_connection():
    return smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
# content of test_module.py


def test_ehlo(smtp_connection):
    response, msg = smtp_connection.ehlo()
    assert response == 250
    assert b"smtp.gmail.com" in msg
    assert 0  # for demo purposes


def test_noop(smtp_connection):
    response, msg = smtp_connection.noop()
    assert response == 250
    assert 0  # for demo purposes
Answered By: azizbro
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.