66unit tests for module modutils (module manipulation utilities)
77"""
88import email
9+ import logging
910import os
1011import shutil
1112import sys
1617from xml import etree
1718from xml .etree import ElementTree
1819
20+ from pytest import CaptureFixture , LogCaptureFixture
21+
1922import astroid
2023from astroid import modutils
2124from astroid .interpreter ._import import spec
@@ -57,7 +60,7 @@ def test_find_egg_module(self) -> None:
5760
5861
5962class LoadModuleFromNameTest (unittest .TestCase ):
60- """load a python module from it's name"""
63+ """load a python module from its name"""
6164
6265 def test_known_values_load_module_from_name_1 (self ) -> None :
6366 self .assertEqual (modutils .load_module_from_name ("sys" ), sys )
@@ -71,6 +74,38 @@ def test_raise_load_module_from_name_1(self) -> None:
7174 )
7275
7376
77+ def test_import_dotted_library (
78+ capsys : CaptureFixture ,
79+ caplog : LogCaptureFixture ,
80+ ) -> None :
81+ caplog .set_level (logging .INFO )
82+ original_module = sys .modules .pop ("xml.etree.ElementTree" )
83+ expected_out = "INFO (TEST): Welcome to cElementTree!"
84+ expected_err = "WARNING (TEST): Monkey-patched version of cElementTree"
85+
86+ def function_with_stdout_and_stderr (expected_out , expected_err ):
87+ def mocked_function (* args , ** kwargs ):
88+ print (f"{ expected_out } args={ args } kwargs={ kwargs } " )
89+ print (expected_err , file = sys .stderr )
90+
91+ return mocked_function
92+
93+ try :
94+ with unittest .mock .patch (
95+ "importlib.import_module" ,
96+ side_effect = function_with_stdout_and_stderr (expected_out , expected_err ),
97+ ):
98+ modutils .load_module_from_name ("xml.etree.ElementTree" )
99+
100+ out , err = capsys .readouterr ()
101+ assert expected_out in caplog .text
102+ assert expected_err in caplog .text
103+ assert not out
104+ assert not err
105+ finally :
106+ sys .modules ["xml.etree.ElementTree" ] = original_module
107+
108+
74109class GetModulePartTest (unittest .TestCase ):
75110 """given a dotted name return the module part of the name"""
76111
0 commit comments