Debian Codegraph @

tests/test_path.py

raw
1 # encoding: utf-8
2 """Tests for IPython.utils.path.py"""
3
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
6
7 import os
8 import shutil
9 import sys
10 import tempfile
11 import unittest
12 from contextlib import contextmanager
13 from importlib import reload
14 from os.path import abspath, join
15 from unittest.mock import patch
16
17 import pytest
18 from tempfile import TemporaryDirectory
19
20 import IPython
21 from IPython import paths
22 from IPython.testing import decorators as dec
23 from IPython.testing.decorators import (
24 onlyif_unicode_paths,
25 skip_if_not_win32,
26 skip_win32,
27 )
28 from IPython.testing.tools import make_tempfile
29 from IPython.utils import path
30
31 # Platform-dependent imports
32 try:
33 import winreg as wreg
34 except ImportError:
35 # Fake _winreg module on non-windows platforms
36 import types
37
38 wr_name = "winreg"
39 sys.modules[wr_name] = types.ModuleType(wr_name)
40 try:
41 import winreg as wreg
42 except ImportError:
43 import _winreg as wreg
44
45 # Add entries that needs to be stubbed by the testing code
46 (
47 wreg.OpenKey,
48 wreg.QueryValueEx,
49 ) = (None, None)
50
51 # -----------------------------------------------------------------------------
52 # Globals
53 # -----------------------------------------------------------------------------
54 env = os.environ
55 TMP_TEST_DIR = tempfile.mkdtemp()
56 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
57 #
58 # Setup/teardown functions/decorators
59 #
60
61
62 def setup_module():
63 """Setup testenvironment for the module:
64
65 - Adds dummy home dir tree
66 """
67 # Do not mask exceptions here. In particular, catching WindowsError is a
68 # problem because that exception is only defined on Windows...
69 os.makedirs(os.path.join(HOME_TEST_DIR, "ipython"))
70
71
72 def teardown_module():
73 """Teardown testenvironment for the module:
74
75 - Remove dummy home dir tree
76 """
77 # Note: we remove the parent test dir, which is the root of all test
78 # subdirs we may have created. Use shutil instead of os.removedirs, so
79 # that non-empty directories are all recursively removed.
80 shutil.rmtree(TMP_TEST_DIR)
81
82
83 # Build decorator that uses the setup_environment/setup_environment
84 @pytest.fixture
85 def environment():
86 global oldstuff, platformstuff
87 oldstuff = (
88 env.copy(),
89 os.name,
90 sys.platform,
91 path.get_home_dir,
92 IPython.__file__,
93 os.getcwd(),
94 )
95
96 yield
97
98 (
99 oldenv,
100 os.name,
101 sys.platform,
102 path.get_home_dir,
103 IPython.__file__,
104 old_wd,
105 ) = oldstuff
106 os.chdir(old_wd)
107 reload(path)
108
109 for key in list(env):
110 if key not in oldenv:
111 del env[key]
112 env.update(oldenv)
113 assert not hasattr(sys, "frozen")
114
115
116 with_environment = pytest.mark.usefixtures("environment")
117
118
119 @skip_if_not_win32
120 @with_environment
121 def test_get_home_dir_1(monkeypatch):
122 """Testcase for py2exe logic, un-compressed lib"""
123 unfrozen = path.get_home_dir()
124 monkeypatch.setattr(sys, "frozen", True, raising=False)
125
126 # fake filename for IPython.__init__
127 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
128
129 home_dir = path.get_home_dir()
130 assert home_dir == unfrozen
131
132
133 @skip_if_not_win32
134 @with_environment
135 def test_get_home_dir_2(monkeypatch):
136 """Testcase for py2exe logic, compressed lib"""
137 unfrozen = path.get_home_dir()
138 monkeypatch.setattr(sys, "frozen", True, raising=False)
139 # fake filename for IPython.__init__
140 IPython.__file__ = abspath(
141 join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")
142 ).lower()
143
144 home_dir = path.get_home_dir(True)
145 assert home_dir == unfrozen
146
147
148 @skip_win32
149 @with_environment
150 def test_get_home_dir_3():
151 """get_home_dir() uses $HOME if set"""
152 env["HOME"] = HOME_TEST_DIR
153 home_dir = path.get_home_dir(True)
154 # get_home_dir expands symlinks
155 assert home_dir == os.path.realpath(env["HOME"])
156
157
158 @with_environment
159 def test_get_home_dir_4():
160 """get_home_dir() still works if $HOME is not set"""
161
162 if "HOME" in env:
163 del env["HOME"]
164 # this should still succeed, but we don't care what the answer is
165 home = path.get_home_dir(False)
166
167
168 @skip_win32
169 @with_environment
170 def test_get_home_dir_5(monkeypatch):
171 """raise HomeDirError if $HOME is specified, but not a writable dir"""
172 env["HOME"] = abspath(HOME_TEST_DIR + "garbage")
173 # set os.name = posix, to prevent My Documents fallback on Windows
174 monkeypatch.setattr(os, "name", "posix")
175 pytest.raises(path.HomeDirError, path.get_home_dir, True)
176
177
178 # Should we stub wreg fully so we can run the test on all platforms?
179 @skip_if_not_win32
180 @with_environment
181 def test_get_home_dir_8(monkeypatch):
182 """Using registry hack for 'My Documents', os=='nt'
183
184 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
185 """
186 monkeypatch.setattr(os, "name", "nt")
187 # Remove from stub environment all keys that may be set
188 for key in ["HOME", "HOMESHARE", "HOMEDRIVE", "HOMEPATH", "USERPROFILE"]:
189 env.pop(key, None)
190
191 class key:
192 def __enter__(self):
193 pass
194
195 def Close(self):
196 pass
197
198 def __exit__(*args, **kwargs):
199 pass
200
201 with (
202 patch.object(wreg, "OpenKey", return_value=key()),
203 patch.object(wreg, "QueryValueEx", return_value=[abspath(HOME_TEST_DIR)]),
204 ):
205 home_dir = path.get_home_dir()
206 assert home_dir == abspath(HOME_TEST_DIR)
207
208
209 @with_environment
210 def test_get_xdg_dir_0(monkeypatch):
211 """test_get_xdg_dir_0, check xdg_dir"""
212 monkeypatch.setattr(path, "_writable_dir", lambda path: True)
213 monkeypatch.setattr(path, "get_home_dir", lambda: "somewhere")
214 monkeypatch.setattr(os, "name", "posix")
215 monkeypatch.setattr(sys, "platform", "linux2")
216 env.pop("IPYTHON_DIR", None)
217 env.pop("IPYTHONDIR", None)
218 env.pop("XDG_CONFIG_HOME", None)
219
220 assert path.get_xdg_dir() == os.path.join("somewhere", ".config")
221
222
223 @with_environment
224 def test_get_xdg_dir_1(monkeypatch):
225 """test_get_xdg_dir_1, check nonexistent xdg_dir"""
226 monkeypatch.setattr(path, "get_home_dir", lambda: HOME_TEST_DIR)
227 monkeypatch.setattr(os, "name", "posix")
228 monkeypatch.setattr(sys, "platform", "linux2")
229 env.pop("IPYTHON_DIR", None)
230 env.pop("IPYTHONDIR", None)
231 env.pop("XDG_CONFIG_HOME", None)
232 assert path.get_xdg_dir() is None
233
234
235 @with_environment
236 def test_get_xdg_dir_2(monkeypatch):
237 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
238 monkeypatch.setattr(path, "get_home_dir", lambda: HOME_TEST_DIR)
239 monkeypatch.setattr(os, "name", "posix")
240 monkeypatch.setattr(sys, "platform", "linux2")
241 env.pop("IPYTHON_DIR", None)
242 env.pop("IPYTHONDIR", None)
243 env.pop("XDG_CONFIG_HOME", None)
244 cfgdir = os.path.join(path.get_home_dir(), ".config")
245 if not os.path.exists(cfgdir):
246 os.makedirs(cfgdir)
247
248 assert path.get_xdg_dir() == cfgdir
249
250
251 @with_environment
252 def test_get_xdg_dir_3(monkeypatch):
253 """test_get_xdg_dir_3, check xdg_dir not used on non-posix systems"""
254 monkeypatch.setattr(path, "get_home_dir", lambda: HOME_TEST_DIR)
255 monkeypatch.setattr(os, "name", "nt")
256 monkeypatch.setattr(sys, "platform", "win32")
257 env.pop("IPYTHON_DIR", None)
258 env.pop("IPYTHONDIR", None)
259 env.pop("XDG_CONFIG_HOME", None)
260 cfgdir = os.path.join(path.get_home_dir(), ".config")
261 os.makedirs(cfgdir, exist_ok=True)
262
263 assert path.get_xdg_dir() is None
264
265
266 def test_filefind():
267 """Various tests for filefind"""
268 f = tempfile.NamedTemporaryFile()
269 # print('fname:',f.name)
270 alt_dirs = paths.get_ipython_dir()
271 t = path.filefind(f.name, alt_dirs)
272 # print('found:',t)
273
274
275 @dec.skip_if_not_win32
276 def test_get_long_path_name_win32():
277 with TemporaryDirectory() as tmpdir:
278 # Make a long path. Expands the path of tmpdir prematurely as it may already have a long
279 # path component, so ensure we include the long form of it
280 long_path = os.path.join(
281 path.get_long_path_name(tmpdir), "this is my long path name"
282 )
283 os.makedirs(long_path)
284
285 # Test to see if the short path evaluates correctly.
286 short_path = os.path.join(tmpdir, "THISIS~1")
287 evaluated_path = path.get_long_path_name(short_path)
288 assert evaluated_path.lower() == long_path.lower()
289
290
291 @dec.skip_win32
292 def test_get_long_path_name():
293 p = path.get_long_path_name("/usr/local")
294 assert p == "/usr/local"
295
296
297 @dec.skip_win32 # can't create not-user-writable dir on win
298 @with_environment
299 def test_not_writable_ipdir():
300 tmpdir = tempfile.mkdtemp()
301 os.name = "posix"
302 env.pop("IPYTHON_DIR", None)
303 env.pop("IPYTHONDIR", None)
304 env.pop("XDG_CONFIG_HOME", None)
305 env["HOME"] = tmpdir
306 ipdir = os.path.join(tmpdir, ".ipython")
307 os.mkdir(ipdir, 0o555)
308 try:
309 open(os.path.join(ipdir, "_foo_"), "w", encoding="utf-8").close()
310 except IOError:
311 pass
312 else:
313 # I can still write to an unwritable dir,
314 # assume I'm root and skip the test
315 pytest.skip("I can't create directories that I can't write to")
316
317 with pytest.warns(UserWarning, match="is not a writable location"):
318 ipdir = paths.get_ipython_dir()
319 env.pop("IPYTHON_DIR", None)
320
321
322 @with_environment
323 def test_get_py_filename():
324 os.chdir(TMP_TEST_DIR)
325 with make_tempfile("foo.py"):
326 assert path.get_py_filename("foo.py") == "foo.py"
327 assert path.get_py_filename("foo") == "foo.py"
328 with make_tempfile("foo"):
329 assert path.get_py_filename("foo") == "foo"
330 pytest.raises(IOError, path.get_py_filename, "foo.py")
331 pytest.raises(IOError, path.get_py_filename, "foo")
332 pytest.raises(IOError, path.get_py_filename, "foo.py")
333 true_fn = "foo with spaces.py"
334 with make_tempfile(true_fn):
335 assert path.get_py_filename("foo with spaces") == true_fn
336 assert path.get_py_filename("foo with spaces.py") == true_fn
337 pytest.raises(IOError, path.get_py_filename, '"foo with spaces.py"')
338 pytest.raises(IOError, path.get_py_filename, "'foo with spaces.py'")
339
340
341 @onlyif_unicode_paths
342 def test_unicode_in_filename():
343 """When a file doesn't exist, the exception raised should be safe to call
344 str() on - i.e. in Python 2 it must only have ASCII characters.
345
346 https://github.com/ipython/ipython/issues/875
347 """
348 try:
349 # these calls should not throw unicode encode exceptions
350 path.get_py_filename("fooéè.py")
351 except IOError as ex:
352 str(ex)
353
354
355 class TestShellGlob(unittest.TestCase):
356 @classmethod
357 def setUpClass(cls):
358 cls.filenames_start_with_a = ["a0", "a1", "a2"]
359 cls.filenames_end_with_b = ["0b", "1b", "2b"]
360 cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b
361 cls.tempdir = TemporaryDirectory()
362 td = cls.tempdir.name
363
364 with cls.in_tempdir():
365 # Create empty files
366 for fname in cls.filenames:
367 open(os.path.join(td, fname), "w", encoding="utf-8").close()
368
369 @classmethod
370 def tearDownClass(cls):
371 cls.tempdir.cleanup()
372
373 @classmethod
374 @contextmanager
375 def in_tempdir(cls):
376 save = os.getcwd()
377 try:
378 os.chdir(cls.tempdir.name)
379 yield
380 finally:
381 os.chdir(save)
382
383 def check_match(self, patterns, matches):
384 with self.in_tempdir():
385 # glob returns unordered list. that's why sorted is required.
386 assert sorted(path.shellglob(patterns)) == sorted(matches)
387
388 def common_cases(self):
389 return [
390 (["*"], self.filenames),
391 (["a*"], self.filenames_start_with_a),
392 (["*c"], ["*c"]),
393 (
394 ["*", "a*", "*b", "*c"],
395 self.filenames
396 + self.filenames_start_with_a
397 + self.filenames_end_with_b
398 + ["*c"],
399 ),
400 (["a[012]"], self.filenames_start_with_a),
401 ]
402
403 @skip_win32
404 def test_match_posix(self):
405 for patterns, matches in self.common_cases() + [
406 ([r"\*"], ["*"]),
407 ([r"a\*", "a*"], ["a*"] + self.filenames_start_with_a),
408 ([r"a\[012]"], ["a[012]"]),
409 ]:
410 self.check_match(patterns, matches)
411
412 @skip_if_not_win32
413 def test_match_windows(self):
414 for patterns, matches in self.common_cases() + [
415 # In windows, backslash is interpreted as path
416 # separator. Therefore, you can't escape glob
417 # using it.
418 ([r"a\*", "a*"], [r"a\*"] + self.filenames_start_with_a),
419 ([r"a\[012]"], [r"a\[012]"]),
420 ]:
421 self.check_match(patterns, matches)
422
423
424 @pytest.mark.parametrize(
425 "globstr, unescaped_globstr",
426 [
427 (r"\*\[\!\]\?", "*[!]?"),
428 (r"\\*", r"\*"),
429 (r"\\\*", r"\*"),
430 (r"\\a", r"\a"),
431 (r"\a", r"\a"),
432 ],
433 )
434 def test_unescape_glob(globstr, unescaped_globstr):
435 assert path.unescape_glob(globstr) == unescaped_globstr
436
437
438 @onlyif_unicode_paths
439 def test_ensure_dir_exists():
440 with TemporaryDirectory() as td:
441 d = os.path.join(td, "∂ir")
442 path.ensure_dir_exists(d) # create it
443 assert os.path.isdir(d)
444 path.ensure_dir_exists(d) # no-op
445 f = os.path.join(td, "ƒile")
446 open(f, "w", encoding="utf-8").close() # touch
447 with pytest.raises(IOError):
448 path.ensure_dir_exists(f)
449
450
451 class TestLinkOrCopy(unittest.TestCase):
452 def setUp(self):
453 self.tempdir = TemporaryDirectory()
454 self.src = self.dst("src")
455 with open(self.src, "w", encoding="utf-8") as f:
456 f.write("Hello, world!")
457
458 def tearDown(self):
459 self.tempdir.cleanup()
460
461 def dst(self, *args):
462 return os.path.join(self.tempdir.name, *args)
463
464 def assert_inode_not_equal(self, a, b):
465 assert (
466 os.stat(a).st_ino != os.stat(b).st_ino
467 ), "%r and %r do reference the same indoes" % (a, b)
468
469 def assert_inode_equal(self, a, b):
470 assert (
471 os.stat(a).st_ino == os.stat(b).st_ino
472 ), "%r and %r do not reference the same indoes" % (a, b)
473
474 def assert_content_equal(self, a, b):
475 with open(a, "rb") as a_f:
476 with open(b, "rb") as b_f:
477 assert a_f.read() == b_f.read()
478
479 @skip_win32
480 def test_link_successful(self):
481 dst = self.dst("target")
482 path.link_or_copy(self.src, dst)
483 self.assert_inode_equal(self.src, dst)
484
485 @skip_win32
486 def test_link_into_dir(self):
487 dst = self.dst("some_dir")
488 os.mkdir(dst)
489 path.link_or_copy(self.src, dst)
490 expected_dst = self.dst("some_dir", os.path.basename(self.src))
491 self.assert_inode_equal(self.src, expected_dst)
492
493 @skip_win32
494 def test_target_exists(self):
495 dst = self.dst("target")
496 open(dst, "w", encoding="utf-8").close()
497 path.link_or_copy(self.src, dst)
498 self.assert_inode_equal(self.src, dst)
499
500 @skip_win32
501 def test_no_link(self):
502 real_link = os.link
503 try:
504 del os.link
505 dst = self.dst("target")
506 path.link_or_copy(self.src, dst)
507 self.assert_content_equal(self.src, dst)
508 self.assert_inode_not_equal(self.src, dst)
509 finally:
510 os.link = real_link
511
512 @skip_if_not_win32
513 def test_windows(self):
514 dst = self.dst("target")
515 path.link_or_copy(self.src, dst)
516 self.assert_content_equal(self.src, dst)
517
518 def test_link_twice(self):
519 # Linking the same file twice shouldn't leave duplicates around.
520 # See https://github.com/ipython/ipython/issues/6450
521 dst = self.dst("target")
522 path.link_or_copy(self.src, dst)
523 path.link_or_copy(self.src, dst)
524 self.assert_inode_equal(self.src, dst)
525 assert sorted(os.listdir(self.tempdir.name)) == ["src", "target"]