Unit testing with pytest

Introduction to Testing in Python

Alexander Levin

Data Scientist

What is a unit test

Unit - the smallest working part that can be tested.

  • Examples of units: functions, methods, classes, modules, etc.

$$

Unit testing - software testing method.

  • Unit testing allows one to scrutinize the correctness of a unit.

$$

Test case - a set of unit inputs and expected outputs.

  • Test case summarizes a particular piece of the problem.
Introduction to Testing in Python

Why to use unit tests

Unit tests - are a foundation for testing "the bigger picture" of the software.

Use cases:

  • When bugs found
  • During development
  • After implemented changes
Introduction to Testing in Python

How to create a unit test

Step-by-step:

  1. Decide which units to test
  2. Define test cases (the creative part):
    • "What are the possible unit outcomes?"
    • "How can one use the unit?"
    • "How should the unit behave in all those cases?"
  3. Write code for each test case
  4. Run the tests and analyze the results
Introduction to Testing in Python

Creating a unit test: example

Unit to test:

# Function for a sum of elements
def sum_of_arr(array:list) -> int:
    return sum(array)

Test cases:

  1. Input is a list of numbers (as expected) - should return the sum
  2. Input is an empty list - should return 0
  3. Input is a list containing one number - should return the number
Introduction to Testing in Python

Creating a unit test: code

# Test Case 1: regular array
def test_regular():
    assert sum_of_arr([1, 2, 3]) == 6
    assert sum_of_arr([100, 150]) == 250
# Test Case 2: empty list
def test_empty():
    assert sum_of_arr([]) == 0
# Test Case 3: one number
def test_one_number():
    assert sum_of_arr([10]) == 10
    assert sum_of_arr([0]) == 0
Introduction to Testing in Python

Summary

Unit test - a test that verifies that a unit works as expected.

Test case - inputs and outputs summarizing a particular piece of the problem.

Use cases:

  • When bugs found
  • During development
  • After implemented changes

Defining test cases - involves creativity.

Introduction to Testing in Python

Let's practice!

Introduction to Testing in Python

Preparing Video For Download...