Florian Bruhin
florian@bruhin.software
https://bruhin.software/
Twitter: @the_compiler
08. September 2020, CH Open Workshoptage, HSLU Rotkreuz
pytest: Test Driven Development (nicht nur) für Python
01. bis 03. Februar 2021, Python Academy, Leipzig + online
Professional Testing with Python
Vielleicht bald?, On-site Firmentraining
Python, pytest, GUI-Applikationen mit Python und Qt (PyQt/PySide), ...
!pytest basic/test_traceback.py
!pytest basic/failure_demo.py
%%writefile test_output.py
def test_passing():
print("I'm a passing test")
def test_failing():
print("I'm a failing test")
assert False
Standardmässig zeigt pytest nur den Output von Tests an, die fehlschlagen:
!pytest test_output.py
Mit -s
wird der ganze Output während den Tests angezeigt, ohne von pytest abgeändert zu werden:
!pytest -s test_output.py
@pytest.mark.codec_x
etc. markierenpytest.ini
unter markers = ...
registrieren:[pytest]
markers =
codec_x: tests codec X
codec_y: tests codec Y
-m codec_x
, -m "codec_x or codec_y"
, -m "not slow"
, etc.!pytest marking/test_marking.py -v -m codec_x
%%writefile test_marking.py
import pytest
@pytest.mark.skip(reason="Should not run")
def test_skipped():
raise Exception
@pytest.mark.xfail(reason="Broken, see JIRA-1234")
def test_xfailing():
raise Exception
!pytest test_marking.py -rsx
%%writefile test_skipping_func.py
import pytest
def test_skipped():
# ...
pytest.skip("Server not reachable")
!pytest test_skipping_func.py
!pytest basic/test_parametrization.py -v
%pycat fixtures/test_fixture.py
!pytest fixtures/test_fixture.py --setup-show -v
Mit session
-scope db
fixture und einer function
-scope transaction
fixture, welche mit autouse=True
automatisch bei jedem Test angewendet wird:
%%writefile test_fixtures.py
import pytest
class Database:
def __init__(self):
print("creating db")
def begin(self):
print("beginning transaction")
def rollback(self):
print("finishing transaction")
@pytest.fixture(scope="session")
def db():
return Database()
@pytest.fixture(autouse=True)
def transaction(db):
db.begin()
yield
db.rollback()
def test_db(db):
print("in test 1")
def test_db_2(db):
print("in test 2")
!pytest test_fixtures.py -v -s
%cd hooks/reporting
%pycat conftest.py
!pytest -v