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: