-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_defer_imports.py
1418 lines (1159 loc) · 41.9 KB
/
test_defer_imports.py
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 defer_imports.
Notes
-----
A proxy's presence in a namespace is checked via stringifying the namespace and then substring matching with the
expected proxy repr, as that's the only way to inspect it without causing it to resolve.
"""
import ast
import contextlib
import importlib.util
import sys
import threading
import time
import types
from importlib.machinery import SourceFileLoader
from pathlib import Path
from typing import Any, cast
import pytest
from defer_imports import (
_BYTECODE_HEADER,
_DEFER_PATH_HOOK,
_DeferredFileLoader,
_DeferredInstrumenter,
install_import_hook,
)
# ============================================================================
# region -------- Helpers --------
# ============================================================================
def create_sample_module(
path: Path,
source: str,
loader_type: type = _DeferredFileLoader,
defer_module_level: bool = False,
):
"""Create a sample module based on the given attributes."""
module_name = "sample"
module_path = path / f"{module_name}.py"
module_path.write_text(source, encoding="utf-8")
loader = loader_type(module_name, str(module_path))
loader.defer_module_level = defer_module_level
spec = importlib.util.spec_from_file_location(module_name, module_path, loader=loader)
assert spec
module = importlib.util.module_from_spec(spec)
return spec, module, module_path
@contextlib.contextmanager
def temp_cache_module(name: str, module: types.ModuleType):
"""Add a module to sys.modules and then attempt to remove it on exit."""
sys.modules[name] = module
try:
yield
finally:
sys.modules.pop(name, None)
@pytest.fixture(autouse=True)
def better_key_repr(monkeypatch: pytest.MonkeyPatch):
"""Replace defer_imports._comptime._DeferredImportKey.__repr__ with a more verbose version for all tests."""
def verbose_repr(self: object) -> str:
return f"<key for {super(type(self), self).__repr__()} import>"
monkeypatch.setattr("defer_imports._DeferredImportKey.__repr__", verbose_repr)
# endregion
# ============================================================================
# region -------- Unit tests --------
# ============================================================================
def test_path_hook_installation():
"""Test the API for putting/removing the defer_imports path hook from sys.path_hooks."""
# It shouldn't be on there by default.
assert _DEFER_PATH_HOOK not in sys.path_hooks
before_length = len(sys.path_hooks)
# It should be present after calling install.
hook_ctx = install_import_hook()
assert _DEFER_PATH_HOOK in sys.path_hooks
assert len(sys.path_hooks) == before_length + 1
# Calling uninstall should remove it.
hook_ctx.uninstall()
assert _DEFER_PATH_HOOK not in sys.path_hooks
assert len(sys.path_hooks) == before_length
# Calling uninstall if it's not present should do nothing to sys.path_hooks.
hook_ctx.uninstall()
assert _DEFER_PATH_HOOK not in sys.path_hooks
assert len(sys.path_hooks) == before_length
@pytest.mark.parametrize(
("before", "after"),
[
pytest.param(
"""'''Module docstring here'''""",
'''\
"""Module docstring here"""
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
del @_DeferredImportKey, @_DeferredImportProxy
''',
id="inserts statements after module docstring",
),
pytest.param(
"""from __future__ import annotations""",
"""\
from __future__ import annotations
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="Inserts statements after __future__ import",
),
pytest.param(
"""\
from contextlib import nullcontext
import defer_imports
with defer_imports.until_use, nullcontext():
import inspect
""",
"""\
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
from contextlib import nullcontext
import defer_imports
with defer_imports.until_use, nullcontext():
import inspect
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="does nothing if used with another context manager",
),
pytest.param(
"""\
import defer_imports
with defer_imports.until_use:
import inspect
""",
"""\
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
import defer_imports
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import inspect
if type(inspect) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('inspect')
@local_ns[@_DeferredImportKey('inspect', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="regular import",
),
pytest.param(
"""\
import defer_imports
with defer_imports.until_use:
import importlib
import importlib.abc
""",
"""\
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
import defer_imports
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import importlib
if type(importlib) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('importlib')
@local_ns[@_DeferredImportKey('importlib', @temp_proxy)] = @temp_proxy
import importlib.abc
if type(importlib) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('importlib')
@local_ns[@_DeferredImportKey('importlib', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="mixed imports",
),
pytest.param(
"""\
import defer_imports
with defer_imports.until_use:
from . import a
""",
"""\
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
import defer_imports
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
from . import a
if type(a) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('a')
@local_ns[@_DeferredImportKey('a', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="relative import",
),
],
)
def test_instrumentation(before: str, after: str):
"""Test what code is generated by the instrumentation side of defer_imports."""
filename = "<unknown>"
orig_tree = ast.parse(before, filename, "exec")
transformer = _DeferredInstrumenter(before, filename)
new_tree = ast.fix_missing_locations(transformer.visit(orig_tree))
assert f"{ast.unparse(new_tree)}\n" == after
@pytest.mark.parametrize(
("before", "after"),
[
pytest.param(
"""\
import inspect
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import inspect
if type(inspect) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('inspect')
@local_ns[@_DeferredImportKey('inspect', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="regular import",
),
pytest.param(
"""\
import hello
import world
import foo
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import hello
if type(hello) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('hello')
@local_ns[@_DeferredImportKey('hello', @temp_proxy)] = @temp_proxy
import world
if type(world) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('world')
@local_ns[@_DeferredImportKey('world', @temp_proxy)] = @temp_proxy
import foo
if type(foo) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('foo')
@local_ns[@_DeferredImportKey('foo', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="multiple imports consecutively",
),
pytest.param(
"""\
import hello
import world
print("hello")
import foo
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import hello
if type(hello) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('hello')
@local_ns[@_DeferredImportKey('hello', @temp_proxy)] = @temp_proxy
import world
if type(world) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('world')
@local_ns[@_DeferredImportKey('world', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
print('hello')
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import foo
if type(foo) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('foo')
@local_ns[@_DeferredImportKey('foo', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="multiple imports separated by statement 1",
),
pytest.param(
"""\
import hello
import world
def do_the_thing(a: int) -> int:
return a
import foo
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import hello
if type(hello) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('hello')
@local_ns[@_DeferredImportKey('hello', @temp_proxy)] = @temp_proxy
import world
if type(world) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('world')
@local_ns[@_DeferredImportKey('world', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
def do_the_thing(a: int) -> int:
return a
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import foo
if type(foo) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('foo')
@local_ns[@_DeferredImportKey('foo', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="multiple imports separated by statement 2",
),
pytest.param(
"""\
import hello
def do_the_thing(a: int) -> int:
import world
return a
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import hello
if type(hello) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('hello')
@local_ns[@_DeferredImportKey('hello', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
def do_the_thing(a: int) -> int:
import world
return a
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="nothing done for imports within function",
),
pytest.param(
"""\
import hello
from world import *
import foo
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import hello
if type(hello) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('hello')
@local_ns[@_DeferredImportKey('hello', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
from world import *
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import foo
if type(foo) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('foo')
@local_ns[@_DeferredImportKey('foo', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="avoids doing anything with wildcard imports",
),
pytest.param(
"""\
import foo
try:
import hello
finally:
pass
import bar
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import foo
if type(foo) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('foo')
@local_ns[@_DeferredImportKey('foo', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
try:
import hello
finally:
pass
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import bar
if type(bar) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('bar')
@local_ns[@_DeferredImportKey('bar', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="avoids imports in try-finally",
),
pytest.param(
"""\
import foo
with nullcontext():
import hello
import bar
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import foo
if type(foo) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('foo')
@local_ns[@_DeferredImportKey('foo', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
with nullcontext():
import hello
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import bar
if type(bar) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('bar')
@local_ns[@_DeferredImportKey('bar', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="avoids imports in non-defer_imports.until_use with block",
),
pytest.param(
"""\
import defer_imports
import foo
with defer_imports.until_use:
import hello
import bar
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
import defer_imports
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import foo
if type(foo) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('foo')
@local_ns[@_DeferredImportKey('foo', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import hello
if type(hello) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('hello')
@local_ns[@_DeferredImportKey('hello', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
with defer_imports.until_use:
@local_ns = locals()
@temp_proxy = None
import bar
if type(bar) is @_DeferredImportProxy:
@temp_proxy = @local_ns.pop('bar')
@local_ns[@_DeferredImportKey('bar', @temp_proxy)] = @temp_proxy
del @temp_proxy, @local_ns
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="still instruments imports in defer_imports.until_use with block",
),
pytest.param(
"""\
try:
import foo
except:
pass
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
try:
import foo
except:
pass
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="escape hatch: try",
),
pytest.param(
"""\
try:
raise Exception
except:
import foo
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
try:
raise Exception
except:
import foo
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="escape hatch: except",
),
pytest.param(
"""\
try:
print('hi')
except:
print('error')
else:
import foo
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
try:
print('hi')
except:
print('error')
else:
import foo
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="escape hatch: else",
),
pytest.param(
"""\
try:
pass
finally:
import foo
""",
"""\
import defer_imports
from defer_imports import _DeferredImportKey as @_DeferredImportKey, _DeferredImportProxy as @_DeferredImportProxy
try:
pass
finally:
import foo
del @_DeferredImportKey, @_DeferredImportProxy
""",
id="escape hatch: finally",
),
],
)
def test_module_instrumentation(before: str, after: str):
"""Test what code is generated by the instrumentation side of defer_imports if applied at a module level."""
filename = "<unknown>"
orig_tree = ast.parse(before, filename, "exec")
transformer = _DeferredInstrumenter(before, filename, module_level=True)
new_tree = ast.fix_missing_locations(transformer.visit(orig_tree))
assert f"{ast.unparse(new_tree)}\n" == after
# endregion
# ============================================================================
# region -------- Integration tests --------
# ============================================================================
def test_empty(tmp_path: Path):
source = ""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
def test_without_until_use_local(tmp_path: Path):
source = "import contextlib"
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
assert module.contextlib is sys.modules["contextlib"]
def test_until_use_noop(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
import inspect
"""
spec, module, _ = create_sample_module(tmp_path, source, SourceFileLoader)
assert spec.loader
spec.loader.exec_module(module)
expected_partial_inspect_repr = "'inspect': <module 'inspect' from"
assert expected_partial_inspect_repr in repr(vars(module))
assert module.inspect is sys.modules["inspect"]
def sample_func(a: int, c: float) -> float: ...
assert str(module.inspect.signature(sample_func)) == "(a: int, c: float) -> float"
def test_regular_import(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
import inspect
"""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
expected_inspect_repr = "<key for 'inspect' import>: <proxy for 'import inspect'>"
assert expected_inspect_repr in repr(vars(module))
assert module.inspect
assert expected_inspect_repr not in repr(vars(module))
assert module.inspect is sys.modules["inspect"]
def sample_func(a: int, c: float) -> float: ...
assert str(module.inspect.signature(sample_func)) == "(a: int, c: float) -> float"
def test_regular_import_with_rename(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
import inspect as gin
"""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
expected_gin_repr = "<key for 'gin' import>: <proxy for 'import inspect'>"
assert expected_gin_repr in repr(vars(module))
with pytest.raises(NameError):
exec("inspect", vars(module))
with pytest.raises(AttributeError):
assert module.inspect
assert expected_gin_repr in repr(vars(module))
assert module.gin
assert expected_gin_repr not in repr(vars(module))
assert sys.modules["inspect"] is module.gin
def sample_func(a: int, b: str) -> str: ...
assert str(module.gin.signature(sample_func)) == "(a: int, b: str) -> str"
def test_regular_import_nested(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
import importlib.abc
"""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
expected_importlib_repr = "<key for 'importlib' import>: <proxy for 'import importlib.abc'>"
assert expected_importlib_repr in repr(vars(module))
assert module.importlib
assert module.importlib.abc
assert module.importlib.abc.MetaPathFinder
assert expected_importlib_repr not in repr(vars(module))
def test_regular_import_nested_with_rename(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
import collections.abc as xyz
"""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
# Make sure the right proxy is in the namespace.
expected_xyz_repr = "<key for 'xyz' import>: <proxy for 'import collections.abc as ...'>"
assert expected_xyz_repr in repr(vars(module))
# Make sure the intermediate imports or proxies for them aren't in the namespace.
with pytest.raises(NameError):
exec("collections", vars(module))
with pytest.raises(AttributeError):
assert module.collections
with pytest.raises(NameError):
exec("collections.abc", vars(module))
with pytest.raises(AttributeError):
assert module.collections.abc
# Make sure xyz resolves properly.
assert expected_xyz_repr in repr(vars(module))
assert module.xyz
assert expected_xyz_repr not in repr(vars(module))
assert module.xyz is sys.modules["collections"].abc
# Make sure only the resolved xyz remains in the namespace.
with pytest.raises(NameError):
exec("collections", vars(module))
with pytest.raises(AttributeError):
assert module.collections
with pytest.raises(NameError):
exec("collections.abc", vars(module))
with pytest.raises(AttributeError):
assert module.collections.abc
def test_from_import(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
from inspect import isfunction, signature
"""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
expected_isfunction_repr = "<key for 'isfunction' import>: <proxy for 'from inspect import isfunction'>"
expected_signature_repr = "<key for 'signature' import>: <proxy for 'from inspect import signature'>"
assert expected_isfunction_repr in repr(vars(module))
assert expected_signature_repr in repr(vars(module))
with pytest.raises(NameError):
exec("inspect", vars(module))
assert expected_isfunction_repr in repr(vars(module))
assert module.isfunction
assert expected_isfunction_repr not in repr(vars(module))
assert module.isfunction is sys.modules["inspect"].isfunction
assert expected_signature_repr in repr(vars(module))
assert module.signature
assert expected_signature_repr not in repr(vars(module))
assert module.signature is sys.modules["inspect"].signature
def test_from_import_with_rename(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
from inspect import Signature as MySignature
"""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
expected_my_signature_repr = "<key for 'MySignature' import>: <proxy for 'from inspect import Signature'>"
assert expected_my_signature_repr in repr(vars(module))
with pytest.raises(NameError):
exec("inspect", vars(module))
with pytest.raises(NameError):
exec("Signature", vars(module))
assert expected_my_signature_repr in repr(vars(module))
assert str(module.MySignature) == "<class 'inspect.Signature'>" # Resolves on use.
assert expected_my_signature_repr not in repr(vars(module))
assert module.MySignature is sys.modules["inspect"].Signature
def test_deferred_header_in_instrumented_pycache(tmp_path: Path):
"""Test that the defer_imports-specific bytecode header is being prepended to the bytecode cache files of
defer_imports-instrumented modules.
"""
source = """\
import defer_imports
with defer_imports.until_use:
import asyncio
"""
spec, module, path = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
expected_cache = Path(importlib.util.cache_from_source(str(path)))
assert expected_cache.is_file()
with expected_cache.open("rb") as fp:
header = fp.read(len(_BYTECODE_HEADER))
assert header == _BYTECODE_HEADER
def test_error_if_non_import(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
print("Hello world")
"""
spec, module, module_path = create_sample_module(tmp_path, source)
assert spec.loader
with pytest.raises(SyntaxError) as exc_info:
spec.loader.exec_module(module)
assert exc_info.value.filename == str(module_path)
assert exc_info.value.lineno == 4
assert exc_info.value.offset == 5
assert exc_info.value.text == 'print("Hello world")'
def test_error_if_import_in_class(tmp_path: Path):
source = """\
import defer_imports
class Example:
with defer_imports.until_use:
from inspect import signature
"""
# Boilerplate to dynamically create and load this module.
spec, module, module_path = create_sample_module(tmp_path, source)
assert spec.loader
with pytest.raises(SyntaxError) as exc_info:
spec.loader.exec_module(module)
assert exc_info.value.filename == str(module_path)
assert exc_info.value.lineno == 4
assert exc_info.value.offset == 5
assert exc_info.value.text == " with defer_imports.until_use:\n from inspect import signature"
def test_error_if_import_in_function(tmp_path: Path):
source = """\
import defer_imports
def test():
with defer_imports.until_use:
import inspect
return inspect.signature(test)
"""
spec, module, module_path = create_sample_module(tmp_path, source)
assert spec.loader
with pytest.raises(SyntaxError) as exc_info:
spec.loader.exec_module(module)
assert exc_info.value.filename == str(module_path)
assert exc_info.value.lineno == 4
assert exc_info.value.offset == 5
assert exc_info.value.text == " with defer_imports.until_use:\n import inspect"
def test_error_if_wildcard_import(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
from typing import *
"""
spec, module, module_path = create_sample_module(tmp_path, source)
assert spec.loader
with pytest.raises(SyntaxError) as exc_info:
spec.loader.exec_module(module)
assert exc_info.value.filename == str(module_path)
assert exc_info.value.lineno == 4
assert exc_info.value.offset == 5
assert exc_info.value.text == "from typing import *"
def test_top_level_and_submodules_1(tmp_path: Path):
source = """\
import defer_imports
with defer_imports.until_use:
import importlib
import importlib.abc
import importlib.util
"""
spec, module, _ = create_sample_module(tmp_path, source)
assert spec.loader
spec.loader.exec_module(module)
# Prevent the caching of these from interfering with the test.
for mod in ("importlib", "importlib.abc", "importlib.util"):
sys.modules.pop(mod, None)
expected_importlib_repr = "<key for 'importlib' import>: <proxy for 'import importlib'>"
expected_importlib_abc_repr = "<key for 'abc' import>: <proxy for 'import importlib.abc as ...'>"
expected_importlib_util_repr = "<key for 'util' import>: <proxy for 'import importlib.util as ...'>"
# Test that the importlib proxy is here and then resolves.
assert expected_importlib_repr in repr(vars(module))
assert module.importlib
assert expected_importlib_repr not in repr(vars(module))
# Test that the nested proxies carry over to the resolved importlib.
module_importlib_vars = cast(dict[str, object], vars(module.importlib))
assert expected_importlib_abc_repr in repr(module_importlib_vars)
assert expected_importlib_util_repr in repr(module_importlib_vars)
assert expected_importlib_abc_repr in repr(module_importlib_vars)
assert module.importlib.abc
assert expected_importlib_abc_repr not in repr(module_importlib_vars)
assert expected_importlib_util_repr in repr(module_importlib_vars)
assert module.importlib.util
assert expected_importlib_util_repr not in repr(module_importlib_vars)