Skip to content

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 username
test_strings.py
 
def test_username_format():
    username = "alice_01"
    assert username.startswith("alice")
    assert " " not in username

If 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 coffee

Was this page helpful?

Let us know how we did