File tree Expand file tree Collapse file tree 3 files changed +39
-0
lines changed
Filter options
Expand file tree Collapse file tree 3 files changed +39
-0
lines changed
Original file line number Diff line number Diff line change 5
5
import os
6
6
import shutil
7
7
import sys
8
+ import textwrap
8
9
import unittest
9
10
import warnings
10
11
@@ -309,3 +310,25 @@ def ready_to_import(name=None, source=""):
309
310
sys .modules [name ] = old_module
310
311
else :
311
312
sys .modules .pop (name , None )
313
+
314
+
315
+ def ensure_lazy_imports (imported_module , modules_to_block ):
316
+ """Test that when imported_module is imported, none of the modules in
317
+ modules_to_block are imported as a side effect."""
318
+ modules_to_block = frozenset (modules_to_block )
319
+ script = textwrap .dedent (
320
+ f"""
321
+ import sys
322
+ modules_to_block = { modules_to_block }
323
+ if unexpected := modules_to_block & sys.modules.keys():
324
+ startup = ", ".join(unexpected)
325
+ raise AssertionError(f'unexpectedly imported at startup: {{startup}}')
326
+
327
+ import { imported_module }
328
+ if unexpected := modules_to_block & sys.modules.keys():
329
+ after = ", ".join(unexpected)
330
+ raise AssertionError(f'unexpectedly imported after importing { imported_module } : {{after}}')
331
+ """
332
+ )
333
+ from .script_helper import assert_python_ok
334
+ assert_python_ok ("-S" , "-c" , script )
Original file line number Diff line number Diff line change 24
24
)
25
25
26
26
from test import support
27
+ from test .support import import_helper
27
28
from test .test_inspect import inspect_stock_annotations
28
29
from test .test_inspect import inspect_stringized_annotations
29
30
from test .test_inspect import inspect_stringized_annotations_2
@@ -1367,3 +1368,9 @@ def test_multiple_ways_to_create(self):
1367
1368
class TestAnnotationLib (unittest .TestCase ):
1368
1369
def test__all__ (self ):
1369
1370
support .check__all__ (self , annotationlib )
1371
+
1372
+ def test_lazy_imports (self ):
1373
+ import_helper .ensure_lazy_imports ("annotationlib" , {
1374
+ "typing" ,
1375
+ "warnings" ,
1376
+ })
Original file line number Diff line number Diff line change @@ -6317,6 +6317,15 @@ def test_collect_parameters(self):
6317
6317
typing ._collect_parameters
6318
6318
self .assertEqual (cm .filename , __file__ )
6319
6319
6320
+ def test_lazy_import (self ):
6321
+ import_helper .ensure_lazy_imports ("typing" , {
6322
+ "warnings" ,
6323
+ "inspect" ,
6324
+ "re" ,
6325
+ "contextlib" ,
6326
+ # "annotationlib", # TODO
6327
+ })
6328
+
6320
6329
6321
6330
@lru_cache ()
6322
6331
def cached_func (x , y ):
You can’t perform that action at this time.
0 commit comments