with pytest.raises(ValueError, match='invalid input'): parse_config
Testing Patterns

Meaning

A pytest context manager that asserts a specific exception type is raised inside its block and optionally verifies the exception message matches a regex pattern. It addresses the pain point of testing error paths where simply confirming code runs without errors is insufficient. You reach for this when you need to verify that invalid inputs or edge cases raise the expected exceptions with meaningful messages.

Primary Function

Exception testing

Communicative Purpose

Ensures code under test raises the correct exception type with the expected error message

Pattern

with pytest.raises(exception_type, match=pattern): callable_under_test(*args, **kwargs)

Core Structure

with pytest.raises(..., match=...): ...

Função primária

Exception testing

Propósito comunicativo

Ensures code under test raises the correct exception type with the expected error message

Situações de gatilho

Input validation: verifying that malformed or out-of-range inputs raise ValueError with a descriptive message; API contract testing: confirming that precondition violations surface as specific exception types; Error path coverage: asserting that failure modes produce distinguishable exceptions rather than silent failures

Contextos

pytest test suites, Python unit testing, CI/CD pipelines, TDD workflows

Padrão

with pytest.raises(exception_type, match=pattern): callable_under_test(*args, **kwargs)

Estrutura central

with pytest.raises(..., match=...): ...

Slots de substituição

exception_type: exception class such as ValueError or TypeError, pattern: regex string matching the exception message

Colocados típicos

  • pytest.fixture
  • pytest.mark.parametrize
  • assert
  • pytest.warns
  • pytest.deprecated_call

Substituições comuns

  • unittest.TestCase.assertRaises: callback style instead of context manager
  • less readable for multi-line code
  • try/except with pytest.fail: manual and verbose
  • pytest.raises is the idiomatic replacement
  • pytest.raises without match: verifies exception type only but misses message validation

Erros comuns

Placing code before the with block instead of inside it — the exception must be raised within the context manager body or the test fails Using match with a plain string containing regex special characters like parentheses or dots — match uses re.search so these are interpreted as regex, causing false failures Expecting pytest.raises to catch exceptions from code that runs after the with block exits — only code inside the indented block is monitored Forgetting the colon after the with statement — syntax error that prevents the test from running

Similar / contraste

unittest.assertRaises: callback-based API with no regex match support, pytest.raises is more Pythonic; try/except/pytest.fail: manual exception checking, more verbose and error-prone; pytest.warns: analogous pattern for warning assertions instead of exceptions

Interferências

Coming from unittest: may write self.assertRaises(ValueError, func, arg) — pytest uses a context manager, not a callback; Coming from Java/JUnit: may expect @Test(expected=...) annotation — pytest has no decorator equivalent, use the with statement instead; Coming from JavaScript/Jest: may expect expect(() => fn()).toThrow() — pytest requires the with context manager form

Família do chunk

  • pytest.raises
  • pytest.warns
  • pytest.deprecated_call
  • pytest.fixture
  • assert

Nuance

Do not use pytest.raises for exceptions you do not actually care about testing — if any exception is acceptable, the test is too permissive. The match parameter uses re.search not exact string equality, so partial matches pass; use ^ and $ anchors for exact matching. If the code inside the with block raises a different exception type than expected, the test fails with a detailed diff showing the actual exception.

Efeito pragmático

Catches regressions where error handling is accidentally removed or exception types are changed, and ensures error messages remain meaningful for debugging and user-facing diagnostics.

Dica de memória

Like a safety net that only catches one specific type of falling object — if the wrong thing falls, the net breaks and the test fails loudly.

Nota

The match parameter was added in pytest 2.8. Prior to that, you had to manually inspect exc_info.value.args[0]. The as exc_info syntax allows post-assertion inspection of the caught exception object.

Upgrade path

pytest.raises with exc_info for multi-assertion exception validation; pytest.mark.parametrize for testing multiple exception-triggering inputs

Frequência: HighFormulaicidade: Semi-fixedTipo de construção: with_statementPrioridade de aquisição: Active recallPrioridade de output: OutputTag de espaçamento: Short-termIdioma?: Sim

Log in to save chunks.