Register to get access to free programming courses with interactive exercises

Bad and good testing practices Python: Automated testing

Like any other code, you can write tests in many ways, including terrible ones. In addition to some general coding practices and standards, tests have their peculiarities that you need to know about. In this lesson, we'll go over some of them.

Tests affecting each other

One of the most important rules is that tests should not interfere with each other. It means each test should run as if no other test existed. It's easy to break this rule. One test may create a file, change a variable, or write something to the database.

If any of the other tests stumble upon these changes, they may not work:

  • Fail where they shouldn't
  • Pass where they shouldn't

In addition, this situation also means uncertainty. Such tests may crash for no apparent reason. For example, when the test runs in isolation, it works, but when the other tests run in parallel, it crashes:

user = None

def test_first():
    user = { 'name': 'Vasya' }
    # Here is the test logic

def test_second():
    # We use a user created by another test
    # This test depends on how the previous test works
    # It cannot work without running both tests in sequence
    user["name"] = 'Petya'

This situation is common in tests that actively interact with the external environment, such as a database or file system. Testing side effects has its tricks, which we'll look at in the advanced testing course.

Conditional constructions in tests

Let us observe the code:

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.