Skip to content

Commit 48f43b7

Browse files
committed
tests: Add tests for overriding builtins.__import__.
1 parent f60229e commit 48f43b7

2 files changed

Lines changed: 35 additions & 0 deletions

File tree

tests/basics/builtin_override.py

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,25 @@
1212
print(abs(1))
1313

1414
# __build_class__ is handled in a special way
15+
orig_build_class = __build_class__
1516
builtins.__build_class__ = lambda x, y: ('class', y)
1617
class A:
1718
pass
1819
print(A)
20+
builtins.__build_class__ = orig_build_class
21+
22+
# __import__ is handled in a special way
23+
def custom_import(name, globals, locals, fromlist, level):
24+
print('import', name, fromlist, level)
25+
class M:
26+
a = 1
27+
b = 2
28+
return M
29+
builtins.__import__ = custom_import
30+
__import__('A', None, None, None, 0)
31+
import a
32+
import a.b
33+
from a import a
34+
from a.b import a, b
35+
from .a import a
36+
from ..a import a, b

tests/import/import_override.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# test overriding __import__ combined with importing from the filesystem
2+
3+
def custom_import(name, globals, locals, fromlist, level):
4+
print('import', name, fromlist, level)
5+
class M:
6+
var = 456
7+
return M
8+
9+
orig_import = __import__
10+
try:
11+
__import__("builtins").__import__ = custom_import
12+
except AttributeError:
13+
print("SKIP")
14+
raise SystemExit
15+
16+
# import1a will be done via normal import which will import1b via our custom import
17+
orig_import('import1a')

0 commit comments

Comments
 (0)