Introduction to fixtures

Introduction to Testing in Python

Alexander Levin

Data Scientist

What is a fixture

  • Fixture - a prepared environment that can be used for a test execution
  • Fixture Setup - a process of preparing the environment and setting up resources that are required by one or more tests

Imagine preparation for a picnic:

  1. Invite our friends and prepare the food (that's what fixtures do)
  2. Have fun!
  3. Clean up
Introduction to Testing in Python

Why do we need fixture

Fixtures help:

  • To make test setup easier
  • To isolate the test of the environmental preparation
  • To make the fixture code reusable
Introduction to Testing in Python

Fixture example: overview

Assume we have:

  • a Python list variable named data
  • data = [0, 1, 1, 2, 3, 5, 8, 13, 21]

And we want to test, that:

  • It contains 9 elements
  • It contains the elements 5 and 21
Introduction to Testing in Python

Fixture example: code

import pytest

# Fixture decorator
@pytest.fixture
# Fixture for data initialization
def data():
    return [0, 1, 1, 2, 3, 5, 8, 13, 21]

def test_list(data):
    assert len(data) == 9
    assert 5 in data
    assert 21 in data
Introduction to Testing in Python

Fixture example: output

Output of the example: output of the fixture example

Introduction to Testing in Python

How to use fixtures

To use the fixture we have to do the following:

  1. Prepare software and tests
  2. Find "environment preparation"
  3. Create a fixture:
    • Declare the @pytest.fixture decorator
    • Implement the fixture function
  4. Use the created fixture:
    • Pass the fixture name to the test function
    • Run the tests!
Introduction to Testing in Python

Summary

We learned about testing fixtures:

  • Fixture - a prepared environment that can be used for a test execution
  • We use fixtures to make test setup easier and isolated from the test functions
  • Simple example: preparation of a Python list
  • Define a pytest fixture by declaring @pytest.fixture
    • followed by a fixture function
  • Fixture names are used in the tests as variables
Introduction to Testing in Python

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...