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
stack
# [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 = []