@@ -551,17 +551,41 @@ def test_invalid_descendant_retries(self):
551551 assert callable(test.test_lazy_import.data.pkg.b.foo)
552552 """ )
553553
554- def test_namespace_import_hooks (self ):
555- self .check ("""
554+ @support .subTests ('copied_builtins' , (False , True ))
555+ @support .subTests ('reverse' , (False , True ))
556+ def test_namespace_import_hooks (self , copied_builtins , reverse ):
557+ self .check (f"""
556558 import builtins
557- first = {'__builtins__': vars(builtins).copy()}
558- second = {'__builtins__': vars(builtins).copy()}
559- exec('lazy import xml.dom', first)
560- exec('lazy import xml.dom', second)
559+ first = {{'__builtins__': vars(builtins)}}
560+ if { copied_builtins !r} :
561+ first['__builtins__'] = vars(builtins).copy()
562+ second = {{'__builtins__': vars(builtins).copy()}}
563+ for namespace in (first, second)[::{ - 1 if reverse else 1 } ]:
564+ exec('lazy import xml.dom', namespace)
561565 def denied(*args):
562- raise AssertionError('used another namespace import hook')
566+ raise RuntimeError('private import hook')
563567 second['__builtins__']['__import__'] = denied
564568 exec('assert xml.dom.__name__ == "xml.dom"', first)
569+ try:
570+ exec('xml.dom', second)
571+ except RuntimeError as exc:
572+ assert str(exc) == 'private import hook', exc
573+ else:
574+ raise AssertionError('private import hook was not called')
575+ """ )
576+
577+ @support .subTests ('statement' , (
578+ 'lazy import xml.dom' ,
579+ 'lazy from xml import dom' ,
580+ ))
581+ def test_shared_child_ignores_private_import_hook (self , statement ):
582+ self .check (f"""
583+ import builtins, sys, xml
584+ def denied(*args):
585+ raise AssertionError('used a private namespace import hook')
586+ namespace = {{'__builtins__': dict(vars(builtins), __import__=denied)}}
587+ exec({ statement !r} , namespace)
588+ assert xml.dom is sys.modules['xml.dom']
565589 """ )
566590
567591 def test_retry_after_recursive_access (self ):
0 commit comments