HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

6) Testing Lesson

Python Test setup() and tearDown()

3 min to complete · By Martin Breuss

Sometimes, you might need a variable, such as the BASE_URL, in more than just one of the test cases. Or you might need a data structure that you want to edit in multiple tests to see whether your code handles it as expected.

Avoid Code Repition

You don't need to explicitly write code for these repeating elements in each test method. Instead, you can use conventional methods of the unittest.TestCase() class that helps you avoid unnecessary repetition:

  • .setUp() executes before every single test case
  • .tearDown() executes after every single test case

You can use these methods to reduce the amount of code you need to type in your test suite. Following the DRY principle also makes it easier to change code in one place and have the effects of the change apply everywhere it's needed.

Single-Out Repeating Code

When writing tests for your web scraper script, you might have defined a variable for the index URL or for an individual recipe URL multiple times. Instead of defining such information in every test method, you can define it only once in the .setUp() method:

import unittest
import rescrape


class TestRescrape(unittest.TestCase):

    def setUp(self):
        self.BASE_URL = "https://codingnomads.github.io/recipes/"
        self.url = f"{self.BASE_URL}recipes/11-making-my-own-baguet.html"

    # snip

As mentioned further up, the .setUp() method will run before every test, which means that these two variables will be available for each test to use.

The corresponding .tearDown() method can also be useful, and it executes after each test case. You might need a method like that to close any sort of database connection or recreate an initial state that you want your other tests to run against.

Summary: Efficient Testing Python

  • The unittest framework provides additional functionality to make your testing more convenient and more stable
  • .setUp() executes before every single test case
  • .tearDown() executes after every single test case
  • These functions make it easier to read and maintain tests