Fixtures autouse

Introduction to Testing in Python

Alexander Levin

Data Scientist

Autouse argument

  • An optional boolean argument of a fixture
  • Can be passed to the fixture decorator
  • When autouse=True the fixture function is executing regardless of a request
  • Helps to reduce the amount of redundant fixture calls
Introduction to Testing in Python

When to use

In case we need to apply certain environment preparations or modifications for all tests.

For example, when we want to guarantee, that all tests:

  • Have the same data
  • Have the same connections (data, API, etc.)
  • Have the same environment configuration
  • Have a monitor, logging, or profiling

All such cases should be addressed with an "autouse" argument.

Introduction to Testing in Python

Autouse example

Example of an "autoused" fixture:

import pytest
import pandas as pd

# Autoused fixture
@pytest.fixture(autouse=True)
def set_pd_options():
    pd.set_option('display.max_columns', 5000)

# Test function
def test_pd_options():
    assert pd.get_option('display.max_columns') == 5000
Introduction to Testing in Python

Autouse incorrect example

Incorrect example of an "autoused" fixture:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture(autouse=True)
def wrong_fixture():
    return [1,2,3,4,5]

# Test function
def test_type():
    assert type(wrong_fixture) == list

Corrected example of the fixture:

import pytest
import pandas as pd

# Wrong autoused fixture
@pytest.fixture
def correct_fixture():
    return [1,2,3,4,5]

# Test function
def test_type(correct_fixture):
    assert type(correct_fixture) == list
Introduction to Testing in Python

Autouse example: output

Output of the example:

autouse example output

Introduction to Testing in Python

Summary

  • Definition of autouse: An optional boolean argument of a fixture decorator
  • Usage: @pytest.fixture(autouse=True)
  • Advantage: Helps to reduce the number of redundant fixture calls, thus makes the code simpler
  • Feature: autouse=True the fixture function is executing regardless of a request
  • When to use: in case we need to apply certain environment preparations or modifications
  • Use cases examples:
    • Reading and preparing data for all tests
    • Configuring connections and environment parameters
    • Implementing a monitor, a logger, or a profiler
Introduction to Testing in Python

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...