From a4d54f161b6d8c730da05a60870af66a122118a2 Mon Sep 17 00:00:00 2001 From: Jonas Hoersch Date: Sun, 9 Jul 2023 14:38:33 +0200 Subject: [PATCH] Add suggested unit test for extra_stacklevel Co-authored-by: Laurent LAPORTE --- tests/test_deprecated.py | 62 ++++++++++++++++++++++++++++++++++------ 1 file changed, 53 insertions(+), 9 deletions(-) diff --git a/tests/test_deprecated.py b/tests/test_deprecated.py index ceb3b2f..0e467ae 100644 --- a/tests/test_deprecated.py +++ b/tests/test_deprecated.py @@ -1,4 +1,5 @@ # -*- coding: utf-8 -*- +import inspect import sys import warnings @@ -265,16 +266,59 @@ def fun(): assert len(warns) == 1 +def test_default_stacklevel(): + """ + The objective of this unit test is to ensure that the triggered warning message, + when invoking the 'use_foo' function, correctly indicates the line where the + deprecated 'foo' function is called. + """ + + @deprecated.classic.deprecated + def foo(): + pass + + def use_foo(): + foo() + + with warnings.catch_warnings(record=True) as warns: + warnings.simplefilter("always") + use_foo() + + # Check that the warning path matches the module path + warn = warns[0] + assert warn.filename == __file__ + + # Check that the line number points to the first line inside 'use_foo' + use_foo_lineno = inspect.getsourcelines(use_foo)[1] + assert warn.lineno == use_foo_lineno + 1 + + def test_extra_stacklevel(): - @deprecated.classic.deprecated(version='1.2.1', reason="deprecated function", extra_stacklevel=1) - def inner(): + """ + The unit test utilizes an 'extra_stacklevel' of 1 to ensure that the warning message + accurately identifies the caller of the deprecated function. It verifies that when + the 'use_foo' function is called, the warning message correctly indicates the line + where the call to 'use_foo' is made. + """ + + @deprecated.classic.deprecated(extra_stacklevel=1) + def foo(): pass - - def outer(): - inner() - warnings.simplefilter("default", category=DeprecationWarning) + def use_foo(): + foo() + + def demo(): + use_foo() + with warnings.catch_warnings(record=True) as warns: - outer() - outer() - assert len(warns) == 2 + warnings.simplefilter("always") + demo() + + # Check that the warning path matches the module path + warn = warns[0] + assert warn.filename == __file__ + + # Check that the line number points to the first line inside 'demo' + demo_lineno = inspect.getsourcelines(demo)[1] + assert warn.lineno == demo_lineno + 1