Chapter 3
Chapter 3
pytest
INTRODUCTION TO TESTING IN PYTHON
Alexander Levin
Data Scientist
What is a unit test
Unit - the smallest working part that can be tested.
Use cases:
Test cases:
Test case - inputs and outputs summarizing a particular piece of the problem.
Use cases:
During development
Alexander Levin
Data Scientist
What is a feature test
Feature Examples:
Data distribution check
a software system functionality.
Report preparation
satisfies a particular user's requirement.
Features
Feature testing
One unit does not work - does not mean the feature is NOT OK.
Vice versa:
All units work as expected - does not mean the feature is OK.
# Setup
import pandas as pd
import pytest
df = pd.read_csv('laptops.csv')
# Filter feature
def filter_data_by_manuf(df, manufacturer_name):
filtered_df = df\
[df["Manufacturer"] == manufacturer_name]
return filtered_df
Feature testing helps to ensure that users get exactly what they expect.
The key to design feature tests - to understand what the features are in a specific system.
Alexander Levin
Data Scientist
What is integration testing?
Integration testing - software testing method, that allows to verify that an interaction
behaves normally.
Power cable
Internet connection
Database connection
Lost connection
Loss of data
Interaction delays
Low bandwidth
Version conflicts
Interface mismatch
Others
@pytest.fixture
def setup_file():
# Create temporary file
file = "test_file.txt"
with open(file, "w") as f1:
f1.write("Test data 1")
yield file
os.remove(file)
def test_fs(setup_file):
file = setup_file
# Check that the file was created successfully
assert os.path.exists(file)
Alexander Levin
Data Scientist
What is performance testing
Performance - how efficiently does software utilizes the resources of the system to
accomplish a task.
Other resources
# Example_1.py
import time
def test_func(benchmark):
benchmark(time.sleep, 1)
CLI Command:
pytest Example_1.py
CLI Command:
pytest Example_2.py