Writing Concise Tests with Plain assert
Assertion introspection
pytest rewrites asserts to show helpful diffs.
test_strings.py
def test_username_format():
username = "alice_01"
assert username.startswith("alice")
assert " " not in usernametest_strings.py
def test_username_format():
username = "alice_01"
assert username.startswith("alice")
assert " " not in usernameIf a check fails, pytest shows:
- the values involved
- a readable explanation
Testing exceptions
test_exceptions.py
import pytest
def parse_age(s: str) -> int:
age = int(s)
if age < 0:
raise ValueError("age must be >= 0")
return age
def test_parse_age_negative():
with pytest.raises(ValueError):
parse_age("-1")test_exceptions.py
import pytest
def parse_age(s: str) -> int:
age = int(s)
if age < 0:
raise ValueError("age must be >= 0")
return age
def test_parse_age_negative():
with pytest.raises(ValueError):
parse_age("-1")Tip
Prefer many small asserts over one huge assert.
🧪 Try It Yourself
Exercise 1 – Write a unittest TestCase
Exercise 2 – assertRaises
Exercise 3 – setUp and tearDown
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
