pytest-dev/pytest · error · TypeError

Unexpected keyword arguments passed to pytest.raises

Error message

Unexpected keyword arguments passed to pytest.raises: {kwargs}
Use context-manager form instead?

What it means

Thrown by pytest.raises() when called with no positional exception and no func/args, but with keyword arguments outside the allowed set {match, check, expected_exception}. It catches user typos like pytest.raises(message=...) or pytest.raises(exc=...).

Solutions

  1. Use only the allowed kwargs: match, check, expected_exception.
  2. Replace the removed `message` kwarg with `match`.
  3. Use the context-manager form: with pytest.raises(ValueError, match='...'):

Example fix

// before
with pytest.raises(ValueError, message="my msg"):
    raise ValueError("x")
// after
with pytest.raises(ValueError, match="my msg"):
    raise ValueError("x")
Defensive patterns

Strategy: validation

Validate before calling

allowed = {'match', 'check', 'expected_exception'}
bad = set(kwargs) - allowed
if bad:
    raise TypeError(f'pytest.raises: unknown kwargs {sorted(bad)}')
pytest.raises(ValueError, **kwargs)

Type guard

def kwargs_are_valid_for_raises(kwargs: dict) -> bool:
    return set(kwargs) <= {'match', 'check', 'expected_exception'}

Prevention

When it happens

Trigger: Calling pytest.raises(ValueError, msg='...') (msg is not a valid kwarg); pytest.raises(code=...) instead of passing a callable; pre-8.x code using `message` which was removed.

Common situations: Upgrading pytest from an old version where `message` was a valid alias for `match`; typos in keyword names; mixing the function form and context-manager form.

Related errors


AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11). Data as JSON: /api/errors/afe1bb0909d5e7de. Report an issue: GitHub.

Appendix: source

Thrown at src/_pytest/raises.py:262

        help the Python interpreter speed up its garbage collection.

        Clearing those references breaks a reference cycle
        (``ExceptionInfo`` --> caught exception --> frame stack raising
        the exception --> current frame stack --> local variables -->
        ``ExceptionInfo``) which makes Python keep all objects referenced
        from that cycle (including all local variables in the current
        frame) alive until the next cyclic garbage collection run.
        More detailed information can be found in the official Python
        documentation for :ref:`the try statement <python:try>`.
    """
    __tracebackhide__ = True

    if func is None and not args:
        if set(kwargs) - {"match", "check", "expected_exception"}:
            msg = "Unexpected keyword arguments passed to pytest.raises: "
            msg += ", ".join(sorted(kwargs))
            msg += "\nUse context-manager form instead?"
            raise TypeError(msg)

        if expected_exception is None:
            return RaisesExc(**kwargs)
        return RaisesExc(expected_exception, **kwargs)

    if not expected_exception:
        raise ValueError(
            f"Expected an exception type or a tuple of exception types, but got `{expected_exception!r}`. "
            f"Raising exceptions is already understood as failing the test, so you don't need "
            f"any special code to say 'this should never raise an exception'."
        )
    if not callable(func):
        raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
    with RaisesExc(expected_exception) as excinfo:
        func(*args, **kwargs)
    try:
        return excinfo
    finally:

View on GitHub (pinned to 0d6fbdeffa)