5 Simple Techniques To Resolve The Pytest Fixture Not Found Error

Fixtures are one of Pytest’s most powerful features.

They help manage setup and teardown of test resources such as database connections, network connections, initializing classes and so on.

But have you ever experienced the dreaded “Pytest fixture not found” error?

You’ve checked your code and tests a million times but cannot figure it out? The result - Your testing comes to a complete halt!

This error can stem from various causes, including naming problems with functions and files, misplacement of conftest.py, and other factors. Accurately identifying the issue is essential for resolving it and re-running your tests.

In this article, we’ll discuss the Pytest fixture not found error in detail. We’ll examine the reasons behind this problem and explore effective solutions to resolve it.

You’ll come out the other side with a better understanding of common Pytest fixture errors and how to solve them.

Take a deep breath and let’s dive in.

Example Code

What You’ll Learn

By the end of this article, you should be able to:

  • Understand the scenarios that can lead to the fixture not found error in Pytest.
  • Diagnose and troubleshoot the error Pytest fixture not found error.
  • Optimize your testing workflow by utilizing Pytest fixtures

What are Pytest Fixtures?

Before we start, let’s take a look at a quick intro to Pytest fixtures.

Pytest Fixtures allow you to set up necessary prerequisites for running your tests, such as managing resources, data, and dependencies, before executing tests. They help provide a well-organized and efficient testing environment.

Fixtures are defined using the @pytest.fixture decorator. Mainly used to set up preconditions for tests, share data across tests or test modules, or initiate teardown tasks after the test is finished.

Here is quick example of Pytest fixture:

1
2
3
4
5
6
7
8
9
10
11
from src.network_manager import network_manager

@pytest.fixture
def network_connection():
net_connect = network_manager()
yield net_connect
# Teardown code

# Function to check network
def test_network_connection(network_connection):
assert network_connection == True

Here, the network_connection() fixture creates an object of the network_manager class. We pass this fixture to the test_network_connections() function to test the network connection.

The code after yield is the fixture teardown bit (e.g. closing database connections, deleting files, etc.).

You can learn more about this in our article on Pytest Fixture Setup and Teardown.

Autouse in Fixtures

Sometimes there are fixtures on which all your tests depends. You can make these fixtures available to all test models by setting autouse=True.

Autouse offers a convenient way to have all tests automatically request and utilize them.

Scopes in Fixtures

When you define a fixture, it is available to all tests in the test module. But sometimes you may want to limit the scope of a fixture to a specific test or test class.

Pytest fixtures also allow you to determine the lifetime and availability of a fixture. These are done via fixture scopes:

  • function - This is the default scope. It defines that the fixture will be created at the beginning of a test function and torn down at the end of the function.
  • class - This scope defines that the fixture will be created at the beginning of a class and torn down at the end of the class.
  • module - This scope defines that the fixture will be created at the beginning of a module and torn down at the end of the module.
  • session - This scope defines that the fixture will be created at the beginning of a session and torn down at the end of the session.

It’s important to choose the right scope for your test needs, if you need assistance, this article on Pytest fixture scopes is a great resource.

Troubleshooting Pytest Fixture not found error

But that is not the only cause of this error. Let’s quickly outline the steps to follow if you encounter the “Pytest fixture not found” error.

1. Check fixture name and test function argument

An error in the fixture name is a common mistake. Check to see if you’ve made any errors in fixture naming or if you’ve defined multiple functions with the same name as a fixture. Examine the code block below.

1
2
3
4
5
6
7
8
9
from datetime import date

@pytest.fixture
def get_current_date():
curr_date = date.today()
return date

def test_get_date(current_date):
assert get_current_date = date.today()

You may notice that we passed the fixture current_date in the function test_get_date. But we defined the fixture as get_current_date. This will cause the “fixture not found” error.

2. Check the location of conftest.py

This is another error that can lead to a Pytest fixture not found error. conftest.py used to define hooks, fixtures, and other necessary configuration options that can be shared across multiple test files.

When you use conftest.py file, Pytest automatically discovers and applies its contents to the tests within that directory and its subdirectories.

If you name the conftest.py as conf.py or place the conftest.py file in an invalid directory, Pytest is not able to find the fixture you defined and can lead the the Fixture not found error. So, make sure to place the conftest file in the correct directory.

If you need a refresher on conftest.py and how to use it, this article is a great start.

