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():