Fixtures Teardowns

Introduction to Testing in Python

Alexander Levin

Data Scientist

What is a fixture teardown

  • Fixture Teardown - a process of cleaning up ("tearing down") resources that were allocated or created during the setup of a testing environment.

Recall the "picnic" analogy:

  1. Invite our friends and prepare the food
  2. Have fun!
  3. Clean up - that's the teardown
Introduction to Testing in Python

Why to use teardowns

It is important to clean the environment at the end of a test. If one does not use teardown, it can lead to significant issues:

  • Memory leaks
  • Low speed of execution and performance issues
  • Invalid test results
  • Pipeline failures and errors
Introduction to Testing in Python

When to use

When to use:

  • Big objects
  • More than one test
  • Usage of autouse

When it is not necessary to use:

  • One simple script with one test
Introduction to Testing in Python

Lazy evaluation in Python

  • yield - is a Python keyword, which allows to create generators
# Example of generator function
def lazy_increment(n):
    for i in range(n):
        yield i
f = lazy_increment(5)
next(f) # 0
next(f) # 1
next(f) # 2
Introduction to Testing in Python

How to use

How to use:

  • Replace return by yield
  • Place the teardown code after yield
  • Make sure that the setup code is only before yield
Introduction to Testing in Python

Teardown example

@pytest.fixture
def init_list():
    return []

@pytest.fixture(autouse=True)
def add_numbers_to_list(init_list):
    # Fixture Setup
    init_list.extend([i for i in range(10)])
    # Fixture output
    yield init_list
    # Teardown statement
    init_list.clear()

def test_9(init_list):
    assert 9 in init_list
Introduction to Testing in Python

Summary

  • Definition: Fixture Teardown - is a process of cleaning up resources that were allocated during the setup.
  • Usage:
    • The yield keyword instead of return
    • Teardown code after yield
  • Advantages:
    • Prevents software failures
    • Prevents potential drops of performance
  • When to use: Always, when you have more than one test!
Introduction to Testing in Python

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...