3. Clear the cache

In some cases, the Pytests cache can lead fixture fixture-related issues. So clear the cache with the command defined below and try again.

1
pytest --cache-clear

4. Check fixture parameters

Parameterized fixtures allow you to accept one or more arguments and can be initialized at runtime.

If you’re using a parameterized fixture, double-check the parameters you’ve passed to the fixture.

If you pass the wrong number of parameters or pass the parameters in the wrong order, it can lead to the “fixture not found” error.

5. Check file organization

File organization is essential for Pytest.

Pytest looks for files starting with test_* under the /tests directory. You can override this using the --rootdir option or specifying the directory in the pytest.ini file.

Bonus: Check fixture scope

If you’re using a fixture with a scope, ensure that you’ve specified the fixture name as an argument in the test function. If you don’t specify the fixture name as an argument, Pytest will not be able to find the fixture and will throw the “fixture not found” error.

Bonus: Install fixture plugins

Pytest has a rich ecosystem of plugins that can help you write better tests. Some popular plugins include pytest-mock, pytest-cov, pytest-html, and pytest-xdist.

For example, if you fail to install the pytest-mock plugin, you’ll get the “fixture ‘mocker’ not found” error. This article covers how to debug this error in detail.

You can read more about the popular Pytest plugins here.

Fixture in Test Classes

To define a fixture for a specific test class, you can define the fixture inside the targeted class and set the fixture scope=”class”. Also, decorate the class with @pytest.mark.usefixtures. Here is a quick example,

1
2
3
4
5
6
7
8
9
@pytest.mark.usefixtures("web_driver")
class Base(unittest.TestCase):

@pytest.fixture(scope="class")
def web_driver(self, request):
driver = webdriver.Chrome("C:/chromedriver.exe")
request.cls.driver = driver
yield
driver.close()

Project Setup

Let’s look at a real scenario on how the Pytest fixture not found error occurs and how to address it.

First, let’s set up our test environment to simulate the error.

Pre-requisite

To follow this guide, you should have:

  • Python 3.11+ installed (recommend installing via Conda).
  • An elementary grasp of Python and Pytest.

Getting Started

This is how our example repo looks like,

pytest-fixture-not-found

To get started. clone the Github Repo here, or you can create your own repo by creating a folder and running git init to initialize it.

Example Code

We’ll start with a very simple example containing a few database functions.

src/database_manager.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import sqlite3

class database_operation:
def __init__(self, dbname: str) -> None:
self.mydb = sqlite3.connect(dbname)
self.cursor = self.mydb.cursor()

def check_connection(self):
"""
Function to check connection.
"""
if self.mydb.cursor:
return True
else:
return False

def execute_sql(self, sql: str):
"""
Function to execute SQL query.
"""
self.cursor.execute(sql)
return True

def get_table_data(self, sql: str):
"""
Function to get data from table.
"""
result = self.cursor.execute(sql)
return result

We created functions for simple database queries like checking connections, executing sql, and getting data from tables.

Test code

Let’s write some test code for our example code.

test/test_database_manager.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import pytest
from src.database_manager import database_operation

# Fixture to initialize database.
@pytest.fixture
def initialize_db():
db = database_operation("player.db")
return db

# Testing connection
def test_connection(initialize_database): # We intentionally made a mistake here with the name of the fixture to demonstrate the error.
db = initialize_database
assert db.check_connection() == True

# Testing execute_sql function
def test_execute_sql(initialize_database):
db = initialize_database
# Creating table
sql = """ CREATE TABLE Player (
Name CHAR(70) NOT NULL,
score INT
); """
assert db.execute_sql(sql) == True
# Inserting data
sql = """INSERT INTO Player VALUES ('Alen', 120)"""
assert db.execute_sql(sql) == True

# Testing get_table_data function
def test_get_table_data(initialize_database):
db = initialize_database
sql = '''SELECT * FROM Player'''
assert db.get_table_data(sql) != None

We have defined various test functions to test functions from our example code.

Let’s proceed.

Result Analysis

Finally, it’s time to run the test on our code.

1
pytest -v

Output result:

pytest-fixture-not-found

As you can see we got an error fixture 'initialize_database' not found.

Let’s fix it.

Why you’re getting this?

Before we fix the error, we must understand why this error has occurred.

You can see that we have created our fixture with a name, initialize_db but used the name initialize_database when passing the fixture to the function.

