Skip to content

Commit

Permalink
Fixed warn_on_error() not showing the actual line of the type violation
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Mar 16, 2023
1 parent 55dec69 commit c333a35
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 1 deletion.
4 changes: 4 additions & 0 deletions docs/versionhistory.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,10 @@ Version history

This library adheres to `Semantic Versioning 2.0 <https://semver.org/#semantic-versioning-200>`_.

**UNRELEASED**

- Fixed ``warn_on_error()`` not showing where the type violation actually occurred

**3.0.1** (2023-03-16)

- Improved the documentation
Expand Down
2 changes: 1 addition & 1 deletion src/typeguard/_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def warn_on_error(exc: TypeCheckError, memo: TypeCheckMemo) -> None:
:attr:`TypeCheckConfiguration.typecheck_fail_callback`.
"""
warnings.warn(TypeCheckWarning(str(exc)))
warnings.warn(TypeCheckWarning(str(exc)), stacklevel=3)


@contextmanager
Expand Down
29 changes: 29 additions & 0 deletions tests/test_warn_on_error.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from typing import List

import pytest

from typeguard import TypeCheckWarning, check_type, config, typechecked, warn_on_error


def test_check_type(monkeypatch, recwarn):
monkeypatch.setattr(config, "typecheck_fail_callback", warn_on_error)
with pytest.warns(TypeCheckWarning) as warning:
check_type(1, str)

assert len(warning.list) == 1
assert warning.list[0].filename == __file__
assert warning.list[0].lineno == test_check_type.__code__.co_firstlineno + 3


def test_typechecked(monkeypatch, recwarn):
@typechecked
def foo() -> List[int]:
return ["aa"] # type: ignore[list-item]

monkeypatch.setattr(config, "typecheck_fail_callback", warn_on_error)
with pytest.warns(TypeCheckWarning) as warning:
foo()

assert len(warning.list) == 1
assert warning.list[0].filename == __file__
assert warning.list[0].lineno == foo.__code__.co_firstlineno + 1

0 comments on commit c333a35

Please sign in to comment.