Skip to content

Commit 391e1de

Browse files
Lisa CarrierLisa Carrier
authored andcommitted
Adds sys.audit event for import_module.
1 parent f58a7c7 commit 391e1de

File tree

3 files changed

+31
-1
lines changed

3 files changed

+31
-1
lines changed

Lib/importlib/__init__.py

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,18 @@ def import_module(name, package=None):
8585
if character != '.':
8686
break
8787
level += 1
88-
return _bootstrap._gcd_import(name[level:], package, level)
88+
module = _bootstrap._gcd_import(name[level:], package, level)
89+
if module:
90+
sys.audit(
91+
"import",
92+
name,
93+
# We could try to grab __file__ here but it breaks LazyLoader
94+
None,
95+
sys.path,
96+
sys.meta_path,
97+
sys.path_hooks
98+
)
99+
return module
89100

90101

91102
_RELOADING = {}

Lib/test/audit-tests.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -672,6 +672,22 @@ def hook(event, args):
672672
assertEqual(event_script_path, tmp_file.name)
673673
assertEqual(remote_event_script_path, tmp_file.name)
674674

675+
def test_import_module():
676+
import importlib
677+
678+
with TestHook() as hook:
679+
importlib.import_module("os") # random stdlib
680+
importlib.import_module("pythoninfo") # random module
681+
682+
actual = [a[0] for e, a in hook.seen if e == "import"]
683+
assertSequenceEqual(
684+
[
685+
"os",
686+
"pythoninfo",
687+
],
688+
actual,
689+
)
690+
675691
if __name__ == "__main__":
676692
from test.support import suppress_msvcrt_asserts
677693

Lib/test/test_audit.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -331,5 +331,8 @@ def test_sys_remote_exec(self):
331331
if returncode:
332332
self.fail(stderr)
333333

334+
def test_import_module(self):
335+
self.do_test("test_import_module")
336+
334337
if __name__ == "__main__":
335338
unittest.main()

0 commit comments

Comments
 (0)