brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: python pytest.raises(match=) checks the error message, not just the type

Python
~/tips/tip-python-pytest-raises-match

import pytest

Make sure code fails with the right exception and the right reason.

Testing that code raises ValueError sounds strict, but a typo in your function can raise a ValueError too. I’d add match so the test checks the reason as well.

import pytest

def parse_port(s):
    port = int(s)
    if not 0 < port < 65536:
        raise ValueError(f"port out of range: {port}")
    return port

def test_port_too_high():
    with pytest.raises(ValueError, match="out of range"):
        parse_port("70000")

Without match, this test would also pass for parse_port("abc"), where int() raises its own ValueError with a completely different message. With it, pytest checks the message too and fails if the text doesn’t match.

match is a regular expression, searched anywhere in the message with re.search. A plain phrase like the one above works fine, but characters like (, . or [ have special meaning. Wrap the expected text in re.escape() when you want to match it literally.

If you need more than the message, write with pytest.raises(ValueError) as exc: and inspect exc.value after the block. Keep only the line that should fail inside the with: any statement after it never runs, and an earlier line that raises the same error makes the test pass for the wrong reason.

Further reading: pytest.raises, pytest: assertions about expected exceptions

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link