Register to get access to free programming courses with interactive exercises

Data preparation Python: Automated testing

Most tests that test a given functionality are very similar, especially in initial data preparation. In the last lesson, each test started with the line: stack = []. It isn't duplication yet, but it's a step in a dangerous direction.

This lesson will learn how to prevent duplication when preparing identical data for different tests. Let's say we are developing the funcy library, which provides functions for working with collections in Python.

Among them, we can find such functions as:

  • compact
  • select
  • flatten

How do we test them? For these functions to work, you need a prepared collection. Let's create the necessary collection, pass it to the function, and look at the result:

def test_compact():
    # Preparing a collection of `coll`
    coll = ['One', True, 3, [1, 'hexlet', [0]], 'cat', {}, '', [], False]

    # Using `coll` for testing
    result = compact(coll)
    assert result == # Here is the expected value

Then we'll do the same for all the other functions:

def test_select():
    # The same collection, there is a duplication
    coll = ['One', True, 3, [1, 'hexlet', [0]], 'cat', {}, '', [], False]

    # Using `coll` for testing
    result = select(coll)
    assert result == # Here is the expected value

Next, we perform this operation for all other tested functions. The collection initialization fragment will start moving from place to place, generating more and more of the same code.

The easiest way to avoid this is to move the collection definition to the module level:

# We describe the creation of the collection in one place for all functions
coll = ['One', True, 3, [1, 'hexlet', [0]], 'cat', {}, '', [], False]

def test_compact():

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

<span class="translation_missing" title="translation missing:">Bookmate</span>
<span class="translation_missing" title="translation missing:">Healthsamurai</span>
<span class="translation_missing" title="translation missing:">Dualboot</span>
<span class="translation_missing" title="translation missing:">Abbyy</span>
Suggested learning programs
Developing web applications with Django
10 months
from scratch
under development
Start at any time

Use Hexlet to the fullest extent!

  • Ask questions about the lesson
  • Test your knowledge in quizzes
  • Practice in your browser
  • Track your progress

Sign up or sign in

By sending this form, you agree to our Personal Policy and Service Conditions
Toto Image

Ask questions if you want to discuss a theory or an exercise. Hexlet Support Team and experienced community members can help find answers and solve a problem.