Debian Codegraph @

tests/test_modutils.py

raw
1 # Licensed under the LGPL: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.en.html
2 # For details: https://github.com/pylint-dev/astroid/blob/main/LICENSE
3 # Copyright (c) https://github.com/pylint-dev/astroid/blob/main/CONTRIBUTORS.txt
4
5 """Unit tests for module modutils (module manipulation utilities)."""
6
7 import email
8 import logging
9 import os
10 import shutil
11 import sys
12 import tempfile
13 import unittest
14 import xml
15 from pathlib import Path
16 from xml.etree import ElementTree
17
18 import pytest
19 from pytest import CaptureFixture, LogCaptureFixture
20
21 import astroid
22 from astroid import modutils
23 from astroid.interpreter._import import spec
24
25 from . import resources
26
27 try:
28 import urllib3 # type: ignore[import]
29
30 HAS_URLLIB3_V1 = urllib3.__version__.startswith("1")
31 except ImportError:
32 HAS_URLLIB3_V1 = False
33
34
35 def _get_file_from_object(obj) -> str:
36 return modutils._path_from_filename(obj.__file__)
37
38
39 class ModuleFileTest(unittest.TestCase):
40 package = "mypypa"
41
42 def tearDown(self) -> None:
43 astroid.MANAGER.clear_cache()
44 for k in list(sys.path_importer_cache):
45 if "MyPyPa" in k:
46 del sys.path_importer_cache[k]
47
48 def test_find_zipped_module(self) -> None:
49 found_spec = spec.find_spec(
50 [self.package], [resources.find("data/MyPyPa-0.1.0-py2.5.zip")]
51 )
52 self.assertEqual(found_spec.type, spec.ModuleType.PY_ZIPMODULE)
53 self.assertEqual(
54 found_spec.location.split(os.sep)[-3:],
55 ["data", "MyPyPa-0.1.0-py2.5.zip", self.package],
56 )
57
58 def test_find_egg_module(self) -> None:
59 found_spec = spec.find_spec(
60 [self.package], [resources.find("data/MyPyPa-0.1.0-py2.5.egg")]
61 )
62 self.assertEqual(found_spec.type, spec.ModuleType.PY_ZIPMODULE)
63 self.assertEqual(
64 found_spec.location.split(os.sep)[-3:],
65 ["data", "MyPyPa-0.1.0-py2.5.egg", self.package],
66 )
67
68
69 class LoadModuleFromNameTest(unittest.TestCase):
70 """Load a python module from its name."""
71
72 def test_known_values_load_module_from_name_1(self) -> None:
73 self.assertEqual(modutils.load_module_from_name("sys"), sys)
74
75 def test_known_values_load_module_from_name_2(self) -> None:
76 self.assertEqual(modutils.load_module_from_name("os.path"), os.path)
77
78 def test_raise_load_module_from_name_1(self) -> None:
79 self.assertRaises(
80 ImportError, modutils.load_module_from_name, "_this_module_does_not_exist_"
81 )
82
83
84 def test_import_dotted_library(
85 capsys: CaptureFixture,
86 caplog: LogCaptureFixture,
87 ) -> None:
88 caplog.set_level(logging.INFO)
89 original_module = sys.modules.pop("xml.etree.ElementTree")
90 expected_out = "INFO (TEST): Welcome to cElementTree!"
91 expected_err = "WARNING (TEST): Monkey-patched version of cElementTree"
92
93 def function_with_stdout_and_stderr(expected_out, expected_err):
94 def mocked_function(*args, **kwargs):
95 print(f"{expected_out} args={args} kwargs={kwargs}")
96 print(expected_err, file=sys.stderr)
97
98 return mocked_function
99
100 try:
101 with unittest.mock.patch(
102 "importlib.import_module",
103 side_effect=function_with_stdout_and_stderr(expected_out, expected_err),
104 ):
105 modutils.load_module_from_name("xml.etree.ElementTree")
106
107 out, err = capsys.readouterr()
108 assert expected_out in caplog.text
109 assert expected_err in caplog.text
110 assert not out
111 assert not err
112 finally:
113 sys.modules["xml.etree.ElementTree"] = original_module
114
115
116 class GetModulePartTest(unittest.TestCase):
117 """Given a dotted name return the module part of the name."""
118
119 def test_known_values_get_module_part_1(self) -> None:
120 self.assertEqual(
121 modutils.get_module_part("astroid.modutils"), "astroid.modutils"
122 )
123
124 def test_known_values_get_module_part_2(self) -> None:
125 self.assertEqual(
126 modutils.get_module_part("astroid.modutils.get_module_part"),
127 "astroid.modutils",
128 )
129
130 def test_known_values_get_module_part_3(self) -> None:
131 """Relative import from given file."""
132 self.assertEqual(
133 modutils.get_module_part("nodes.node_classes.AssName", modutils.__file__),
134 "nodes.node_classes",
135 )
136
137 def test_known_values_get_compiled_module_part(self) -> None:
138 self.assertEqual(modutils.get_module_part("math.log10"), "math")
139 self.assertEqual(modutils.get_module_part("math.log10", __file__), "math")
140
141 def test_known_values_get_builtin_module_part(self) -> None:
142 self.assertEqual(modutils.get_module_part("sys.path"), "sys")
143 self.assertEqual(modutils.get_module_part("sys.path", "__file__"), "sys")
144
145 def test_get_module_part_exception(self) -> None:
146 self.assertRaises(
147 ImportError, modutils.get_module_part, "unknown.module", modutils.__file__
148 )
149
150 def test_get_module_part_only_dot(self) -> None:
151 self.assertEqual(modutils.get_module_part(".", modutils.__file__), ".")
152
153
154 class IsSubpathTest(unittest.TestCase):
155 """Tests for modutils._is_subpath,
156 which is used internally by modutils.modpath_from_file."""
157
158 @unittest.skipUnless(sys.platform == "win32", "Windows-specific path test")
159 def test_is_subpath_with_trailing_separator_unc_path(self) -> None:
160 self.assertTrue(
161 modutils._is_subpath(
162 "\\\\Mac\\Code\\tests\\test_resources.py",
163 # UNC path with trailing separator
164 "\\\\mac\\code\\",
165 )
166 )
167
168 @unittest.skipUnless(sys.platform == "win32", "Windows-specific path test")
169 def test_is_subpath_without_trailing_separator_unc_path(self) -> None:
170 self.assertTrue(
171 modutils._is_subpath(
172 "\\\\Mac\\Code\\tests\\test_resources.py",
173 # UNC path without trailing separator
174 "\\\\mac\\code",
175 )
176 )
177
178
179 class ModPathFromFileTest(unittest.TestCase):
180 """Given an absolute file path return the python module's path as a list."""
181
182 def test_known_values_modpath_from_file_1(self) -> None:
183 self.assertEqual(
184 modutils.modpath_from_file(ElementTree.__file__),
185 ["xml", "etree", "ElementTree"],
186 )
187
188 def test_raise_modpath_from_file_exception(self) -> None:
189 self.assertRaises(ImportError, modutils.modpath_from_file, "/turlututu")
190
191 def test_import_symlink_with_source_outside_of_path(self) -> None:
192 with tempfile.NamedTemporaryFile() as tmpfile:
193 linked_file_name = "symlinked_file.py"
194 try:
195 os.symlink(tmpfile.name, linked_file_name)
196 self.assertEqual(
197 modutils.modpath_from_file(linked_file_name), ["symlinked_file"]
198 )
199 finally:
200 os.remove(linked_file_name)
201
202 def test_modpath_from_file_path_order(self) -> None:
203 """Test for ordering of paths.
204 The test does the following:
205 1. Add a tmp directory to beginning of sys.path via augmented_sys_path
206 2. Create a module file in sub directory of tmp directory
207 3. If the sub directory is passed as additional directory, module name
208 should be relative to the subdirectory since additional directory has
209 higher precedence."""
210 with tempfile.TemporaryDirectory() as tmp_dir:
211 with resources.augmented_sys_path([tmp_dir]):
212 mod_name = "module"
213 sub_dirname = "subdir"
214 sub_dir = tmp_dir + "/" + sub_dirname
215 os.mkdir(sub_dir)
216 module_file = f"{sub_dir}/{mod_name}.py"
217
218 with open(module_file, "w+", encoding="utf-8"):
219 pass
220
221 # Without additional directory, return relative to tmp_dir
222 self.assertEqual(
223 modutils.modpath_from_file(module_file), [sub_dirname, mod_name]
224 )
225
226 # With sub directory as additional directory, return relative to
227 # sub directory
228 self.assertEqual(
229 modutils.modpath_from_file(f"{sub_dir}/{mod_name}.py", [sub_dir]),
230 [mod_name],
231 )
232
233 def test_import_symlink_both_outside_of_path(self) -> None:
234 with tempfile.NamedTemporaryFile() as tmpfile:
235 linked_file_name = os.path.join(tempfile.gettempdir(), "symlinked_file.py")
236 try:
237 os.symlink(tmpfile.name, linked_file_name)
238 self.assertRaises(
239 ImportError, modutils.modpath_from_file, linked_file_name
240 )
241 finally:
242 os.remove(linked_file_name)
243
244 def test_load_from_module_symlink_on_symlinked_paths_in_syspath(self) -> None:
245 # constants
246 tmp = tempfile.gettempdir()
247 deployment_path = os.path.join(tmp, "deployment")
248 path_to_include = os.path.join(tmp, "path_to_include")
249 real_secret_path = os.path.join(tmp, "secret.py")
250 symlink_secret_path = os.path.join(path_to_include, "secret.py")
251
252 # setup double symlink
253 # /tmp/deployment
254 # /tmp/path_to_include (symlink to /tmp/deployment)
255 # /tmp/secret.py
256 # /tmp/deployment/secret.py (points to /tmp/secret.py)
257 try:
258 os.mkdir(deployment_path)
259 self.addCleanup(shutil.rmtree, deployment_path)
260 os.symlink(deployment_path, path_to_include)
261 self.addCleanup(os.remove, path_to_include)
262 except OSError:
263 pass
264 with open(real_secret_path, "w", encoding="utf-8"):
265 pass
266 os.symlink(real_secret_path, symlink_secret_path)
267 self.addCleanup(os.remove, real_secret_path)
268
269 # add the symlinked path to sys.path
270 sys.path.append(path_to_include)
271 self.addCleanup(sys.path.pop)
272
273 # this should be equivalent to: import secret
274 self.assertEqual(modutils.modpath_from_file(symlink_secret_path), ["secret"])
275
276 def test_load_packages_without_init(self) -> None:
277 """Test that we correctly find packages with an __init__.py file.
278
279 Regression test for issue reported in:
280 https://github.com/pylint-dev/astroid/issues/1327
281 """
282 tmp_dir = Path(tempfile.gettempdir())
283 self.addCleanup(os.chdir, os.getcwd())
284 os.chdir(tmp_dir)
285
286 self.addCleanup(shutil.rmtree, tmp_dir / "src")
287 os.mkdir(tmp_dir / "src")
288 os.mkdir(tmp_dir / "src" / "package")
289 with open(tmp_dir / "src" / "__init__.py", "w", encoding="utf-8"):
290 pass
291 with open(tmp_dir / "src" / "package" / "file.py", "w", encoding="utf-8"):
292 pass
293
294 # this should be equivalent to: import secret
295 self.assertEqual(
296 modutils.modpath_from_file(str(Path("src") / "package"), ["."]),
297 ["src", "package"],
298 )
299
300
301 class LoadModuleFromPathTest(resources.SysPathSetup, unittest.TestCase):
302 def test_do_not_load_twice(self) -> None:
303 modutils.load_module_from_modpath(["data", "lmfp", "foo"])
304 modutils.load_module_from_modpath(["data", "lmfp"])
305 # pylint: disable=no-member; just-once is added by a test file dynamically.
306 self.assertEqual(len(sys.just_once), 1)
307 del sys.just_once
308
309
310 class FileFromModPathTest(resources.SysPathSetup, unittest.TestCase):
311 """given a mod path (i.e. splited module / package name), return the
312 corresponding file, giving priority to source file over precompiled file
313 if it exists"""
314
315 def test_site_packages(self) -> None:
316 filename = _get_file_from_object(modutils)
317 result = modutils.file_from_modpath(["astroid", "modutils"])
318 self.assertEqual(os.path.realpath(result), os.path.realpath(filename))
319
320 def test_std_lib(self) -> None:
321 path = modutils.file_from_modpath(["os", "path"]).replace(".pyc", ".py")
322 self.assertEqual(
323 os.path.realpath(path),
324 os.path.realpath(os.path.__file__.replace(".pyc", ".py")),
325 )
326
327 def test_builtin(self) -> None:
328 self.assertIsNone(modutils.file_from_modpath(["sys"]))
329
330 def test_unexisting(self) -> None:
331 self.assertRaises(ImportError, modutils.file_from_modpath, ["turlututu"])
332
333 def test_unicode_in_package_init(self) -> None:
334 # file_from_modpath should not crash when reading an __init__
335 # file with unicode characters.
336 modutils.file_from_modpath(["data", "unicode_package", "core"])
337
338
339 class GetSourceFileTest(unittest.TestCase):
340 def test(self) -> None:
341 filename = _get_file_from_object(os.path)
342 self.assertEqual(
343 modutils.get_source_file(os.path.__file__), os.path.normpath(filename)
344 )
345
346 def test_raise(self) -> None:
347 self.assertRaises(modutils.NoSourceFile, modutils.get_source_file, "whatever")
348
349 def test_pyi(self) -> None:
350 package = resources.find("pyi_data")
351 module = os.path.join(package, "__init__.pyi")
352 self.assertEqual(modutils.get_source_file(module), os.path.normpath(module))
353
354 def test_pyi_preferred(self) -> None:
355 package = resources.find("pyi_data/find_test")
356 module = os.path.join(package, "__init__.py")
357 self.assertEqual(
358 modutils.get_source_file(module, prefer_stubs=True),
359 os.path.normpath(module) + "i",
360 )
361
362 def test_nonstandard_extension(self) -> None:
363 package = resources.find("pyi_data/find_test")
364 modules = [
365 os.path.join(package, "__init__.weird_ext"),
366 os.path.join(package, "standalone_file.weird_ext"),
367 ]
368 for module in modules:
369 self.assertEqual(
370 modutils.get_source_file(module, prefer_stubs=True),
371 module,
372 )
373 self.assertEqual(
374 modutils.get_source_file(module),
375 module,
376 )
377
378
379 class IsStdLibModuleTest(resources.SysPathSetup, unittest.TestCase):
380 """
381 Return true if the module is path of the standard library
382 """
383
384 def test_datetime(self) -> None:
385 # This is an interesting example, since datetime, on pypy,
386 # is under lib_pypy, rather than the usual Lib directory.
387 assert modutils.is_stdlib_module("datetime")
388
389 def test_builtins(self) -> None:
390 assert not modutils.is_stdlib_module("__builtin__")
391 assert modutils.is_stdlib_module("builtins")
392
393 def test_builtin(self) -> None:
394 assert modutils.is_stdlib_module("sys")
395 assert modutils.is_stdlib_module("marshal")
396
397 def test_nonstandard(self) -> None:
398 assert not modutils.is_stdlib_module("astroid")
399
400 def test_unknown(self) -> None:
401 assert not modutils.is_stdlib_module("unknown")
402
403 def test_4(self) -> None:
404 assert modutils.is_stdlib_module("hashlib")
405 assert modutils.is_stdlib_module("pickle")
406 assert modutils.is_stdlib_module("email")
407 assert modutils.is_stdlib_module("io")
408 assert not modutils.is_stdlib_module("StringIO")
409 assert modutils.is_stdlib_module("unicodedata")
410
411 def test_subpackages(self) -> None:
412 # using a module + object name as modname argument
413 assert modutils.is_stdlib_module("sys.path")
414 # this is because only the first package/module is considered
415 assert modutils.is_stdlib_module("sys.whatever")
416
417 def test_platform_specific(self) -> None:
418 assert modutils.is_stdlib_module("_curses")
419 assert modutils.is_stdlib_module("msvcrt")
420 assert modutils.is_stdlib_module("termios")
421
422
423 class ModuleInPathTest(resources.SysPathSetup, unittest.TestCase):
424 """
425 Return true if the module is imported from the specified path
426 """
427
428 def test_success(self) -> None:
429 datadir = resources.find("")
430 assert modutils.module_in_path("data.module", datadir)
431 assert modutils.module_in_path("data.module", (datadir,))
432 assert modutils.module_in_path("data.module", os.path.abspath(datadir))
433 assert modutils.module_in_path("pyi_data.module", datadir)
434 assert modutils.module_in_path("pyi_data.module", (datadir,))
435 assert modutils.module_in_path("pyi_data.module", os.path.abspath(datadir))
436 # "" will evaluate to cwd
437 assert modutils.module_in_path("data.module", "")
438 assert modutils.module_in_path("pyi_data.module", "")
439
440 def test_bad_import(self) -> None:
441 datadir = resources.find("")
442 assert not modutils.module_in_path("this_module_is_no_more", datadir)
443
444 def test_no_filename(self) -> None:
445 datadir = resources.find("")
446 assert not modutils.module_in_path("sys", datadir)
447
448 def test_failure(self) -> None:
449 datadir = resources.find("")
450 assert not modutils.module_in_path("etree", datadir)
451 assert not modutils.module_in_path("astroid", datadir)
452
453
454 class IsRelativeTest(unittest.TestCase):
455 def test_known_values_is_relative_1(self) -> None:
456 self.assertTrue(modutils.is_relative("utils", email.__path__[0]))
457
458 def test_known_values_is_relative_3(self) -> None:
459 self.assertFalse(modutils.is_relative("astroid", astroid.__path__[0]))
460
461 def test_known_values_is_relative_4(self) -> None:
462 self.assertTrue(
463 modutils.is_relative("util", astroid.interpreter._import.spec.__file__)
464 )
465
466 def test_known_values_is_relative_5(self) -> None:
467 self.assertFalse(
468 modutils.is_relative(
469 "objectmodel", astroid.interpreter._import.spec.__file__
470 )
471 )
472
473 def test_deep_relative(self) -> None:
474 self.assertTrue(modutils.is_relative("ElementTree", xml.etree.__path__[0]))
475
476 def test_deep_relative2(self) -> None:
477 self.assertFalse(modutils.is_relative("ElementTree", xml.__path__[0]))
478
479 def test_deep_relative3(self) -> None:
480 self.assertTrue(modutils.is_relative("etree.ElementTree", xml.__path__[0]))
481
482 def test_deep_relative4(self) -> None:
483 self.assertTrue(modutils.is_relative("etree.gibberish", xml.__path__[0]))
484
485 def test_is_relative_bad_path(self) -> None:
486 self.assertFalse(
487 modutils.is_relative("ElementTree", os.path.join(xml.__path__[0], "ftree"))
488 )
489
490
491 class GetModuleFilesTest(unittest.TestCase):
492 def test_get_module_files_1(self) -> None:
493 package = resources.find("data/find_test")
494 modules = set(modutils.get_module_files(package, []))
495 expected = [
496 "__init__.py",
497 "module.py",
498 "module2.py",
499 "noendingnewline.py",
500 "nonregr.py",
501 ]
502 self.assertEqual(modules, {os.path.join(package, x) for x in expected})
503
504 def test_get_module_files_2(self) -> None:
505 package = resources.find("pyi_data/find_test")
506 modules = set(modutils.get_module_files(package, []))
507 expected = [
508 "__init__.py",
509 "__init__.pyi",
510 "module.py",
511 "module2.py",
512 "noendingnewline.py",
513 "nonregr.py",
514 ]
515 self.assertEqual(modules, {os.path.join(package, x) for x in expected})
516
517 def test_get_all_files(self) -> None:
518 """Test that list_all returns all Python files from given location."""
519 non_package = resources.find("data/notamodule")
520 modules = modutils.get_module_files(non_package, [], list_all=True)
521 self.assertEqual(modules, [os.path.join(non_package, "file.py")])
522
523 def test_load_module_set_attribute(self) -> None:
524 del xml.etree.ElementTree
525 del sys.modules["xml.etree.ElementTree"]
526 m = modutils.load_module_from_modpath(["xml", "etree", "ElementTree"])
527 self.assertTrue(hasattr(xml, "etree"))
528 self.assertTrue(hasattr(xml.etree, "ElementTree"))
529 self.assertTrue(m is xml.etree.ElementTree)
530
531
532 class ExtensionPackageWhitelistTest(unittest.TestCase):
533 def test_is_module_name_part_of_extension_package_whitelist_true(self) -> None:
534 self.assertTrue(
535 modutils.is_module_name_part_of_extension_package_whitelist(
536 "numpy", {"numpy"}
537 )
538 )
539 self.assertTrue(
540 modutils.is_module_name_part_of_extension_package_whitelist(
541 "numpy.core", {"numpy"}
542 )
543 )
544 self.assertTrue(
545 modutils.is_module_name_part_of_extension_package_whitelist(
546 "numpy.core.umath", {"numpy"}
547 )
548 )
549
550 def test_is_module_name_part_of_extension_package_whitelist_success(self) -> None:
551 self.assertFalse(
552 modutils.is_module_name_part_of_extension_package_whitelist(
553 "numpy", {"numpy.core"}
554 )
555 )
556 self.assertFalse(
557 modutils.is_module_name_part_of_extension_package_whitelist(
558 "numpy.core", {"numpy.core.umath"}
559 )
560 )
561 self.assertFalse(
562 modutils.is_module_name_part_of_extension_package_whitelist(
563 "core.umath", {"numpy"}
564 )
565 )
566
567
568 @pytest.mark.skipif(not HAS_URLLIB3_V1, reason="This test requires urllib3 < 2.")
569 def test_file_info_from_modpath__SixMetaPathImporter() -> None:
570 """Six is not backported anymore in urllib3 v2.0.0+"""
571 assert modutils.file_info_from_modpath(["urllib3.packages.six.moves.http_client"])
572
573
574 def test_find_setuptools_pep660_editable_install():
575 """Find the spec for a package installed via setuptools PEP 660 import hooks."""
576 # pylint: disable-next=import-outside-toplevel
577 from tests.testdata.python3.data.import_setuptools_pep660.__editable___example_0_1_0_finder import (
578 _EditableFinder,
579 )
580
581 with unittest.mock.patch.object(sys, "meta_path", new=[_EditableFinder]):
582 assert spec.find_spec(["example"])
583 assert spec.find_spec(["example", "subpackage"])
584
585
586 def test_no_import_done_for_submodule_sharing_std_lib_name() -> None:
587 sys.path.insert(0, resources.find("data"))
588 try:
589 with pytest.raises(ImportError):
590 spec._find_spec_with_path(
591 [resources.find("data")],
592 "trace",
593 ("divide_by_zero", "trace"),
594 ("divide_by_zero",),
595 resources.find("data/divide_by_zero"),
596 )
597 finally:
598 sys.path.pop(0)