Skip to content

Commit

Permalink
Backport assert_never change to include repr of value (#371)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hnasar committed Apr 20, 2024
1 parent d0a654c commit 2a7945b
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Expand Up @@ -4,6 +4,9 @@
`__static_attributes__` attribute to all classes in Python,
which broke some assumptions made by the implementation of
`typing_extensions.Protocol`.
- At runtime, `assert_never` now includes the repr of the argument
in the `AssertionError`. Patch by Hashem, backporting of the original
fix https://github.com/python/cpython/pull/91720 by Jelle Zijlstra.

# Release 4.11.0 (April 5, 2024)

Expand Down
13 changes: 13 additions & 0 deletions src/test_typing_extensions.py
Expand Up @@ -283,6 +283,19 @@ def test_exception(self):
with self.assertRaises(AssertionError):
assert_never(None)

value = "some value"
with self.assertRaisesRegex(AssertionError, value):
assert_never(value)

# Make sure a huge value doesn't get printed in its entirety
huge_value = "a" * 10000
with self.assertRaises(AssertionError) as cm:
assert_never(huge_value)
self.assertLess(
len(cm.exception.args[0]),
typing_extensions._ASSERT_NEVER_REPR_MAX_LENGTH * 2,
)


class OverrideTests(BaseTestCase):
def test_override(self):
Expand Down
11 changes: 10 additions & 1 deletion src/typing_extensions.py
Expand Up @@ -2355,6 +2355,12 @@ def reveal_type(obj: T, /) -> T:
return obj


if hasattr(typing, "_ASSERT_NEVER_REPR_MAX_LENGTH"): # 3.11+
_ASSERT_NEVER_REPR_MAX_LENGTH = typing._ASSERT_NEVER_REPR_MAX_LENGTH
else: # <=3.10
_ASSERT_NEVER_REPR_MAX_LENGTH = 100


if hasattr(typing, "assert_never"): # 3.11+
assert_never = typing.assert_never
else: # <=3.10
Expand All @@ -2378,7 +2384,10 @@ def int_or_str(arg: int | str) -> None:
At runtime, this throws an exception when called.
"""
raise AssertionError("Expected code to be unreachable")
value = repr(arg)
if len(value) > _ASSERT_NEVER_REPR_MAX_LENGTH:
value = value[:_ASSERT_NEVER_REPR_MAX_LENGTH] + '...'
raise AssertionError(f"Expected code to be unreachable, but got: {value}")


if sys.version_info >= (3, 12): # 3.12+
Expand Down

0 comments on commit 2a7945b

Please sign in to comment.