From 9af595a17ebfcf3397f77050b97c51108fb10ed8 Mon Sep 17 00:00:00 2001 From: Bruno Oliveira Date: Fri, 3 Nov 2023 08:45:29 -0300 Subject: [PATCH] Add warning about using pytest.raises(Exception) Related to #4475 --- src/_pytest/python_api.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/src/_pytest/python_api.py b/src/_pytest/python_api.py index 4f0fa49f1..07db0f234 100644 --- a/src/_pytest/python_api.py +++ b/src/_pytest/python_api.py @@ -862,6 +862,20 @@ def raises( # noqa: F811 >>> assert exc_info.type is ValueError >>> assert exc_info.value.args[0] == "value must be 42" + .. warning:: + + Given that ``pytest.raises`` matches subclasses, be wary of using it to match :class:`Exception` like this:: + + with pytest.raises(Exception): # Careful, this will catch ANY exception raised. + some_function() + + Because :class:`Exception` is the base class of almost all exceptions, it is easy for this to hide + real bugs, where the user wrote this expecting a specific exception, but some other exception is being + raised due to a bug introduced during a refactoring. + + Avoid using ``pytest.raises`` to catch :class:`Exception` unless certain that you really want to catch + **any** exception raised. + .. note:: When using ``pytest.raises`` as a context manager, it's worthwhile to