typestar

Testing failures in Python

pytest.raises asserts that the call fails, and how.

import pytest


def stars(value):
    if not 0 <= value <= 3:
        raise ValueError(f"stars out of range: {value}")
    return value


def test_rejects_too_many():
    with pytest.raises(ValueError, match="out of range"):
        stars(9)


def test_reports_the_bad_value():
    with pytest.raises(ValueError) as excinfo:
        stars(-1)
    assert "-1" in str(excinfo.value)


def test_accepts_the_range():
    assert [stars(n) for n in range(4)] == [0, 1, 2, 3]

How it works

  1. The with block must contain the failing call and nothing else.
  2. match checks the message against a regular expression.
  3. excinfo.value is the exception itself, for further assertions.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
420
Tokens
114
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 68 seconds.

Type this snippet

Step 2 of 3 in Writing tests, step 2 of 9 in Testing with pytest.

← Previous Next →