From 88634bd086f7520b70c1d1615baee6f4c7e9ffaa Mon Sep 17 00:00:00 2001 From: Cheukting Date: Fri, 13 May 2022 18:54:33 +0100 Subject: [PATCH] Give warning when test function return other than None --- src/_pytest/python.py | 10 ++++++++++ src/_pytest/warning_types.py | 7 +++++++ 2 files changed, 17 insertions(+) diff --git a/src/_pytest/python.py b/src/_pytest/python.py index cd951939e..e793721c6 100644 --- a/src/_pytest/python.py +++ b/src/_pytest/python.py @@ -77,10 +77,12 @@ from _pytest.pathlib import parts from _pytest.pathlib import visit from _pytest.scope import Scope from _pytest.warning_types import PytestCollectionWarning +from _pytest.warning_types import PytestReturnNotNoneWarning from _pytest.warning_types import PytestUnhandledCoroutineWarning if TYPE_CHECKING: from typing_extensions import Literal + from _pytest.scope import _ScopeName @@ -192,6 +194,14 @@ def pytest_pyfunc_call(pyfuncitem: "Function") -> Optional[object]: result = testfunction(**testargs) if hasattr(result, "__await__") or hasattr(result, "__aiter__"): async_warn_and_skip(pyfuncitem.nodeid) + elif result is not None: + warnings.warn( + PytestReturnNotNoneWarning( + "Test function returning {result}, do you mean to use `assert` instead or `return`?".format( + result=result + ) + ) + ) return True diff --git a/src/_pytest/warning_types.py b/src/_pytest/warning_types.py index ac79bb53a..aec767cdc 100644 --- a/src/_pytest/warning_types.py +++ b/src/_pytest/warning_types.py @@ -42,6 +42,13 @@ class PytestCollectionWarning(PytestWarning): __module__ = "pytest" +@final +class PytestReturnNotNoneWarning(PytestWarning): + """Warning emitted when a test function is returning value other than None.""" + + __module__ = "pytest" + + class PytestDeprecationWarning(PytestWarning, DeprecationWarning): """Warning class for features that will be removed in a future version."""