pytest-dev/pytest · error · TypeError
Unexpected keyword arguments passed to pytest.warns
Error message
Unexpected keyword arguments passed to pytest.warns: {argnames}
Use context-manager form instead? What it means
Raised by pytest.warns when the context-manager form is used but unrecognized keyword arguments are passed. Only match= is consumed from kwargs in that form; anything else is almost certainly a typo or a misplaced parameter meant for the function form. The error lists the sorted offending names and reminds the user to use the context-manager form correctly.
Solutions
- Use the supported match= keyword for regex matching: pytest.warns(UserWarning, match='x').
- Drop the unrecognized kwargs if they were accidental.
- If you intended the function form, pass a callable as the second positional argument.
Example fix
// before
with pytest.warns(UserWarning, message='deprecated'):
...
// after
with pytest.warns(UserWarning, match='deprecated'):
... Defensive patterns
Strategy: validation
Validate before calling
allowed = {'match'}
bad = set(kwargs) - allowed
assert not bad, f'pytest.warns context-manager form only accepts {allowed}; got {sorted(bad)}' Type guard
def warns_kwargs_valid(kwargs) -> bool:
return set(kwargs) <= {'match'} Prevention
- In context-manager form, only match= is accepted by pytest.warns.
- Use message= only with warnings.warn, not pytest.warns.
- Run a quick smoke test of warns helpers after refactor.
When it happens
Trigger: pytest.warns(UserWarning, match='x', foo=1); pytest.warns(UserWarning, message='x'); any kwarg other than match when func is None and args is empty. The `if kwargs:` branch after popping match fires.
Common situations: Typing message= instead of match=; passing category kwargs that belong to warnings.warn; copy-paste from filterwarnings parameter names.
Related errors
- object (type: ) must be callable
- `allow_unwrapped=True` bypasses the `match` and `check`…
- `allow_unwrapped=True` has no effect when expecting a…
- Cannot enter twice
- Cannot exit without entering first
AI-assisted analysis of pytest-dev/pytest@0d6fbdeffa (2026-08-11).
Data as JSON: /api/errors/54136c0ed6022be9.
Report an issue: GitHub.
Appendix: source
Thrown at src/_pytest/recwarn.py:163
Failed: Regex pattern did not match any of the 1 warnings emitted.
Regex: ...
Emitted warnings: ...UserWarning...
**Using with** ``pytest.mark.parametrize``
When using :ref:`pytest.mark.parametrize ref` it is possible to parametrize tests
such that some runs raise a warning and others do not.
This could be achieved in the same way as with exceptions, see
:ref:`parametrizing_conditional_raising` for an example.
"""
__tracebackhide__ = True
if func is None and not args:
match: str | re.Pattern[str] | None = kwargs.pop("match", None)
if kwargs:
argnames = ", ".join(sorted(kwargs))
raise TypeError(
f"Unexpected keyword arguments passed to pytest.warns: {argnames}"
"\nUse context-manager form instead?"
)
return WarningsChecker(expected_warning, match_expr=match, _ispytest=True)
else:
if not callable(func):
raise TypeError(f"{func!r} object (type: {type(func)}) must be callable")
with WarningsChecker(expected_warning, _ispytest=True):
return func(*args, **kwargs)
class WarningsRecorder(warnings.catch_warnings):
"""A context manager to record raised warnings.
Each recorded warning is an instance of :class:`warnings.WarningMessage`.
Adapted from `warnings.catch_warnings`.
View on GitHub (pinned to 0d6fbdeffa)