Skip to content

Commit e697a4b

Browse files
authored
fix(const): keep AppType/OptionType.register loud inside a quiet block (#1916) (#1927)
* 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 * refactor(utilities): rename _CaughtByCaller to CaughtByCaller (#1916) - The block is used across pcapkit as a library-wide context manager, so drop the leading underscore. It is new in this beta, so no old-name re-export is kept. - Rename every use: exceptions.py, corekit/enum.py, the AppType and OptionType vendor templates, the exceptions docs page, and the tests that open the block. The two const modules are regenerated from the templates. - Export it from pcapkit.utilities.exceptions.__all__ and word its docstring as a contract, with a versionadded directive. Refs #1916
1 parent 12b72da commit e697a4b

10 files changed

Lines changed: 130 additions & 33 deletions

File tree

‎docs/source/pcapkit/utilities/exceptions.rst‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ It is still an ordinary exception carrying its message, so ``except`` clauses an
2929
:func:`repr` are unaffected.
3030

3131
An error is also quiet when it is constructed inside a
32-
:class:`~pcapkit.utilities.exceptions._CaughtByCaller` block naming one of its
32+
:class:`~pcapkit.utilities.exceptions.CaughtByCaller` block naming one of its
3333
classes. That is how :mod:`pcapkit` marks as control flow an error raised by
3434
code it calls but does not own, such as a generated ``_validate_value``
3535
override, which cannot know to pass ``quiet=True`` itself (:issue:`1845`).
@@ -54,7 +54,7 @@ override, which cannot know to pass ``quiet=True`` itself (:issue:`1845`).
5454
:param \*args: Arbitrary positional arguments.
5555
:param \*\*kwargs: Arbitrary keyword arguments.
5656

57-
.. autoclass:: pcapkit.utilities.exceptions._CaughtByCaller
57+
.. autoclass:: pcapkit.utilities.exceptions.CaughtByCaller
5858
:no-members:
5959

6060
:exc:`TypeError` Category

‎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 CaughtByCaller, EnumValueError
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 CaughtByCaller, EnumValueError
2121

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

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

28362839
identifier = cls._sanitize_identifier(name)
28372840
if not identifier.isidentifier():

‎pcapkit/corekit/enum.py‎

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -100,7 +100,7 @@
100100
from aenum import extend_enum
101101

102102
from pcapkit.corekit.sentinels import NO_DEFAULT
103-
from pcapkit.utilities.exceptions import BaseError, EnumKeyError, EnumValueError, _CaughtByCaller
103+
from pcapkit.utilities.exceptions import BaseError, CaughtByCaller, EnumKeyError, EnumValueError
104104

105105
if TYPE_CHECKING:
106106
from typing import Any
@@ -200,7 +200,7 @@ def _validate_value(cls, value: 'Any') -> 'None':
200200
:meth:`get`'s own ``except ValueError`` and falls back to ``default``
201201
just as any other unresolvable value does. It is also quiet:
202202
:meth:`get` always calls this hook inside a
203-
:class:`~pcapkit.utilities.exceptions._CaughtByCaller` block for
203+
:class:`~pcapkit.utilities.exceptions.CaughtByCaller` block for
204204
:exc:`ValueError`, so an override need not pass ``quiet=True`` for its
205205
rejection to log nothing there (:issue:`1845`). An override raising
206206
something outside that hierarchy would instead propagate past
@@ -342,7 +342,7 @@ def get(cls, key: 'Any', default: 'Any' = NO_DEFAULT) -> 'Self':
342342
given on :meth:`_validate_value` itself.
343343
344344
The hook and ``cls(key)`` run inside a
345-
:class:`~pcapkit.utilities.exceptions._CaughtByCaller` block for
345+
:class:`~pcapkit.utilities.exceptions.CaughtByCaller` block for
346346
:exc:`ValueError`, because every :exc:`ValueError` they raise is this
347347
method's own lookup miss: caught here, then answered with ``default`` or
348348
raised to the caller as the miss. A loud
@@ -445,7 +445,7 @@ def get(cls, key: 'Any', default: 'Any' = NO_DEFAULT) -> 'Self':
445445
# this method's own lookup miss -- answered with ``default`` below,
446446
# or raised as the miss -- so a loud one is quiet here, whoever
447447
# constructed it.
448-
with _CaughtByCaller(ValueError):
448+
with CaughtByCaller(ValueError):
449449
cls._validate_value(key)
450450
return cls(key) # type: ignore[call-arg]
451451
except ValueError as error:
@@ -546,7 +546,7 @@ def register(cls, value: 'Any', name: 'str') -> 'Self':
546546
hook, because there the rejection is a lookup miss for the caller to
547547
handle; here it refuses a mint the caller explicitly asked for, which
548548
is a fault to report. So this calls the hook in a
549-
:class:`~pcapkit.utilities.exceptions._CaughtByCaller` block declaring
549+
:class:`~pcapkit.utilities.exceptions.CaughtByCaller` block declaring
550550
that nothing is caught -- loud even if ``register`` is reached from
551551
inside a ``get`` (:issue:`1845`).
552552
@@ -577,7 +577,7 @@ def register(cls, value: 'Any', name: 'str') -> 'Self':
577577
f'to add a further name for it')
578578
# NOTE: GitHub issue #1845. Declares that nothing is caught, so the
579579
# rejection stays loud even inside a ``get`` block that would quiet it.
580-
with _CaughtByCaller():
580+
with CaughtByCaller():
581581
cls._validate_value(value)
582582
return cls._extend(value, name)
583583

‎pcapkit/utilities/exceptions.py‎

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from typing import Any, Callable, Optional, Type
3232

3333
__all__ = [
34-
'stacklevel',
34+
'stacklevel', 'CaughtByCaller',
3535

3636
'BaseError', # Exception
3737
'DigitError', 'IntError', 'RealError', 'ComplexError', # TypeError
@@ -158,7 +158,7 @@ def stacklevel() -> 'int':
158158

159159
#: ContextVar[tuple[Type[BaseException], ...]]: The exception classes the
160160
#: :mod:`pcapkit` code running in this context has undertaken to catch itself,
161-
#: as declared by the innermost :class:`_CaughtByCaller` block. A
161+
#: as declared by the innermost :class:`CaughtByCaller` block. A
162162
#: :class:`BaseError` that is an instance of one of them is constructed quiet,
163163
#: whatever its own ``quiet`` says.
164164
#:
@@ -170,15 +170,19 @@ def stacklevel() -> 'int':
170170
) # type: contextvars.ContextVar[tuple[Type[BaseException], ...]]
171171

172172

173-
class _CaughtByCaller:
173+
class CaughtByCaller:
174174
"""Construct errors of the given classes quietly for the duration of a block.
175175
176-
For :mod:`pcapkit` code that is about to call something it does not own --
177-
a generated :meth:`~pcapkit.corekit.enum.EnumLookup._validate_value`
178-
override, say -- and will catch the named exceptions itself. An error the
179-
callee raises is then the quiet control flow it is at that call site,
180-
without the callee having to pass ``quiet=True``, which it cannot know to
181-
do (:issue:`1845`). Only the named classes are affected: anything else the
176+
A :class:`BaseError` constructed inside the block that is an instance of one
177+
of ``types`` behaves exactly as if it had been given ``quiet=True``: nothing
178+
is logged and no exception hook is installed. Every other error stays loud.
179+
180+
Use it around a call into code the caller does not own -- a generated
181+
:meth:`~pcapkit.corekit.enum.EnumLookup._validate_value` override, say --
182+
whose named exceptions the caller then catches itself. An error the callee
183+
raises is then the quiet control flow it is at that call site, without the
184+
callee having to pass ``quiet=True``, which it cannot know to do
185+
(:issue:`1845`). Only the named classes are affected: anything else the
182186
callee raises escapes the caller and so stays loud.
183187
184188
Given no classes, it declares that nothing is caught, which makes errors
@@ -188,7 +192,9 @@ class _CaughtByCaller:
188192
189193
Re-entrant: on exit a block restores whatever the enclosing block declared.
190194
An instance holds the token of the one ``with`` it is entered by, so it is
191-
built afresh for each.
195+
built afresh for each. The declaration is per thread and per
196+
:mod:`contextvars` context, so a block never quiets an error raised on
197+
another thread.
192198
193199
A class rather than :func:`contextlib.contextmanager`, because
194200
:meth:`EnumLookup.get <pcapkit.corekit.enum.EnumLookup.get>` enters one on
@@ -198,6 +204,8 @@ class _CaughtByCaller:
198204
Args:
199205
*types: Exception classes the caller catches.
200206
207+
.. versionadded:: 1.5.0
208+
201209
"""
202210

203211
__slots__ = ('_types', '_token')
@@ -236,7 +244,7 @@ class BaseError(Exception):
236244
catches it.
237245
238246
An error is also quiet when it is constructed inside a
239-
:class:`_CaughtByCaller` block naming one of its classes, which is how a
247+
:class:`CaughtByCaller` block naming one of its classes, which is how a
240248
:mod:`pcapkit` caller marks as control flow an error raised by code that
241249
does not pass ``quiet=True`` itself. The effect is exactly that of
242250
``quiet=True``.
@@ -276,7 +284,7 @@ class BaseError(Exception):
276284

277285
def __init__(self, *args: 'Any', quiet: 'bool' = False, **kwargs: 'Any') -> 'None':
278286
# log error -- a quiet error emits nothing and mutates nothing, and so
279-
# does one a :class:`_CaughtByCaller` block says its caller catches
287+
# does one a :class:`CaughtByCaller` block says its caller catches
280288
if not quiet and not isinstance(self, _caught_here.get()):
281289
if DEVMODE:
282290
logger.critical('%s: %s', type(self).__name__, str(self),

‎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 CaughtByCaller, EnumValueError
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 CaughtByCaller, EnumValueError
113113
114114
__all__ = ['TransportProtocol', '{NAME}']
115115
@@ -785,7 +785,10 @@ def register(cls, port: 'int', name: 'str') -> '{NAME}': # pylint: disable=argu
785785
f'({{", ".join(member.svc for member in existing)}}); use '
786786
f'{{cls.__name__}}.register_alias() to add a further service name '
787787
'for it')
788-
cls._validate_value(port)
788+
# NOTE: GitHub issue #1845. Declares that nothing is caught, so the
789+
# rejection stays loud even inside a ``get`` block that would quiet it.
790+
with CaughtByCaller():
791+
cls._validate_value(port)
789792
790793
identifier = cls._sanitize_identifier(name)
791794
if not identifier.isidentifier():

‎tests/const/test_const_enum_builtin_parity.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -435,7 +435,7 @@ def test_the_exception_is_not_an_in_library_one(self) -> None:
435435
its constructor unless it is quiet, so it fires even for an exception
436436
that is caught and discarded. The base
437437
:meth:`~pcapkit.corekit.enum.EnumLookup.get` constructs its lookup inside
438-
a ``_CaughtByCaller(ValueError)`` block (#1845), which quiets a
438+
a ``CaughtByCaller(ValueError)`` block (#1845), which quiets a
439439
:exc:`ValueError` subclass there, but a direct ``cls(value)`` caught by
440440
its caller has no such block: a guard raising a
441441
:class:`~pcapkit.utilities.exceptions.BaseError` subclass would log once
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 CaughtByCaller, EnumValueError
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()

‎tests/corekit/test_enum_get_quiet_fallback_1845_unit.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
``default`` or without one -- without, the miss is still raised, just not
1111
reported -- and kept ``register`` loud. The quiet path lives in
1212
:mod:`pcapkit.corekit`, so the generated overrides are untouched: ``get`` runs
13-
them inside a :class:`~pcapkit.utilities.exceptions._CaughtByCaller` block, which
13+
them inside a :class:`~pcapkit.utilities.exceptions.CaughtByCaller` block, which
1414
makes a :exc:`ValueError`-derived :class:`~pcapkit.utilities.exceptions.BaseError`
1515
constructed there quiet.
1616
@@ -286,16 +286,16 @@ def test_register_reached_from_a_raising_get_stays_loud(self) -> 'None':
286286

287287
def test_register_inside_a_quiet_block_stays_loud(self) -> 'None':
288288
with _records() as (_, module):
289-
with exceptions._CaughtByCaller(ValueError):
289+
with exceptions.CaughtByCaller(ValueError):
290290
with self.assertRaises(EnumValueError):
291291
ToSPrecedence.register(OUT_OF_RANGE, 'Block_1845')
292292
self.assertEqual(module.messages, [LOUD_RECORD])
293293

294294
def test_blocks_nest_and_restore(self) -> 'None':
295295
with _records() as (_, module):
296-
with exceptions._CaughtByCaller(ValueError):
296+
with exceptions.CaughtByCaller(ValueError):
297297
EnumValueError('outer, quiet')
298-
with exceptions._CaughtByCaller():
298+
with exceptions.CaughtByCaller():
299299
EnumValueError('inner, loud')
300300
EnumValueError('outer again, quiet')
301301
IntError('not a ValueError, loud')

0 commit comments

Comments
 (0)