Практические примеры

Введение в тестирование на Python

Alexander Levin

Data Scientist

Данные и конвейер

Данные: зарплаты в сфере науки о данных.

Каждая строка содержит информацию о специалисте: зарплату, должность и другие атрибуты.

ds salaries table

Конвейер для вычисления средней зарплаты:

  1. Считать данные
  2. Отфильтровать по типу занятости
  3. Вычислить среднюю зарплату
  4. Сохранить результаты
Введение в тестирование на Python

Код конвейера

import pandas as pd

# Fixture to get the data
@pytest.fixture
def read_df():
    return pd.read_csv('ds_salaries.csv')
# Function to filter the data
def filter_df(df):
    return df[df['employment_type'] == 'FT']
# Function to get the mean
def get_mean(df):   
    return df['salary_in_usd'].mean()
Введение в тестирование на Python

Интеграционные тесты

Тест-кейсы:

  • Чтение данных
  • Запись в файл

Код:

def test_read_df(read_df):
    # Check the type of the dataframe
    assert isinstance(read_df, pd.DataFrame)
    # Check that df contains rows
    assert read_df.shape[0] > 0
Введение в тестирование на Python

Интеграционные тесты

Пример проверки создания файлов средствами Python.

def test_write():
    # Opening a file in writing mode
    with open('temp.txt', 'w') as wfile:
        # Writing the text to the file
        wfile.write('Testing stuff is awesome')
    # Checking the file exists
    assert os.path.exists('temp.txt')
    # Don't forget to clean after yourself
    os.remove('temp.txt')
Введение в тестирование на Python

Юнит-тесты

Тест-кейсы:

  • Отфильтрованный набор данных содержит только тип занятости 'FT'
  • Функция get_mean() возвращает число

Код:

def test_units(read_df):
    filtered = filter_df(read_df)
    assert filtered['employment_type'].unique() == ['FT']
    assert isinstance(get_mean(filtered), float)
Введение в тестирование на Python

Тесты признаков

Тест-кейсы:

  • Среднее значение больше нуля
  • Среднее значение не превышает максимальную зарплату в наборе данных

Код:

def test_feature(read_df):
    # Filtering the data
    filtered = filter_df(read_df)
    # Test case: mean is greater than zero
    assert get_mean(filtered) > 0
    # Test case: mean is not bigger than the maximum
    assert get_mean(filtered) <= read_df['salary_in_usd'].max()
Введение в тестирование на Python

Тесты производительности

Тест-кейсы:

  • Время выполнения конвейера от начала до конца

Код:

def test_performance(benchmark, read_df):
    # Benchmark decorator
    @benchmark
    # Function to measure
    def get_result():
        filtered = filter_df(read_df)
        return get_mean(filtered)
Введение в тестирование на Python

Итоговый набор тестов

import pytest

## Integration Tests
def test_read_df(read_df):
      # Check the type of the dataframe
    assert isinstance(read_df, pd.DataFrame)
    # Check that df contains rows
    assert read_df.shape[0] > 0
def test_write():
    with open('temp.txt', 'w') as wfile:
        wfile.write('12345')
    assert os.path.exists('temp.txt')
    os.remove('temp.txt')

## Unit Tests
def test_units(read_df):
    filtered = filter_df(read_df)
    assert filtered['employment_type'].unique() == ['FT']
    assert isinstance(get_mean(filtered), float)
## Feature Tests
def test_feature(read_df):
    # Filtering the data
    filtered = filter_df(read_df)
    # Test case: mean is greater than zero
    assert get_mean(filtered) > 0
    # Test case: mean is not bigger than the maximum
    assert get_mean(filtered) <= read_df['salary_in_usd'].max()

## Performance Tests
def test_performance(benchmark, read_df):
    # Benchmark decorator
    @benchmark
    # Function to measure
    def pipeline():
        filtered = filter_df(read_df)
        return get_mean(filtered)
Введение в тестирование на Python

Давайте потренируемся!

Введение в тестирование на Python

Preparing Video For Download...