Register to get access to free programming courses with interactive exercises

Modular tests Python: Automated testing

The information we've looked at is already enough for everyday testing. Before we dive into more complex topics and features of Pytest, let's go through the testing path of the library. We'll talk about organizing tests and good and bad practices. It will help you get the right attitude towards testing in general.

What is unit testing

In this lesson, we'll analyze the basics of unit testing**. This type of testing examines program modules in isolation from all other parts. They test basic language constructs such as functions, modules, and classes. These tests don't guarantee that the entire application will work, but they help when a program module has complex logic.

Let's try to test a stack. You'll no doubt remember that a stack is a list of items organized by LIFO (Last In First Out). Typically, stacks themselves are often used to implement algorithms. Developers often use them in low-level code, such as within programming languages or operating systems:

stack = []  # Python implements stacks using lists
not stack  # The list is empty
# True
stack.append(1)  # [1]
stack.append(2)  # [1, 2]
stack.append(3)  # [1, 2, 3]
not stack  # The list is not empty
# False
# [1, 2, 3]
stack.pop()  # In the stack [1, 2]
# 3
stack.pop()  # In the stack [1]
# 2
stack.pop()  # The stack is empty
# 1
not stack
# True

Testing basic features

Let's write our first test. The first test should always check a positive scenario, one that involves the main functionality of the component:

def test_stack():
    stack = []

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.