Fixtures in unittest

Introduction to Testing in Python

Alexander Levin

Data Scientist

Fixtures recap

  • Fixture
    • a prepared environment for a test
    • separate the preparation from the test code
  • Fixture setup - setting up resources for tests
  • Fixture teardown - cleaning up ("tearing down") resources that were allocated
  • Example: preparing the food for a picnic and the cleaning at the end
Introduction to Testing in Python

Fixtures in the unittest library

  • Fixture in unittest - the preparaton needed to perform one or more tests
  • .setUp() - a method called to prepare the test fixture before the actual test
  • .tearDown() - a method called after the test method to clean the environment
1 https://docs.python.org/3/library/unittest.html
Introduction to Testing in Python

Example code

import unittest

class TestLi(unittest.TestCase):
    # Fixture setup method
    def setUp(self):
        self.li = [i for i in range(100)]

    # Fixture teardown method
    def tearDown(self):
        self.li.clear()

    # Test method
    def test_your_list(self):
        self.assertIn(99, self.li)
        self.assertNotIn(100, self.li)
Introduction to Testing in Python

Capital U and capital D

  • The correct syntax: setUp with capital U and tearDown with capital D.

    class TestLi(unittest.TestCase):
      # Fixture setup method
      def setUp(self):
          self.li = [i for i in range(100)]
    
      # Fixture teardown method
      def tearDown(self):
          self.li.clear()
    
Introduction to Testing in Python

Example output

The command: python3 -m unittest test_in_list.py

Output of a run with a .setUp() and .tearDown():

output of a run with a fixture

Introduction to Testing in Python

Incorrectly named methods

Output of a run with a .set_up():

output of a run with a fixture with a wrong name

Introduction to Testing in Python

Summary

  • Fixture in unittest - the preparation needed to perform one or more tests
  • To create a fixture:
    • Implement the .setUp() method
    • Implement the .tearDown() method
  • .setUp() - a method called to prepare the test fixture before the actual test.
  • .tearDown() - a method called after the test method to clean the environment.
Introduction to Testing in Python

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...