Pytest Basics
Pytest testing framework essentials for Python.
Basic Tests
Simple test
def test_addition():
assert 2 + 2 == 4
With message
def test_something():
assert 1 == 1, "Values should be equal"
Multiple assertions
def test_multiple():
x = 5
assert x > 0
assert x < 10
Assertions
Equality
assert a == b
assert a != b
Identity
assert a is b
assert a is not None
Membership
assert item in collection
assert key in dictionary
Exceptions
import pytest
with pytest.raises(ValueError):
raise ValueError("error")
Running Tests
Run all tests
pytest
Specific file
pytest test_module.py
Specific test
pytest test_module.py::test_function
Verbose output
pytest -v
Stop on first failure
pytest -x
Show print output
pytest -s
Markers
Skip test
@pytest.mark.skip(reason="Not implemented")
def test_feature():
pass
Conditional skip
@pytest.mark.skipif(sys.version_info < (3, 8), reason="Python 3.8+")
def test_new_feature():
pass
Expected failure
@pytest.mark.xfail
def test_buggy_feature():
pass