Skip to content

Commit 26f81b8

Browse files
Add a wrapping function to the function mocking an output
1 parent f7f6bd5 commit 26f81b8

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

tests/unittest_modutils.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
unit tests for module modutils (module manipulation utilities)
77
"""
88
import email
9+
import logging
910
import os
1011
import shutil
1112
import sys
@@ -16,6 +17,8 @@
1617
from xml import etree
1718
from xml.etree import ElementTree
1819

20+
from pytest import CaptureFixture, LogCaptureFixture
21+
1922
import astroid
2023
from astroid import modutils
2124
from astroid.interpreter._import import spec
@@ -71,6 +74,35 @@ 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+
del sys.modules["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+
with unittest.mock.patch(
94+
"importlib.import_module",
95+
side_effect=function_with_stdout_and_stderr(expected_out, expected_err),
96+
):
97+
modutils.load_module_from_name("xml.etree.ElementTree")
98+
99+
out, err = capsys.readouterr()
100+
assert expected_out in caplog.text
101+
assert expected_err in caplog.text
102+
assert not out
103+
assert not err
104+
105+
74106
class GetModulePartTest(unittest.TestCase):
75107
"""given a dotted name return the module part of the name"""
76108

0 commit comments

Comments
 (0)