Фишки Python
29 subscribers
2 photos
3 files
29 links
Всё что ты хотел узнать, но ленился спросить.

Декораторы, итераторы и контракты.
Download Telegram
python -m unittest test_module.py
Запуск всех тестов в текущей папке:

python -m unittest .
def setUp(self): ... - вызывается перед запуском теста
def tearDown(self): ... - после отработки теста
@classmethod
def setUpClass(cls): ... - перед запуском всех тестов

@classmethod
def tearDownClass(cls): ... - после отработки всех тестов
unittest - клон JUnit для python, camelCase и многословность это не круто
pip install -U pytest
Найти все тесты и запустить их:

python -m pytest
python -m pytest test_me.py
python -m pytest test_me.py::test_2plus2
Тестирует функции с именем test_*, методы test_* в классе Test* или в классе наследнике unittest.TestCase
Тестирование doctest-ов:

python -m pytest --doctest-modules
# content of test_sample.py
def inc(x):
return x + 1

def test_answer():
assert inc(3) == 5
$ pytest
======= test session starts ========
platform linux — Python 3.5.2, pytest-3.0.7, py-1.4.32, pluggy-0.4.0
rootdir: $REGENDOC_TMPDIR, inifile:
collected 1 items

test_sample.py F

======= FAILURES ========
_______ test_answer ________

def test_answer():
> assert inc(3) == 5
E assert 4 == 5
E + where 4 = inc(3)

test_sample.py:5: AssertionError
======= 1 failed in 0.12 seconds ========
Проверка выбросилось ли исключение:

with pytest.raises(KeyError):
d["foo"]
Параметризированный вызов теста:

import pytest
@pytest.mark.parametrize("test_input,expected", [
("3+5", 8),
("2+4", 6),
("6*9", 42),
])
def test_eval(test_input, expected):
assert eval(test_input) == expected
Контексты тестирования, монкипатч (замена стандартного ввода/вывода на время теста)
import io
import sys

def test_smth(capsys, monkeypath):
handle = io.StringIO('!')
monkeypath.setattr(sys, 'stdin', handle)
start_smth()
output, _err = capsys.readouterr()
assert output == '!'
def test_me(tmpdir): ... - создает на время теста временную директорию
Плагины для py.test:

pytest-cov: coverage reporting, compatible with distributed testing

pytest-django: write tests for django apps, using pytest integration

pytest-timeout: to timeout tests based on function marks or global definitions

pytest-pep8: a —pep8 option to enable PEP8 compliance checking