Тестування вашого пакета

Розроблення пакетів Python

James Fulton

Climate informatics researcher

Мистецтво й дисципліна тестування

Уявіть, що ви працюєте над цією функцією

def get_ends(x):
    """Get the first and last element in a list"""
    return x[0], x[-1]

Її варто протестувати, щоб переконатися, що все працює

# Перевірка функції
get_ends([1,1,5,39,0])
(1, 0)
Розроблення пакетів Python

Мистецтво й дисципліна тестування

Хороші пакети хваляться кількістю тестів

  • 91% коду пакета pandas покрито тестами Значок покриття Pandas: 91% функцій протестовано
Розроблення пакетів Python

Написання тестів

def get_ends(x):
    """Get the first and last element in a list"""
    return x[0], x[-1]
def test_get_ends():
    assert get_ends([1,5,39,0]) == (1,0)
test_get_ends()


Розроблення пакетів Python

Написання тестів

def get_ends(x):
    """Get the first and last element in a list"""
    return x[0], x[1]
def test_get_ends():
    assert get_ends([1,5,39,0]) == (1,0)
test_get_ends()
AssertionError: 
...
Розроблення пакетів Python

Написання тестів

def get_ends(x):
    """Get the first and last element in a list"""
    return x[0], x[-1]
def test_get_ends():
    assert get_ends([1,5,39,0]) == (1,0)
    assert get_ends(['n','e','r','d']) == ('n','d')
Розроблення пакетів Python

Організація тестів у пакеті

mysklearn/
|-- mysklearn   <-- пакет
|-- tests       <-- каталог тестів
|-- setup.py
|-- LICENSE
|-- MANIFEST.in
Розроблення пакетів Python

Організація тестів у пакеті

Структура каталогу з тестами

mysklearn/tests/
|-- __init__.py
|-- preprocessing

| |-- __init__.py | |-- test_normalize.py
| |-- test_standardize.py |-- regression | |-- __init__.py | |-- test_regression.py |-- test_utils.py

Структура каталогу з кодом

mysklearn/mysklearn/
|-- __init__.py
|-- preprocessing

| |-- __init__.py | |-- normalize.py
| |-- standardize.py |-- regression | |-- __init__.py | |-- regression.py |-- utils.py
Розроблення пакетів Python

Організація тестового модуля

У файлі test_normalize.py

from mysklearn.preprocessing.normalize import (
    find_max, find_min, normalize_data
)

def test_find_max(x):
    assert find_max([1,4,7,1])==7

def test_find_min(x):
    assert ...

def test_normalize_data(x):
    assert ...

DataCamp: Unit testing for data science

У файлі normalize.py

def find_max(x):
    ...
    return x_max

def find_min(x):
    ...
    return x_min

def normalize_data(x):
    ...
    return x_norm
Розроблення пакетів Python

Запуск тестів із pytest

pytest
  • pytest шукає всередині каталогу test
  • Шукає модулі на кшталт test_modulename.py
  • Шукає функції на кшталт test_functionname()
  • Запускає ці функції й показує результат
mysklearn/ <-- перейдіть сюди
|-- mysklearn
|-- tests
|-- setup.py
|-- LICENSE
|-- MANIFEST.in
Розроблення пакетів Python

Запуск тестів із pytest

pytest
======================== test session starts ========================
platform linux -- Python 3.7.9, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /home/workspace/mypackages/mysklearn
collected 6 items

tests/preprocessing/test_normalize.py ...                     [ 50%]
tests/preprocessing/test_standardize.py ...                   [100%]

========================= 6 passed in 0.23s =========================
Розроблення пакетів Python

Запуск тестів із pytest

pytest
======================== test session starts ========================
platform linux -- Python 3.7.9, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /home/workspace/mypackages/mysklearn     <--    запуск у цьому каталозі
collected 6 items                                 <--    знайдено 6 тестових функцій

tests/preprocessing/test_normalize.py ...                     [ 50%]
tests/preprocessing/test_standardize.py ...                   [100%]

========================= 6 passed in 0.23s =========================
Розроблення пакетів Python

Запуск тестів із pytest

pytest
======================== test session starts ========================
platform linux -- Python 3.7.9, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /home/workspace/mypackages/mysklearn
collected 6 items

tests/preprocessing/test_normalize.py ...                     [ 50%]  <-- 
tests/preprocessing/test_standardize.py ...                   [100%]  <-- 

========================= 6 passed in 0.23s =========================
Розроблення пакетів Python

Запуск тестів із pytest

pytest
======================== test session starts ========================
platform linux -- Python 3.7.9, pytest-6.1.2, py-1.9.0, pluggy-0.13.1
rootdir: /home/workspace/mypackages/mysklearn
collected 6 items

tests/preprocessing/test_normalize.py ...                     [ 50%]
tests/preprocessing/test_standardize.py ...                   [100%]

========================= 6 passed in 0.23s =========================
Розроблення пакетів Python

Запуск тестів із pytest

pytest
==================================== test session starts ====================================
...
tests/preprocessing/test_normalize.py .F.                                              [ 50%]
tests/preprocessing/test_standardize.py ...                                            [100%]

========================================= FAILURES ==========================================
________________________________________ test_mymax _________________________________________
...

tests/preprocessing/test_normalize.py:10: AssertionError
================================== short test summary info ==================================
FAILED tests/preprocessing/test_normalize.py::test_mymax - assert -100 == 100       <-- test_mymax
================================ 1 failed, 5 passed in 0.17s ================================
Розроблення пакетів Python

Давайте потренуємось!

Розроблення пакетів Python

Preparing Video For Download...