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

Декораторы, итераторы и контракты.
Download Telegram
Проверка выбросилось ли исключение:

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
Hypothesis - API для формулирования и проверки свойств. Production ready on Python.
Hypothesis is a modern implementation of property based testing, designed from the ground up for mainstream languages.
Модуль strategies определяет как генерировать числа, списки, строки и другие примитивы для тестирования работы функций (гипотез)
Декоратор @given определяет спецификацию параметров функции, которые нужно генерировать
Запуск проверки гипотез через pytest:

C:\Users\MainUser\AppData\Local\Programs\Python\Python35\python.exe -m pytest hyp_tests.py
============================= test session starts =============================
platform win32 -- Python 3.5.1, pytest-3.0.7, py-1.4.33, pluggy-0.4.0
rootdir: C:\Users\MainUser\PycharmProjects\hypothesis_tests, inifile:
plugins: hypothesis-3.8.2
collected 1 items

hyp_tests.py F

================================== FAILURES ===================================
__________________________________ test_sort __________________________________

@given(st.lists(st.integers()))
> def test_sort(xs):

hyp_tests.py:8:

...

xs = [0, 0, 0, 0, 0, 0, ...]

@given(st.lists(st.integers()))
def test_sort(xs):
res = sorted(xs)
> assert all(xi <= xj for xi, xj in zip(res, res[1:]))
E assert False
E + where False = all(<generator object test_sort.<locals>.<genexpr> at 0x00000196C78AA410>)

hyp_tests.py:10: AssertionError
--------------------------------- Hypothesis ----------------------------------
Falsifying example: test_sort(xs=[0, 0, 0, 0, 0, 0, 1, 0])
========================== 1 failed in 0.52 seconds ===========================
import pytest
import hypothesis
import hypothesis.strategies as st
from hypothesis import given


@given(st.lists(st.integers()))
def test_sort(xs):
res = sorted(xs)
assert all(xi <= xj for xi, xj in zip(res, res[1:]))


def sorted(xs, f=sorted):
return xs if len(xs) == 8 else f(xs)


if __name__ == "__main__":
pytest.main(__file__)
st.just(x) ==> x, x, x, ...
st.none() ==> None, None, None, ...
st.one_of(a, b, c) ==> a, a, b, c, a, ...
st.booleans() ==> True, True, False, ...
st.integers() ==> 1, 2, -4, ...
st.floats() ==> math.pi, 13.1, 42.2, ...

st.text() ==> "test", "something", ...
st.binary() ==> b"\xef\xff", ...

st.sampled_from(iterable)
st.tuples(st.none(), st.floats(), st.just(42))
st.lists(st.integers())
st.sets(st.floats())
st.dictionaries(st.integers(), st.text())
st.text().map(iter) - итераторы от строк
Hypothesis - лучший способ тестирования функций с инвариантами
st.text().filter(lambda x: len(x) > 10)
Измерение скорости работы кода на Python