Skip to content

Commit

Permalink
Add suggested unit test for extra_stacklevel
Browse files Browse the repository at this point in the history
Co-authored-by: Laurent LAPORTE <[email protected]>
  • Loading branch information
coroa and tantale committed Jul 9, 2023
1 parent 61ed54a commit a4d54f1
Showing 1 changed file with 53 additions and 9 deletions.
62 changes: 53 additions & 9 deletions tests/test_deprecated.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# -*- coding: utf-8 -*-
import inspect
import sys
import warnings

Expand Down Expand Up @@ -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

0 comments on commit a4d54f1

Please sign in to comment.