diff options
author | Ben Elliston <bje@air.net.au> | 2023-01-30 19:46:59 +1100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-01-30 09:46:59 +0100 |
commit | 054519205e3052d91c1a4a6b695fd245c09ddfc4 (patch) | |
tree | 9e10ddb925d2e0ecc9df1034a7d8f20d330aa668 /tests | |
parent | e31c9c48c63943cec9be87a70fe0ef30b38c0ab0 (diff) | |
download | astroid-git-054519205e3052d91c1a4a6b695fd245c09ddfc4.tar.gz |
Capture unwanted output signaled in #1904. (#1978)
Co-authored-by: Pierre Sassoulas <pierre.sassoulas@gmail.com>
Co-authored-by: Marc Mueller <30130371+cdce8p@users.noreply.github.com>
Diffstat (limited to 'tests')
-rw-r--r-- | tests/unittest_raw_building.py | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/tests/unittest_raw_building.py b/tests/unittest_raw_building.py index 64c22727..ad0f0af7 100644 --- a/tests/unittest_raw_building.py +++ b/tests/unittest_raw_building.py @@ -8,8 +8,15 @@ to simulate issues in unittest below # For details: https://github.com/PyCQA/astroid/blob/main/LICENSE # Copyright (c) https://github.com/PyCQA/astroid/blob/main/CONTRIBUTORS.txt +from __future__ import annotations + +import logging +import os +import sys import types import unittest +from typing import Any +from unittest import mock import _io import pytest @@ -117,5 +124,45 @@ class RawBuildingTC(unittest.TestCase): AstroidBuilder().inspect_build(fm_getattr, "test") +@pytest.mark.skipif( + "posix" not in sys.builtin_module_names, reason="Platform doesn't support posix" +) +def test_build_module_getattr_catch_output( + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, +) -> None: + """Catch stdout and stderr in module __getattr__ calls when building a module. + + Usually raised by DeprecationWarning or FutureWarning. + """ + caplog.set_level(logging.INFO) + original_sys = sys.modules + original_module = sys.modules["posix"] + expected_out = "INFO (TEST): Welcome to posix!" + expected_err = "WARNING (TEST): Monkey-patched version of posix - module getattr" + + class CustomGetattr: + def __getattr__(self, name: str) -> Any: + print(f"{expected_out}") + print(expected_err, file=sys.stderr) + return getattr(original_module, name) + + def mocked_sys_modules_getitem(name: str) -> types.ModuleType | CustomGetattr: + if name != "posix": + return original_sys[name] + return CustomGetattr() + + with mock.patch("astroid.raw_building.sys.modules") as sys_mock: + sys_mock.__getitem__.side_effect = mocked_sys_modules_getitem + builder = AstroidBuilder() + builder.inspect_build(os) + + out, err = capsys.readouterr() + assert expected_out in caplog.text + assert expected_err in caplog.text + assert not out + assert not err + + if __name__ == "__main__": unittest.main() |