Skip to content

Commit 2d50c6b

Browse files
committed
fix(const): keep AppType/OptionType.register loud inside a quiet block (#1916)
- AppType.register and OptionType.register called _validate_value bare, so a rejection raised inside an enclosing quiet get block logged nothing. Run it inside `with _CaughtByCaller():`, as EnumRegistry.register does (#1845), in the vendor templates, and import _CaughtByCaller there. - Regenerate pcapkit/const/reg/apptype/apptype.py and pcapkit/const/pcapng/option_type.py from the edited templates, reusing the committed crawled data rather than re-crawling. - Add a unit test that TCP.register(70000, 'x') and OptionType.register(-1, 'x') still leave their record on the pcapkit logger inside `_CaughtByCaller(ValueError)`. Closes #1916
1 parent 95caa8b commit 2d50c6b

5 files changed

Lines changed: 97 additions & 8 deletions

File tree

‎pcapkit/const/pcapng/option_type.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
from aenum import StrEnum, extend_enum
1717

1818
from pcapkit.corekit.enum import EnumRegistry
19-
from pcapkit.utilities.exceptions import EnumValueError
19+
from pcapkit.utilities.exceptions import EnumValueError, _CaughtByCaller
2020

2121
__all__ = ['OptionType']
2222

@@ -277,7 +277,10 @@ def register(cls, value: 'int', name: 'str') -> 'OptionType':
277277
if existing is not None:
278278
raise ValueError(f'{value!r} is already registered on {cls.__name__} as '
279279
f'{existing.name!r} in namespace {space!r}')
280-
cls._validate_value(value)
280+
# NOTE: GitHub issue #1845. Declares that nothing is caught, so the
281+
# rejection stays loud even inside a ``get`` block that would quiet it.
282+
with _CaughtByCaller():
283+
cls._validate_value(value)
281284
try:
282285
return extend_enum(cls, name, value, name)
283286
except TypeError as error:

‎pcapkit/const/reg/apptype/apptype.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
from pcapkit.corekit.enum import EnumLookup, EnumRegistry
1919
from pcapkit.corekit.sentinels import NO_DEFAULT
20-
from pcapkit.utilities.exceptions import EnumValueError
20+
from pcapkit.utilities.exceptions import EnumValueError, _CaughtByCaller
2121

2222
__all__ = ['TransportProtocol', 'AppType']
2323

@@ -2828,7 +2828,10 @@ def register(cls, port: 'int', name: 'str') -> 'AppType': # pylint: disable=arg
28282828
f'({", ".join(member.svc for member in existing)}); use '
28292829
f'{cls.__name__}.register_alias() to add a further service name '
28302830
'for it')
2831-
cls._validate_value(port)
2831+
# NOTE: GitHub issue #1845. Declares that nothing is caught, so the
2832+
# rejection stays loud even inside a ``get`` block that would quiet it.
2833+
with _CaughtByCaller():
2834+
cls._validate_value(port)
28322835

28332836
identifier = cls._sanitize_identifier(name)
28342837
if not identifier.isidentifier():

‎pcapkit/vendor/pcapng/option_type.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@
4444
from aenum import StrEnum, extend_enum
4545
4646
from pcapkit.corekit.enum import EnumRegistry
47-
from pcapkit.utilities.exceptions import EnumValueError
47+
from pcapkit.utilities.exceptions import EnumValueError, _CaughtByCaller
4848
4949
__all__ = ['{NAME}']
5050
@@ -187,7 +187,10 @@ def register(cls, value: 'int', name: 'str') -> '{NAME}':
187187
if existing is not None:
188188
raise ValueError(f'{{value!r}} is already registered on {{cls.__name__}} as '
189189
f'{{existing.name!r}} in namespace {{space!r}}')
190-
cls._validate_value(value)
190+
# NOTE: GitHub issue #1845. Declares that nothing is caught, so the
191+
# rejection stays loud even inside a ``get`` block that would quiet it.
192+
with _CaughtByCaller():
193+
cls._validate_value(value)
191194
try:
192195
return extend_enum(cls, name, value, name)
193196
except TypeError as error:

‎pcapkit/vendor/reg/apptype/apptype.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@
109109
110110
from pcapkit.corekit.enum import EnumLookup, EnumRegistry
111111
from pcapkit.corekit.sentinels import NO_DEFAULT
112-
from pcapkit.utilities.exceptions import EnumValueError
112+
from pcapkit.utilities.exceptions import EnumValueError, _CaughtByCaller
113113
114114
__all__ = ['TransportProtocol', '{NAME}']
115115
@@ -782,7 +782,10 @@ def register(cls, port: 'int', name: 'str') -> '{NAME}': # pylint: disable=argu
782782
f'({{", ".join(member.svc for member in existing)}}); use '
783783
f'{{cls.__name__}}.register_alias() to add a further service name '
784784
'for it')
785-
cls._validate_value(port)
785+
# NOTE: GitHub issue #1845. Declares that nothing is caught, so the
786+
# rejection stays loud even inside a ``get`` block that would quiet it.
787+
with _CaughtByCaller():
788+
cls._validate_value(port)
786789
787790
identifier = cls._sanitize_identifier(name)
788791
if not identifier.isidentifier():
Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# -*- coding: utf-8 -*-
2+
"""The generated ``register`` overrides stay loud inside a quiet block.
3+
4+
GitHub issue #1916. :meth:`~pcapkit.corekit.enum.EnumRegistry.register` runs
5+
:meth:`~pcapkit.corekit.enum.EnumLookup._validate_value` inside a
6+
:class:`~pcapkit.utilities.exceptions._CaughtByCaller` block declaring that
7+
nothing is caught, so its rejection is logged even when an enclosing ``get``
8+
has quieted :exc:`ValueError` (#1845). The overrides on
9+
:class:`~pcapkit.const.reg.apptype.apptype.AppType` and
10+
:class:`~pcapkit.const.pcapng.option_type.OptionType` called the hook bare, so
11+
inside such a block their rejection raised and logged nothing.
12+
13+
Each test opens the quiet block the way ``get`` does and checks that the
14+
rejection still leaves its record on the ``pcapkit`` logger. The record comes
15+
from :mod:`pcapkit.utilities.exceptions`'s own logger, a child of that one.
16+
17+
This module is unit-tier and reads no capture.
18+
19+
"""
20+
from __future__ import annotations
21+
22+
import logging
23+
import sys
24+
import threading
25+
import unittest
26+
from typing import TYPE_CHECKING
27+
28+
from tests.utilities._harness import capture
29+
30+
if TYPE_CHECKING:
31+
from typing import Callable
32+
33+
34+
class RegisterLoudInQuietBlock1916Tests(unittest.TestCase):
35+
"""``register`` on a generated registry logs its rejection inside a quiet block."""
36+
37+
def setUp(self) -> 'None':
38+
# A loud error outside development mode replaces both hooks; put the
39+
# real ones back so this test does not leak pcapkit's into later ones.
40+
saved_sys, saved_threading = sys.excepthook, threading.excepthook
41+
42+
def _restore() -> 'None':
43+
sys.excepthook = saved_sys
44+
threading.excepthook = saved_threading
45+
46+
self.addCleanup(_restore)
47+
48+
def assertLoudInsideQuietBlock(self, registry: 'type', call: 'Callable[[], object]',
49+
message: 'str') -> 'None':
50+
"""Assert ``call`` raises ``message`` and logs it, inside a quiet block."""
51+
from pcapkit.utilities.exceptions import EnumValueError, _CaughtByCaller
52+
53+
members = dict(registry.__members__) # type: ignore[attr-defined]
54+
with capture(logging.getLogger('pcapkit')) as package:
55+
with _CaughtByCaller(ValueError):
56+
with self.assertRaises(EnumValueError) as caught:
57+
call()
58+
self.assertEqual(str(caught.exception), message)
59+
self.assertEqual(package.messages, [('CRITICAL', f'EnumValueError: {message}')],
60+
'the rejection was quieted by the enclosing block')
61+
self.assertEqual(dict(registry.__members__), members) # type: ignore[attr-defined]
62+
63+
def test_apptype_register(self) -> 'None':
64+
from pcapkit.const.reg.apptype import TCP
65+
66+
self.assertLoudInsideQuietBlock(TCP, lambda: TCP.register(70000, 'x'),
67+
'70000 is not a valid TCP')
68+
69+
def test_option_type_register(self) -> 'None':
70+
from pcapkit.const.pcapng.option_type import OptionType
71+
72+
self.assertLoudInsideQuietBlock(OptionType, lambda: OptionType.register(-1, 'x'),
73+
'-1 is not a valid OptionType')
74+
75+
76+
if __name__ == '__main__':
77+
unittest.main()

0 commit comments

Comments
 (0)