forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_lazy_imports.py
More file actions
1721 lines (1384 loc) · 64.1 KB
/
test_lazy_imports.py
File metadata and controls
1721 lines (1384 loc) · 64.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Tests for PEP 810 lazy imports."""
import io
import dis
import subprocess
import sys
import textwrap
import threading
import types
import unittest
import tempfile
import os
try:
import _testcapi
except ImportError:
_testcapi = None
class LazyImportTests(unittest.TestCase):
"""Tests for basic lazy import functionality."""
def tearDown(self):
"""Clean up any test modules from sys.modules."""
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
sys.lazy_modules.clear()
def test_basic_unused(self):
"""Lazy imported module should not be loaded if never accessed."""
import test.test_import.data.lazy_imports.basic_unused
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
self.assertIn("test.test_import.data.lazy_imports", sys.lazy_modules)
self.assertEqual(sys.lazy_modules["test.test_import.data.lazy_imports"], {"basic2"})
def test_sys_lazy_modules(self):
try:
import test.test_import.data.lazy_imports.basic_from_unused
except ImportError as e:
self.fail('lazy import failed')
self.assertFalse("test.test_import.data.lazy_imports.basic2" in sys.modules)
self.assertIn("test.test_import.data.lazy_imports", sys.lazy_modules)
self.assertEqual(sys.lazy_modules["test.test_import.data.lazy_imports"], {"basic2"})
test.test_import.data.lazy_imports.basic_from_unused.basic2
self.assertNotIn("test.test_import.data", sys.lazy_modules)
def test_basic_unused_use_externally(self):
"""Lazy import should load module when accessed from outside."""
from test.test_import.data.lazy_imports import basic_unused
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
x = basic_unused.test.test_import.data.lazy_imports.basic2
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_basic_from_unused_use_externally(self):
"""Lazy 'from' import should load when accessed from outside."""
from test.test_import.data.lazy_imports import basic_from_unused
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
x = basic_from_unused.basic2
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_basic_unused_dir(self):
"""dir() on module should not trigger lazy import reification."""
import test.test_import.data.lazy_imports.basic_unused
x = dir(test.test_import.data.lazy_imports.basic_unused)
self.assertIn("test", x)
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_basic_dir(self):
"""dir() at module scope should not trigger lazy import reification."""
from test.test_import.data.lazy_imports import basic_dir
self.assertIn("test", basic_dir.x)
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_basic_used(self):
"""Lazy import should load when accessed within the module."""
import test.test_import.data.lazy_imports.basic_used
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
class GlobalLazyImportModeTests(unittest.TestCase):
"""Tests for sys.set_lazy_imports() global mode control."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_global_off(self):
"""Mode 'none' should disable lazy imports entirely."""
import test.test_import.data.lazy_imports.global_off
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_global_on(self):
"""Mode 'all' should make regular imports lazy."""
import test.test_import.data.lazy_imports.global_on
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_global_filter(self):
"""Filter returning False should prevent lazy loading."""
import test.test_import.data.lazy_imports.global_filter
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_global_filter_true(self):
"""Filter returning True should allow lazy loading."""
import test.test_import.data.lazy_imports.global_filter_true
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_global_filter_from(self):
"""Filter should work with 'from' imports."""
import test.test_import.data.lazy_imports.global_filter
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_global_filter_from_true(self):
"""Filter returning True should allow lazy 'from' imports."""
import test.test_import.data.lazy_imports.global_filter_true
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
class CompatibilityModeTests(unittest.TestCase):
"""Tests for __lazy_modules__ compatibility mode."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_compatibility_mode(self):
"""__lazy_modules__ should enable lazy imports for listed modules."""
import test.test_import.data.lazy_imports.basic_compatibility_mode
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_compatibility_mode_used(self):
"""Using a lazy import from __lazy_modules__ should load the module."""
import test.test_import.data.lazy_imports.basic_compatibility_mode_used
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_compatibility_mode_func(self):
"""Imports inside functions should be eager even in compatibility mode."""
import test.test_import.data.lazy_imports.compatibility_mode_func
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_compatibility_mode_try_except(self):
"""Imports in try/except should be eager even in compatibility mode."""
import test.test_import.data.lazy_imports.compatibility_mode_try_except
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_compatibility_mode_relative(self):
"""__lazy_modules__ should work with relative imports."""
import test.test_import.data.lazy_imports.basic_compatibility_mode_relative
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
class ModuleIntrospectionTests(unittest.TestCase):
"""Tests for module dict and getattr behavior with lazy imports."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_modules_dict(self):
"""Accessing module.__dict__ should not trigger reification."""
import test.test_import.data.lazy_imports.modules_dict
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_modules_getattr(self):
"""Module __getattr__ for lazy import name should trigger reification."""
import test.test_import.data.lazy_imports.modules_getattr
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_modules_getattr_other(self):
"""Module __getattr__ for other names should not trigger reification."""
import test.test_import.data.lazy_imports.modules_getattr_other
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
class LazyImportTypeTests(unittest.TestCase):
"""Tests for the LazyImportType and its resolve() method."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_lazy_value_resolve(self):
"""resolve() method should force the lazy import to load."""
import test.test_import.data.lazy_imports.lazy_get_value
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_lazy_import_type_exposed(self):
"""LazyImportType should be exposed in types module."""
self.assertHasAttr(types, 'LazyImportType')
self.assertEqual(types.LazyImportType.__name__, 'lazy_import')
def test_lazy_import_type_cant_construct(self):
"""LazyImportType should not be directly constructible."""
self.assertRaises(TypeError, types.LazyImportType, {}, "module")
class SyntaxRestrictionTests(unittest.TestCase):
"""Tests for syntax restrictions on lazy imports."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_lazy_try_except(self):
"""lazy import inside try/except should raise SyntaxError."""
with self.assertRaises(SyntaxError):
import test.test_import.data.lazy_imports.lazy_try_except
def test_lazy_try_except_from(self):
"""lazy from import inside try/except should raise SyntaxError."""
with self.assertRaises(SyntaxError):
import test.test_import.data.lazy_imports.lazy_try_except_from
def test_lazy_try_except_from_star(self):
"""lazy from import * should raise SyntaxError."""
with self.assertRaises(SyntaxError):
import test.test_import.data.lazy_imports.lazy_try_except_from_star
def test_lazy_future_import(self):
"""lazy from __future__ import should raise SyntaxError."""
with self.assertRaises(SyntaxError) as cm:
import test.test_import.data.lazy_imports.lazy_future_import
# Check we highlight 'lazy' (column offset 0, end offset 4)
self.assertEqual(cm.exception.offset, 1)
self.assertEqual(cm.exception.end_offset, 5)
def test_lazy_import_func(self):
"""lazy import inside function should raise SyntaxError."""
with self.assertRaises(SyntaxError):
import test.test_import.data.lazy_imports.lazy_import_func
def test_lazy_import_exec_in_function(self):
"""lazy import via exec() inside a function should raise SyntaxError."""
# exec() inside a function creates a non-module-level context
# where lazy imports are not allowed
def f():
exec("lazy import json")
with self.assertRaises(SyntaxError) as cm:
f()
self.assertIn("only allowed at module level", str(cm.exception))
def test_lazy_import_exec_at_module_level(self):
"""lazy import via exec() at module level should work."""
# exec() at module level (globals == locals) should allow lazy imports
code = textwrap.dedent("""
import sys
exec("lazy import json")
# Should be lazy - not loaded yet
assert 'json' not in sys.modules
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
class EagerImportInLazyModeTests(unittest.TestCase):
"""Tests for imports that should remain eager even in lazy mode."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_try_except_eager(self):
"""Imports in try/except should be eager even with mode='all'."""
sys.set_lazy_imports("all")
import test.test_import.data.lazy_imports.try_except_eager
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_try_except_eager_from(self):
"""From imports in try/except should be eager even with mode='all'."""
sys.set_lazy_imports("all")
import test.test_import.data.lazy_imports.try_except_eager_from
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_eager_import_func(self):
"""Imports inside functions should return modules, not proxies."""
sys.set_lazy_imports("all")
import test.test_import.data.lazy_imports.eager_import_func
f = test.test_import.data.lazy_imports.eager_import_func.f
self.assertEqual(type(f()), type(sys))
class WithStatementTests(unittest.TestCase):
"""Tests for lazy imports in with statement context."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_lazy_with(self):
"""lazy import with 'with' statement should work."""
import test.test_import.data.lazy_imports.lazy_with
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_lazy_with_from(self):
"""lazy from import with 'with' statement should work."""
import test.test_import.data.lazy_imports.lazy_with_from
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
class PackageTests(unittest.TestCase):
"""Tests for lazy imports with packages."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_lazy_import_pkg(self):
"""lazy import of package submodule should load the package."""
import test.test_import.data.lazy_imports.lazy_import_pkg
self.assertIn("test.test_import.data.lazy_imports.pkg", sys.modules)
self.assertIn("test.test_import.data.lazy_imports.pkg.bar", sys.modules)
def test_lazy_import_pkg_cross_import(self):
"""Cross-imports within package should preserve lazy imports."""
import test.test_import.data.lazy_imports.pkg.c
self.assertIn("test.test_import.data.lazy_imports.pkg", sys.modules)
self.assertIn("test.test_import.data.lazy_imports.pkg.c", sys.modules)
self.assertNotIn("test.test_import.data.lazy_imports.pkg.b", sys.modules)
g = test.test_import.data.lazy_imports.pkg.c.get_globals()
self.assertEqual(type(g["x"]), int)
self.assertEqual(type(g["b"]), types.LazyImportType)
class DunderLazyImportTests(unittest.TestCase):
"""Tests for __lazy_import__ builtin function."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_dunder_lazy_import(self):
"""__lazy_import__ should create lazy import proxy."""
import test.test_import.data.lazy_imports.dunder_lazy_import
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_dunder_lazy_import_used(self):
"""Using __lazy_import__ result should trigger module load."""
import test.test_import.data.lazy_imports.dunder_lazy_import_used
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_dunder_lazy_import_invalid_arguments(self):
"""__lazy_import__ should reject invalid arguments."""
for invalid_name in (b"", 123, None):
with self.assertRaises(TypeError):
__lazy_import__(invalid_name)
with self.assertRaises(ValueError):
__lazy_import__("sys", level=-1)
def test_dunder_lazy_import_builtins(self):
"""__lazy_import__ should use module's __builtins__ for __import__."""
from test.test_import.data.lazy_imports import dunder_lazy_import_builtins
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
self.assertEqual(dunder_lazy_import_builtins.basic.basic2, 42)
def test_dunder_lazy_import_argument_validation(self):
"""__lazy_import__ should strictly validate argument types to avoid SystemError."""
invalid_type_scenarios = [
(123, {}, {}, [], 0, "argument 1 must be str"),
('os', 1, {}, [], 0, "argument 2 must be dict"),
('os', {}, "not_a_dict", [], 0, "argument 3 must be dict"),
('os', {}, {}, 42, 0, "argument 4 must be a list or tuple"),
('os', {}, {}, "string_instead_of_list", 0, "argument 4 must be a list or tuple"),
]
for name, glbs, lcls, flist, lvl, msg in invalid_type_scenarios:
with self.subTest(case=msg):
with self.assertRaisesRegex(TypeError, msg):
__lazy_import__(name, glbs, lcls, flist, lvl)
class SysLazyImportsAPITests(unittest.TestCase):
"""Tests for sys lazy imports API functions."""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_set_lazy_imports_requires_string(self):
"""set_lazy_imports should reject non-string arguments."""
with self.assertRaises(TypeError):
sys.set_lazy_imports(True)
with self.assertRaises(TypeError):
sys.set_lazy_imports(None)
with self.assertRaises(TypeError):
sys.set_lazy_imports(1)
def test_set_lazy_imports_rejects_invalid_mode(self):
"""set_lazy_imports should reject invalid mode strings."""
with self.assertRaises(ValueError):
sys.set_lazy_imports("invalid")
with self.assertRaises(ValueError):
sys.set_lazy_imports("on")
with self.assertRaises(ValueError):
sys.set_lazy_imports("off")
def test_get_lazy_imports_returns_string(self):
"""get_lazy_imports should return string modes."""
sys.set_lazy_imports("normal")
self.assertEqual(sys.get_lazy_imports(), "normal")
sys.set_lazy_imports("all")
self.assertEqual(sys.get_lazy_imports(), "all")
sys.set_lazy_imports("none")
self.assertEqual(sys.get_lazy_imports(), "none")
def test_get_lazy_imports_filter_default(self):
"""get_lazy_imports_filter should return None by default."""
sys.set_lazy_imports_filter(None)
self.assertIsNone(sys.get_lazy_imports_filter())
def test_set_and_get_lazy_imports_filter(self):
"""set/get_lazy_imports_filter should round-trip filter function."""
def my_filter(name):
return name.startswith("test.")
sys.set_lazy_imports_filter(my_filter)
self.assertIs(sys.get_lazy_imports_filter(), my_filter)
def test_lazy_modules_attribute_is_set(self):
"""sys.lazy_modules should be a set per PEP 810."""
self.assertIsInstance(sys.lazy_modules, dict)
def test_lazy_modules_tracks_lazy_imports(self):
"""sys.lazy_modules should track lazily imported module names."""
code = textwrap.dedent("""
import sys
initial_count = len(sys.lazy_modules)
import test.test_import.data.lazy_imports.basic_unused
assert "test.test_import.data.lazy_imports" in sys.lazy_modules
assert sys.lazy_modules["test.test_import.data.lazy_imports"] == {"basic2"}
assert len(sys.lazy_modules) > initial_count
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
class ErrorHandlingTests(unittest.TestCase):
"""Tests for error handling during lazy import reification.
PEP 810: Errors during reification should show exception chaining with
both the lazy import definition location and the access location.
"""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_import_error_shows_chained_traceback(self):
"""ImportError during reification should chain to show both definition and access."""
# Errors at reification must show where the lazy import was defined
# AND where the access happened, per PEP 810 "Reification" section
code = textwrap.dedent("""
import sys
lazy import test.test_import.data.lazy_imports.nonexistent_module
try:
x = test.test_import.data.lazy_imports.nonexistent_module
except ImportError as e:
# Should have __cause__ showing the original error
# The exception chain shows both where import was defined and where access happened
assert e.__cause__ is not None, "Expected chained exception"
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_attribute_error_on_from_import_shows_chained_traceback(self):
"""Accessing missing attribute from lazy from-import should chain errors."""
# Tests 'lazy from module import nonexistent' behavior
code = textwrap.dedent("""
import sys
lazy from test.test_import.data.lazy_imports.basic2 import nonexistent_name
try:
x = nonexistent_name
except ImportError as e:
# PEP 810: Enhanced error reporting through exception chaining
assert e.__cause__ is not None, "Expected chained exception"
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_reification_retries_on_failure(self):
"""Failed reification should allow retry on subsequent access.
PEP 810: "If reification fails, the lazy object is not reified or replaced.
Subsequent uses of the lazy object will re-try the reification."
"""
code = textwrap.dedent("""
import sys
import types
lazy import test.test_import.data.lazy_imports.broken_module
# First access - should fail
try:
x = test.test_import.data.lazy_imports.broken_module
except ValueError:
pass
# The lazy object should still be a lazy proxy (not reified)
g = globals()
lazy_obj = g['test']
# The root 'test' binding should still allow retry
# Second access - should also fail (retry the import)
try:
x = test.test_import.data.lazy_imports.broken_module
except ValueError:
print("OK - retry worked")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_error_during_module_execution_propagates(self):
"""Errors in module code during reification should propagate correctly."""
# Module that raises during import should propagate with chaining
code = textwrap.dedent("""
import sys
lazy import test.test_import.data.lazy_imports.broken_module
try:
_ = test.test_import.data.lazy_imports.broken_module
print("FAIL - should have raised")
except ValueError as e:
# The ValueError from the module should be the cause
if "always fails" in str(e) or (e.__cause__ and "always fails" in str(e.__cause__)):
print("OK")
else:
print(f"FAIL - wrong error: {e}")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_circular_lazy_import_does_not_crash_for_gh_144727(self):
with tempfile.TemporaryDirectory() as tmpdir:
a_path = os.path.join(tmpdir, "a.py")
b_path = os.path.join(tmpdir, "b.py")
with open(a_path, "w") as f:
f.write(textwrap.dedent("""\
lazy import b
def something():
b.hello()
something()
"""))
with open(b_path, "w") as f:
f.write(textwrap.dedent("""\
lazy import a
def hello():
print(a)
"""))
result = subprocess.run(
[sys.executable, a_path],
capture_output=True,
text=True,
cwd=tmpdir,
)
# Should get a proper Python error, not a crash
self.assertEqual(result.returncode, 1)
self.assertIn("Error", result.stderr)
class GlobalsAndDictTests(unittest.TestCase):
"""Tests for globals() and __dict__ behavior with lazy imports.
PEP 810: "Calling globals() or accessing a module's __dict__ does not trigger
reification – they return the module's dictionary, and accessing lazy objects
through that dictionary still returns lazy proxy objects."
"""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_globals_returns_lazy_proxy_when_accessed_from_function(self):
"""globals() accessed from a function should return lazy proxy without reification.
Note: At module level, accessing globals()['name'] triggers LOAD_NAME which
automatically resolves lazy imports. Inside a function, accessing globals()['name']
uses BINARY_SUBSCR which returns the lazy proxy without resolution.
"""
code = textwrap.dedent("""
import sys
import types
lazy from test.test_import.data.lazy_imports.basic2 import x
# Check that module is not yet loaded
assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
def check_lazy():
# Access through globals() from inside a function
g = globals()
lazy_obj = g['x']
return type(lazy_obj) is types.LazyImportType
# Inside function, should get lazy proxy
is_lazy = check_lazy()
assert is_lazy, "Expected LazyImportType from function scope"
# Module should STILL not be loaded
assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_globals_dict_access_returns_lazy_proxy_inline(self):
"""Accessing globals()['name'] inline should return lazy proxy.
Note: Assigning g['name'] to a local variable at module level triggers
reification due to STORE_NAME bytecode. Inline access preserves laziness.
"""
code = textwrap.dedent("""
import sys
import types
lazy import json
# Inline access without assignment to local variable preserves lazy proxy
assert type(globals()['json']) is types.LazyImportType
assert 'json' not in sys.modules
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_module_dict_returns_lazy_proxy_without_reifying(self):
"""module.__dict__ access should not trigger reification."""
import test.test_import.data.lazy_imports.globals_access
# Module not loaded yet via direct dict access
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
# Access via get_from_globals should return lazy proxy
lazy_obj = test.test_import.data.lazy_imports.globals_access.get_from_globals()
self.assertEqual(type(lazy_obj), types.LazyImportType)
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_direct_access_triggers_reification(self):
"""Direct name access (not through globals()) should trigger reification."""
import test.test_import.data.lazy_imports.globals_access
self.assertNotIn("test.test_import.data.lazy_imports.basic2", sys.modules)
# Direct access should reify
result = test.test_import.data.lazy_imports.globals_access.get_direct()
self.assertIn("test.test_import.data.lazy_imports.basic2", sys.modules)
def test_resolve_method_forces_reification(self):
"""Calling resolve() on lazy proxy should force reification.
Note: Must access lazy proxy from within a function to avoid automatic
reification by LOAD_NAME at module level.
"""
code = textwrap.dedent("""
import sys
import types
lazy from test.test_import.data.lazy_imports.basic2 import x
assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
def test_resolve():
g = globals()
lazy_obj = g['x']
assert type(lazy_obj) is types.LazyImportType, f"Expected lazy proxy, got {type(lazy_obj)}"
resolved = lazy_obj.resolve()
# Now module should be loaded
assert 'test.test_import.data.lazy_imports.basic2' in sys.modules
assert resolved == 42 # x is 42 in basic2.py
return True
assert test_resolve()
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_add_lazy_to_globals(self):
code = textwrap.dedent("""
import sys
import types
lazy from test.test_import.data.lazy_imports import basic2
assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
class C: pass
sneaky = C()
sneaky.x = 1
def f():
t = 0
for _ in range(5):
t += sneaky.x
return t
f()
globals()["sneaky"] = globals()["basic2"]
assert f() == 210
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
class MultipleNameFromImportTests(unittest.TestCase):
"""Tests for lazy from ... import with multiple names.
PEP 810: "When using lazy from ... import, each imported name is bound to a
lazy proxy object. The first access to any of these names triggers loading
of the entire module and reifies only that specific name to its actual value.
Other names remain as lazy proxies until they are accessed."
"""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_accessing_one_name_leaves_others_as_proxies(self):
"""Accessing one name from multi-name import should leave others lazy."""
code = textwrap.dedent("""
import sys
import types
lazy from test.test_import.data.lazy_imports.basic2 import f, x
# Neither should be loaded yet
assert 'test.test_import.data.lazy_imports.basic2' not in sys.modules
g = globals()
assert type(g['f']) is types.LazyImportType
assert type(g['x']) is types.LazyImportType
# Access 'x' - this loads the module and reifies only 'x'
value = x
assert value == 42
# Module is now loaded
assert 'test.test_import.data.lazy_imports.basic2' in sys.modules
# 'x' should be reified (int), 'f' should still be lazy proxy
assert type(g['x']) is int, f"Expected int, got {type(g['x'])}"
assert type(g['f']) is types.LazyImportType, f"Expected LazyImportType, got {type(g['f'])}"
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_all_names_reified_after_all_accessed(self):
"""All names should be reified after each is accessed."""
code = textwrap.dedent("""
import sys
import types
lazy from test.test_import.data.lazy_imports.basic2 import f, x
g = globals()
# Access both
_ = x
_ = f
# Both should be reified now
assert type(g['x']) is int
assert callable(g['f'])
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
class SysLazyModulesTrackingTests(unittest.TestCase):
"""Tests for sys.lazy_modules tracking behavior.
PEP 810: "When the module is reified, it's removed from sys.lazy_modules"
"""
def tearDown(self):
for key in list(sys.modules.keys()):
if key.startswith('test.test_import.data.lazy_imports'):
del sys.modules[key]
sys.set_lazy_imports_filter(None)
sys.set_lazy_imports("normal")
def test_module_added_to_lazy_modules_on_lazy_import(self):
"""Module should be added to sys.lazy_modules when lazily imported."""
# PEP 810 states lazy_modules tracks modules that have been lazily imported
# Note: The current implementation keeps modules in lazy_modules even after
# reification (primarily for diagnostics and introspection)
code = textwrap.dedent("""
import sys
initial_count = len(sys.lazy_modules)
lazy import test.test_import.data.lazy_imports.basic2
# Should be in lazy_modules after lazy import
assert "test.test_import.data.lazy_imports" in sys.lazy_modules
assert sys.lazy_modules["test.test_import.data.lazy_imports"] == {"basic2"}
assert len(sys.lazy_modules) > initial_count
# Trigger reification
_ = test.test_import.data.lazy_imports.basic2.x
# Module should still be tracked (for diagnostics per PEP 810)
assert "test.test_import.data.lazy_imports" not in sys.lazy_modules
print("OK")
""")
result = subprocess.run(
[sys.executable, "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stdout: {result.stdout}, stderr: {result.stderr}")
self.assertIn("OK", result.stdout)
def test_lazy_modules_is_per_interpreter(self):
"""Each interpreter should have independent sys.lazy_modules."""
# Basic test that sys.lazy_modules exists and is a set
self.assertIsInstance(sys.lazy_modules, dict)
class CommandLineAndEnvVarTests(unittest.TestCase):
"""Tests for command-line and environment variable control.
PEP 810: The global lazy imports flag can be controlled through:
- The -X lazy_imports=<mode> command-line option
- The PYTHON_LAZY_IMPORTS=<mode> environment variable
"""
def test_cli_lazy_imports_all_makes_regular_imports_lazy(self):
"""-X lazy_imports=all should make all imports potentially lazy."""
code = textwrap.dedent("""
import sys
# In 'all' mode, regular imports become lazy
import json
# json should not be in sys.modules yet (lazy)
# Actually accessing it triggers reification
if 'json' not in sys.modules:
print("LAZY")
else:
print("EAGER")
""")
result = subprocess.run(
[sys.executable, "-X", "lazy_imports=all", "-c", code],
capture_output=True,
text=True
)
self.assertEqual(result.returncode, 0, f"stderr: {result.stderr}")
self.assertIn("LAZY", result.stdout)
def test_cli_lazy_imports_none_forces_all_imports_eager(self):
"""-X lazy_imports=none should force all imports to be eager."""
code = textwrap.dedent("""
import sys
# Even explicit lazy imports should be eager in 'none' mode
lazy import json
if 'json' in sys.modules:
print("EAGER")
else:
print("LAZY")