Now when your test begins, Pytest found that the fixture initialize_database is not defined anywhere in the test file. This causes the “fixture not found” error.

How to solve it?

Now that we understand the cause of the error, let’s fix it.

To solve this error, we have two options here. We can either rename our fixture with the same name that we passed to the functions or change the name passed to the functions to match the fixture that has already been created.

Here is the fixed version of the code:

test/test_database_manager.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import pytest
from src.database_manager import database_operation

# Fixture to initialize database. We intentionally made a mistake here with the name of the fixture to demonstrate the error.
@pytest.fixture
def initialize_database():
db = database_operation("player.db")
return db

# Testing connection
def test_connection(initialize_database):
db = initialize_database
assert db.check_connection() == True

# Testing execute_sql function
def test_execute_sql(initialize_database):
db = initialize_database
# Creating table
sql = """ CREATE TABLE Player (
Name CHAR(70) NOT NULL,
score INT
); """
assert db.execute_sql(sql) == True
# Inserting data
sql = """INSERT INTO Player VALUES ('Alen', 120)"""
assert db.execute_sql(sql) == True

# Testing get_table_data function
def test_get_table_data(initialize_database):
db = initialize_database
sql = '''SELECT * FROM Player'''
assert db.get_table_data(sql) != None

Here we rename our fixture with the same name that we passed to the test functions.

Now the test result will look like this,

pytest-fixture-not-found

The database will look like,

pytest-fixture-not-found

Tips to prevent the Pytest fixture not found error

Let’s take a look at some quick tips that will help you prevent the Pytest “fixture not found” error and write error-free, clean code:

  • Make sure that fixture names do not overlap with function names.
  • Ensure to specify the fixture name as arguments in the test functions or set the autouse=True option in the fixture definition.
  • If you plan to share fixtures across multiple test modules, define it in conftest.py. It will make that fixture available across all the test modules and files.
  • Ensure that conftest.py file is placed in the correct directory and discoverable by all unit test modules.
  • Check that you’ve placed all your test files inside the /test directory.
  • Check that you’ve installed all necessary plugins.

Sharing Fixtures Across Multiple Test Modules

When you have multiple test files with several test functions, and they require some common fixtures, you can use conftest.py to declare the fixtures.

The fixtures defined in conftest.py will act as global fixtures that you can use across your tests and modules.

Let’s take a look at a quick step with examples to see how it works,

Step-1: Create a conftest.py file inside your test root directory - tests/.
Step-2: Define the fixtures in the conftest.py like the below,

tests/conftest.py

1
2
3
4
5
6
from src.network_manager import network_manager

@pytest.fixture
def network_connection():
net_connect = network_manager()
yield net_connect

Now the fixture network_connection() is available globally and you can import this fixture to all your test files and function as usually you do when defining fixture inside each test file.

1
2
3
4
5

### test_file.py
# Function to check network
def test_network_connection(network_connection):
assert network_connection == True

Final Thoughts

The article introduces us to the Pytest fixture not found error in brief.

First, we discussed some basics about Pytest fixtures and touched on autouse in Pytest fixtures.

Then, we saw an example that triggers the Pytest fixture not found error. We looked at why this error occurred and how to fix it.

We also described some troubleshooting techniques that will be helpful to you when you encounter the fixture not found error.

Lastly, we discussed the use of the conftest.py file and provided some helpful tips for writing error-free code.

Pytest fixtures are an amazing tool in Pytest. If you’re experiencing the fixture not found error, you may find it helpful to follow the checks defined in this article to help resolve it.

This article may save you time to fix errors caused by fixtures. Happy coding.

If you have any ideas for improvement or like me to cover any topics please comment below or send me a message via Twitter, GitHub or Email.

Additional Learning

Example Code Repository
Pytest Fixtures
Fixture errors
Autouse fixtures (fixtures you don’t have to request)
How Pytest Fixtures Can Help You Write More Readable And Efficient Tests
What Are Pytest Fixture Scopes?
Pytest Conftest With Best Practices And Real Examples
What is Setup and Teardown in Pytest? (Importance of a Clean Test Environment)
8 Useful Pytest Plugins To Make Your Python Unit Tests Easier, Faster and Prettier
How To Easily Resolve The “Fixture ‘Mocker’ Not Found” Error in Pytest
A Step-by-Step Guide To Using Pytest Fixtures With Arguments