117117"""
118118from __future__ import annotations
119119
120+ import importlib
120121import pathlib
121122import re
122123import unittest
123124
124- from pcapkit .corekit .enum import NO_DEFAULT , NoDefaultType
125- from pcapkit .corekit .fields .field import NO_VALUE , NoValueType
126- from pcapkit .corekit .module import NULL , NullType
127- from pcapkit .protocols .protocol import ABSENT , AbsentType
125+ from tests ._support import reimport_once_per_class
126+
127+ # ``pcapkit`` is deliberately not imported at module load. GitHub issue #1332: the
128+ # plain-unittest ordering legs leave a freshly re-imported ``pcapkit`` in
129+ # ``sys.modules``, so a sentinel bound here would be the *old* import's object and
130+ # every ``assertIs`` against the canonical one would fail. The sentinels are read
131+ # through :func:`_sentinels` after :func:`~tests._support.reimport_once_per_class`.
128132
129133#: Repository root, for the two tests that read a file rather than import it.
130134ROOT = pathlib .Path (__file__ ).resolve ().parents [2 ]
134138#: below used to name a different module here (``pcapkit.corekit.module``,
135139#: ``pcapkit.corekit.fields.field``, ``pcapkit.corekit.enum`` and
136140#: ``pcapkit.protocols.protocol`` respectively); all four now report this one.
137- import pcapkit .corekit .sentinels as sentinels
138-
139141CANONICAL_MODULE = 'pcapkit.corekit.sentinels'
140142
141143#: Every sentinel in the tree that follows the house ``<SENTINEL>Type`` convention,
145147#: All four now share :data:`CANONICAL_MODULE` as their defining module, which is
146148#: why a per-entry module column is no longer part of this tuple -- see
147149#: :data:`PUBLIC_SENTINELS` below for the (still distinct) *shim* locations.
148- SENTINELS = (
149- ('NULL' , NULL , NullType ),
150- ('NO_VALUE' , NO_VALUE , NoValueType ),
151- ('NO_DEFAULT' , NO_DEFAULT , NoDefaultType ),
152- ('ABSENT' , ABSENT , AbsentType ),
153- )
150+ #: Built by :func:`_sentinels` from the live import, not at module load.
154151
155152#: The public three of :data:`SENTINELS`, as ``(module, object name, type name)``.
156153#: ``ABSENT`` is absent from it deliberately: it is private, so it is exported
163160)
164161
165162
163+ def _sentinels () -> 'tuple[tuple[str, object, type], ...]' :
164+ """:data:`SENTINELS`, read from the ``pcapkit`` import that is live now."""
165+ enum = importlib .import_module ('pcapkit.corekit.enum' )
166+ field = importlib .import_module ('pcapkit.corekit.fields.field' )
167+ module = importlib .import_module ('pcapkit.corekit.module' )
168+ protocol = importlib .import_module ('pcapkit.protocols.protocol' )
169+ return (
170+ ('NULL' , module .NULL , module .NullType ),
171+ ('NO_VALUE' , field .NO_VALUE , field .NoValueType ),
172+ ('NO_DEFAULT' , enum .NO_DEFAULT , enum .NoDefaultType ),
173+ ('ABSENT' , protocol .ABSENT , protocol .AbsentType ),
174+ )
175+
176+
177+ class _ReimportCase (unittest .TestCase ):
178+ """Base: give each test class one fresh ``pcapkit`` import (GitHub issue #1332)."""
179+
180+ def setUp (self ) -> 'None' :
181+ reimport_once_per_class (self )
182+
183+
166184def _expected_type_name (instance_name : 'str' ) -> 'str' :
167185 """The type name the house convention derives from an instance name.
168186
@@ -214,7 +232,7 @@ def _sentinel_section() -> 'str':
214232 return path .read_text (encoding = 'utf-8' )
215233
216234
217- class SentinelExportTests (unittest . TestCase ):
235+ class SentinelExportTests (_ReimportCase ):
218236 """``__all__`` names the object and not the type, per module."""
219237
220238 def test_module_exports_the_object_and_not_the_type (self ) -> 'None' :
@@ -279,15 +297,14 @@ def test_star_import_hands_back_the_canonical_object(self) -> 'None':
279297 test above and break every ``is`` check the sentinel exists for.
280298
281299 """
300+ canonical = importlib .import_module (CANONICAL_MODULE )
282301 for module , obj , _ in PUBLIC_SENTINELS :
283302 namespace = _star_import (module )
284303 with self .subTest (module = module ):
285- # Matched on the instance name alone: every entry in ``SENTINELS``
286- # now shares :data:`CANONICAL_MODULE`, so a ``where == module``
287- # filter against the *shim* location would no longer distinguish
288- # them -- the instance names themselves already do.
289- expected = next (instance for name , instance , _ in SENTINELS if name == obj )
290- self .assertIs (namespace [obj ], expected )
304+ # Taken from the defining module, never from the shim being star-imported:
305+ # both sides of the comparison would otherwise read the same shim attribute
306+ # and the check could not fail if a shim defined its own object.
307+ self .assertIs (namespace [obj ], getattr (canonical , obj ))
291308
292309 def test_every_sentinel_type_is_still_importable_by_name (self ) -> 'None' :
293310 """The exact extent of the breaking change: ``import *`` narrows, nothing else.
@@ -297,7 +314,7 @@ def test_every_sentinel_type_is_still_importable_by_name(self) -> 'None':
297314 relies on that -- this module's own imports are the demonstration.
298315
299316 """
300- for name , instance , type_ in SENTINELS :
317+ for name , instance , type_ in _sentinels () :
301318 with self .subTest (sentinel = name ):
302319 self .assertIs (type (instance ), type_ )
303320 self .assertEqual (type_ .__module__ , CANONICAL_MODULE )
@@ -323,7 +340,7 @@ def test_the_private_sentinel_is_exported_neither_way(self) -> 'None':
323340 self .assertNotIn ('ABSENT' , _star_import ('pcapkit.protocols.protocol' ))
324341
325342
326- class SentinelPopulationTests (unittest . TestCase ):
343+ class SentinelPopulationTests (_ReimportCase ):
327344 """There are four, they follow the naming rule, and the docs say so."""
328345
329346 def test_every_sentinel_follows_the_naming_convention (self ) -> 'None' :
@@ -332,7 +349,7 @@ def test_every_sentinel_follows_the_naming_convention(self) -> 'None':
332349 The house convention set under GitHub issue #857, kept uniform so that a
333350 future maintainer adding a sentinel can derive the type's name mechanically.
334351 """
335- for name , _ , type_ in SENTINELS :
352+ for name , _ , type_ in _sentinels () :
336353 with self .subTest (sentinel = name ):
337354 self .assertEqual (type_ .__name__ , _expected_type_name (name ))
338355
@@ -363,7 +380,7 @@ def test_every_sentinel_object_is_screaming_snake(self) -> 'None':
363380
364381 """
365382 pattern = re .compile (r'^[A-Z][A-Z0-9_]*$' )
366- for name , _ , _ in SENTINELS :
383+ for name , _ , _ in _sentinels () :
367384 with self .subTest (sentinel = name ):
368385 self .assertRegex (name , pattern )
369386
@@ -380,7 +397,7 @@ def test_conventions_doc_lists_every_sentinel_in_the_tree(self) -> 'None':
380397 """
381398 section = _sentinel_section ()
382399
383- for name , _ , type_ in SENTINELS :
400+ for name , _ , type_ in _sentinels () :
384401 with self .subTest (sentinel = name ):
385402 self .assertIn (f'``{ name } ``' , section )
386403 self .assertIn (f'``{ type_ .__name__ } ``' , section )
@@ -428,7 +445,7 @@ def test_conventions_doc_records_that_only_the_object_is_exported(self) -> 'None
428445
429446 # The ruling itself, against the module it governs rather than against prose:
430447 # every public sentinel's instance is exported and its type is not.
431- exported = set (sentinels .__all__ )
448+ exported = set (importlib . import_module ( CANONICAL_MODULE ) .__all__ )
432449 for _ , instance_name , type_name in PUBLIC_SENTINELS :
433450 with self .subTest (sentinel = instance_name ):
434451 self .assertIn (instance_name , exported ,
@@ -466,10 +483,10 @@ def test_the_sentinel_table_has_a_row_per_sentinel_and_no_more(self) -> 'None':
466483 table = table [:table .index ('\n \n ' , table .index ('- Defined in' ))]
467484
468485 rows = re .findall (r'^ \* - (\S+)$' , table , re .MULTILINE )
469- self .assertEqual (rows , ['Instance' ] + [f'``{ name } ``' for name , _ , _ in SENTINELS ])
486+ self .assertEqual (rows , ['Instance' ] + [f'``{ name } ``' for name , _ , _ in _sentinels () ])
470487
471488
472- class SentinelBehaviourTests (unittest . TestCase ):
489+ class SentinelBehaviourTests (_ReimportCase ):
473490 """The per-sentinel differences
474491 :file:`docs/source/contributing/conventions/sentinel-convention.rst`
475492 documents.
@@ -482,7 +499,8 @@ class SentinelBehaviourTests(unittest.TestCase):
482499
483500 def test_the_absent_value_sentinels_are_falsy (self ) -> 'None' :
484501 """``NULL``, ``NO_VALUE`` and ``ABSENT`` each stand for an absent value."""
485- for sentinel in (NULL , NO_VALUE , ABSENT ):
502+ live = {name : obj for name , obj , _ in _sentinels ()}
503+ for sentinel in (live ['NULL' ], live ['NO_VALUE' ], live ['ABSENT' ]):
486504 with self .subTest (sentinel = repr (sentinel )):
487505 self .assertFalse (sentinel )
488506
@@ -494,7 +512,7 @@ def test_no_default_is_deliberately_truthy(self) -> 'None':
494512 prevent.
495513
496514 """
497- self .assertTrue (NO_DEFAULT )
515+ self .assertTrue (_sentinels ()[ 2 ][ 1 ] )
498516
499517 def test_the_private_sentinel_reprs_as_its_own_name (self ) -> 'None' :
500518 """``<absent>``, not ``<object object at 0x...>``.
@@ -504,12 +522,14 @@ def test_the_private_sentinel_reprs_as_its_own_name(self) -> 'None':
504522 does not.
505523
506524 """
507- self .assertEqual (repr (ABSENT ), '<absent>' )
508- self .assertNotIn ('0x' , repr (ABSENT ))
509- self .assertNotIn ('__repr__' , vars (NoValueType ))
525+ live = _sentinels ()
526+ absent , no_value_type = live [3 ][1 ], live [1 ][2 ]
527+ self .assertEqual (repr (absent ), '<absent>' )
528+ self .assertNotIn ('0x' , repr (absent ))
529+ self .assertNotIn ('__repr__' , vars (no_value_type ))
510530
511531
512- class NoValueIsTheDocumentedFieldDefaultTests (unittest . TestCase ):
532+ class NoValueIsTheDocumentedFieldDefaultTests (_ReimportCase ):
513533 """Why the ruling reaches ``NO_VALUE`` at all.
514534
515535 ``NO_VALUE``'s own comment in :mod:`pcapkit.corekit.fields.field` reads *"Default
@@ -530,6 +550,7 @@ class NoValueIsTheDocumentedFieldDefaultTests(unittest.TestCase):
530550
531551 def test_an_undefaulted_field_reports_the_sentinel (self ) -> 'None' :
532552 """``is``, not ``==`` -- the whole point of a sentinel."""
553+ from pcapkit .corekit .fields .field import NO_VALUE
533554 from pcapkit .corekit .fields .strings import BytesField
534555
535556 self .assertIs (BytesField (length = 4 ).default , NO_VALUE )
@@ -542,6 +563,7 @@ def test_setting_and_deleting_a_default_round_trips_through_the_sentinel(self) -
542563 exactly the confusion the sentinel exists to prevent.
543564
544565 """
566+ from pcapkit .corekit .fields .field import NO_VALUE
545567 from pcapkit .corekit .fields .strings import BytesField
546568
547569 field = BytesField (length = 4 )
0 commit comments