##// END OF EJS Templates
Backport PR #6581: Properly mock winreg functions for test...
MinRK -
Show More
@@ -1,677 +1,669 b''
1 1 # encoding: utf-8
2 2 """Tests for IPython.utils.path.py"""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2008-2011 The IPython Development Team
6 6 #
7 7 # Distributed under the terms of the BSD License. The full license is in
8 8 # the file COPYING, distributed as part of this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 from __future__ import with_statement
16 16
17 17 import errno
18 18 import os
19 19 import shutil
20 20 import sys
21 21 import tempfile
22 22 import warnings
23 23 from contextlib import contextmanager
24 24
25 try: # Python 3.3+
26 from unittest.mock import patch
27 except ImportError:
28 from mock import patch
29
25 30 from os.path import join, abspath, split
26 31
27 32 import nose.tools as nt
28 33
29 34 from nose import with_setup
30 35
31 36 import IPython
32 37 from IPython.testing import decorators as dec
33 38 from IPython.testing.decorators import (skip_if_not_win32, skip_win32,
34 39 onlyif_unicode_paths,)
35 40 from IPython.testing.tools import make_tempfile, AssertPrints
36 41 from IPython.utils import path
37 42 from IPython.utils import py3compat
38 43 from IPython.utils.tempdir import TemporaryDirectory
39 44
40 45 # Platform-dependent imports
41 46 try:
42 47 import winreg as wreg # Py 3
43 48 except ImportError:
44 49 try:
45 50 import _winreg as wreg # Py 2
46 51 except ImportError:
47 52 #Fake _winreg module on none windows platforms
48 53 import types
49 54 wr_name = "winreg" if py3compat.PY3 else "_winreg"
50 55 sys.modules[wr_name] = types.ModuleType(wr_name)
51 56 try:
52 57 import winreg as wreg
53 58 except ImportError:
54 59 import _winreg as wreg
55 60 #Add entries that needs to be stubbed by the testing code
56 61 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
57 62
58 63 try:
59 64 reload
60 65 except NameError: # Python 3
61 66 from imp import reload
62 67
63 68 #-----------------------------------------------------------------------------
64 69 # Globals
65 70 #-----------------------------------------------------------------------------
66 71 env = os.environ
67 72 TEST_FILE_PATH = split(abspath(__file__))[0]
68 73 TMP_TEST_DIR = tempfile.mkdtemp()
69 74 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
70 75 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
71 76 XDG_CACHE_DIR = join(HOME_TEST_DIR, "xdg_cache_dir")
72 77 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
73 78 #
74 79 # Setup/teardown functions/decorators
75 80 #
76 81
77 82 def setup():
78 83 """Setup testenvironment for the module:
79 84
80 85 - Adds dummy home dir tree
81 86 """
82 87 # Do not mask exceptions here. In particular, catching WindowsError is a
83 88 # problem because that exception is only defined on Windows...
84 89 os.makedirs(IP_TEST_DIR)
85 90 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
86 91 os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython'))
87 92
88 93
89 94 def teardown():
90 95 """Teardown testenvironment for the module:
91 96
92 97 - Remove dummy home dir tree
93 98 """
94 99 # Note: we remove the parent test dir, which is the root of all test
95 100 # subdirs we may have created. Use shutil instead of os.removedirs, so
96 101 # that non-empty directories are all recursively removed.
97 102 shutil.rmtree(TMP_TEST_DIR)
98 103
99 104
100 105 def setup_environment():
101 106 """Setup testenvironment for some functions that are tested
102 107 in this module. In particular this functions stores attributes
103 108 and other things that we need to stub in some test functions.
104 109 This needs to be done on a function level and not module level because
105 110 each testfunction needs a pristine environment.
106 111 """
107 112 global oldstuff, platformstuff
108 113 oldstuff = (env.copy(), os.name, sys.platform, path.get_home_dir, IPython.__file__, os.getcwd())
109 114
110 if os.name == 'nt':
111 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
112
113
114 115 def teardown_environment():
115 116 """Restore things that were remembered by the setup_environment function
116 117 """
117 118 (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff
118 119 os.chdir(old_wd)
119 120 reload(path)
120 121
121 122 for key in list(env):
122 123 if key not in oldenv:
123 124 del env[key]
124 125 env.update(oldenv)
125 126 if hasattr(sys, 'frozen'):
126 127 del sys.frozen
127 if os.name == 'nt':
128 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
129 128
130 129 # Build decorator that uses the setup_environment/setup_environment
131 130 with_environment = with_setup(setup_environment, teardown_environment)
132 131
133 132 @contextmanager
134 133 def patch_get_home_dir(dirpath):
135 134 orig_get_home_dir = path.get_home_dir
136 135 path.get_home_dir = lambda : dirpath
137 136 try:
138 137 yield
139 138 finally:
140 139 path.get_home_dir = orig_get_home_dir
141 140
142 141 @skip_if_not_win32
143 142 @with_environment
144 143 def test_get_home_dir_1():
145 144 """Testcase for py2exe logic, un-compressed lib
146 145 """
147 146 unfrozen = path.get_home_dir()
148 147 sys.frozen = True
149 148
150 149 #fake filename for IPython.__init__
151 150 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
152 151
153 152 home_dir = path.get_home_dir()
154 153 nt.assert_equal(home_dir, unfrozen)
155 154
156 155
157 156 @skip_if_not_win32
158 157 @with_environment
159 158 def test_get_home_dir_2():
160 159 """Testcase for py2exe logic, compressed lib
161 160 """
162 161 unfrozen = path.get_home_dir()
163 162 sys.frozen = True
164 163 #fake filename for IPython.__init__
165 164 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
166 165
167 166 home_dir = path.get_home_dir(True)
168 167 nt.assert_equal(home_dir, unfrozen)
169 168
170 169
171 170 @with_environment
172 171 def test_get_home_dir_3():
173 172 """get_home_dir() uses $HOME if set"""
174 173 env["HOME"] = HOME_TEST_DIR
175 174 home_dir = path.get_home_dir(True)
176 175 # get_home_dir expands symlinks
177 176 nt.assert_equal(home_dir, os.path.realpath(env["HOME"]))
178 177
179 178
180 179 @with_environment
181 180 def test_get_home_dir_4():
182 181 """get_home_dir() still works if $HOME is not set"""
183 182
184 183 if 'HOME' in env: del env['HOME']
185 184 # this should still succeed, but we don't care what the answer is
186 185 home = path.get_home_dir(False)
187 186
188 187 @with_environment
189 188 def test_get_home_dir_5():
190 189 """raise HomeDirError if $HOME is specified, but not a writable dir"""
191 190 env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
192 191 # set os.name = posix, to prevent My Documents fallback on Windows
193 192 os.name = 'posix'
194 193 nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
195 194
196
197 195 # Should we stub wreg fully so we can run the test on all platforms?
198 196 @skip_if_not_win32
199 197 @with_environment
200 198 def test_get_home_dir_8():
201 199 """Using registry hack for 'My Documents', os=='nt'
202 200
203 201 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
204 202 """
205 203 os.name = 'nt'
206 204 # Remove from stub environment all keys that may be set
207 205 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
208 206 env.pop(key, None)
209 207
210 #Stub windows registry functions
211 def OpenKey(x, y):
212 class key:
213 def Close(self):
214 pass
215 return key()
216 def QueryValueEx(x, y):
217 return [abspath(HOME_TEST_DIR)]
218
219 wreg.OpenKey = OpenKey
220 wreg.QueryValueEx = QueryValueEx
208 class key:
209 def Close(self):
210 pass
221 211
222 home_dir = path.get_home_dir()
212 with patch.object(wreg, 'OpenKey', return_value=key()), \
213 patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]):
214 home_dir = path.get_home_dir()
223 215 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
224 216
225 217
226 218 @with_environment
227 219 def test_get_ipython_dir_1():
228 220 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
229 221 env_ipdir = os.path.join("someplace", ".ipython")
230 222 path._writable_dir = lambda path: True
231 223 env['IPYTHONDIR'] = env_ipdir
232 224 ipdir = path.get_ipython_dir()
233 225 nt.assert_equal(ipdir, env_ipdir)
234 226
235 227
236 228 @with_environment
237 229 def test_get_ipython_dir_2():
238 230 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
239 231 with patch_get_home_dir('someplace'):
240 232 path.get_xdg_dir = lambda : None
241 233 path._writable_dir = lambda path: True
242 234 os.name = "posix"
243 235 env.pop('IPYTHON_DIR', None)
244 236 env.pop('IPYTHONDIR', None)
245 237 env.pop('XDG_CONFIG_HOME', None)
246 238 ipdir = path.get_ipython_dir()
247 239 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
248 240
249 241 @with_environment
250 242 def test_get_ipython_dir_3():
251 243 """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
252 244 tmphome = TemporaryDirectory()
253 245 try:
254 246 with patch_get_home_dir(tmphome.name):
255 247 os.name = "posix"
256 248 env.pop('IPYTHON_DIR', None)
257 249 env.pop('IPYTHONDIR', None)
258 250 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
259 251
260 252 with warnings.catch_warnings(record=True) as w:
261 253 ipdir = path.get_ipython_dir()
262 254
263 255 nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
264 256 if sys.platform != 'darwin':
265 257 nt.assert_equal(len(w), 1)
266 258 nt.assert_in('Moving', str(w[0]))
267 259 finally:
268 260 tmphome.cleanup()
269 261
270 262 @with_environment
271 263 def test_get_ipython_dir_4():
272 264 """test_get_ipython_dir_4, warn if XDG and home both exist."""
273 265 with patch_get_home_dir(HOME_TEST_DIR):
274 266 os.name = "posix"
275 267 env.pop('IPYTHON_DIR', None)
276 268 env.pop('IPYTHONDIR', None)
277 269 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
278 270 try:
279 271 os.mkdir(os.path.join(XDG_TEST_DIR, 'ipython'))
280 272 except OSError as e:
281 273 if e.errno != errno.EEXIST:
282 274 raise
283 275
284 276 with warnings.catch_warnings(record=True) as w:
285 277 ipdir = path.get_ipython_dir()
286 278
287 279 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython"))
288 280 if sys.platform != 'darwin':
289 281 nt.assert_equal(len(w), 1)
290 282 nt.assert_in('Ignoring', str(w[0]))
291 283
292 284 @with_environment
293 285 def test_get_ipython_dir_5():
294 286 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
295 287 with patch_get_home_dir(HOME_TEST_DIR):
296 288 os.name = "posix"
297 289 env.pop('IPYTHON_DIR', None)
298 290 env.pop('IPYTHONDIR', None)
299 291 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
300 292 try:
301 293 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
302 294 except OSError as e:
303 295 if e.errno != errno.ENOENT:
304 296 raise
305 297 ipdir = path.get_ipython_dir()
306 298 nt.assert_equal(ipdir, IP_TEST_DIR)
307 299
308 300 @with_environment
309 301 def test_get_ipython_dir_6():
310 302 """test_get_ipython_dir_6, use home over XDG if defined and neither exist."""
311 303 xdg = os.path.join(HOME_TEST_DIR, 'somexdg')
312 304 os.mkdir(xdg)
313 305 shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython'))
314 306 with patch_get_home_dir(HOME_TEST_DIR):
315 307 orig_get_xdg_dir = path.get_xdg_dir
316 308 path.get_xdg_dir = lambda : xdg
317 309 try:
318 310 os.name = "posix"
319 311 env.pop('IPYTHON_DIR', None)
320 312 env.pop('IPYTHONDIR', None)
321 313 env.pop('XDG_CONFIG_HOME', None)
322 314 with warnings.catch_warnings(record=True) as w:
323 315 ipdir = path.get_ipython_dir()
324 316
325 317 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, '.ipython'))
326 318 nt.assert_equal(len(w), 0)
327 319 finally:
328 320 path.get_xdg_dir = orig_get_xdg_dir
329 321
330 322 @with_environment
331 323 def test_get_ipython_dir_7():
332 324 """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
333 325 path._writable_dir = lambda path: True
334 326 home_dir = os.path.normpath(os.path.expanduser('~'))
335 327 env['IPYTHONDIR'] = os.path.join('~', 'somewhere')
336 328 ipdir = path.get_ipython_dir()
337 329 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
338 330
339 331 @skip_win32
340 332 @with_environment
341 333 def test_get_ipython_dir_8():
342 334 """test_get_ipython_dir_8, test / home directory"""
343 335 old = path._writable_dir, path.get_xdg_dir
344 336 try:
345 337 path._writable_dir = lambda path: bool(path)
346 338 path.get_xdg_dir = lambda: None
347 339 env.pop('IPYTHON_DIR', None)
348 340 env.pop('IPYTHONDIR', None)
349 341 env['HOME'] = '/'
350 342 nt.assert_equal(path.get_ipython_dir(), '/.ipython')
351 343 finally:
352 344 path._writable_dir, path.get_xdg_dir = old
353 345
354 346 @with_environment
355 347 def test_get_xdg_dir_0():
356 348 """test_get_xdg_dir_0, check xdg_dir"""
357 349 reload(path)
358 350 path._writable_dir = lambda path: True
359 351 path.get_home_dir = lambda : 'somewhere'
360 352 os.name = "posix"
361 353 sys.platform = "linux2"
362 354 env.pop('IPYTHON_DIR', None)
363 355 env.pop('IPYTHONDIR', None)
364 356 env.pop('XDG_CONFIG_HOME', None)
365 357
366 358 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
367 359
368 360
369 361 @with_environment
370 362 def test_get_xdg_dir_1():
371 363 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
372 364 reload(path)
373 365 path.get_home_dir = lambda : HOME_TEST_DIR
374 366 os.name = "posix"
375 367 sys.platform = "linux2"
376 368 env.pop('IPYTHON_DIR', None)
377 369 env.pop('IPYTHONDIR', None)
378 370 env.pop('XDG_CONFIG_HOME', None)
379 371 nt.assert_equal(path.get_xdg_dir(), None)
380 372
381 373 @with_environment
382 374 def test_get_xdg_dir_2():
383 375 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
384 376 reload(path)
385 377 path.get_home_dir = lambda : HOME_TEST_DIR
386 378 os.name = "posix"
387 379 sys.platform = "linux2"
388 380 env.pop('IPYTHON_DIR', None)
389 381 env.pop('IPYTHONDIR', None)
390 382 env.pop('XDG_CONFIG_HOME', None)
391 383 cfgdir=os.path.join(path.get_home_dir(), '.config')
392 384 if not os.path.exists(cfgdir):
393 385 os.makedirs(cfgdir)
394 386
395 387 nt.assert_equal(path.get_xdg_dir(), cfgdir)
396 388
397 389 @with_environment
398 390 def test_get_xdg_dir_3():
399 391 """test_get_xdg_dir_3, check xdg_dir not used on OS X"""
400 392 reload(path)
401 393 path.get_home_dir = lambda : HOME_TEST_DIR
402 394 os.name = "posix"
403 395 sys.platform = "darwin"
404 396 env.pop('IPYTHON_DIR', None)
405 397 env.pop('IPYTHONDIR', None)
406 398 env.pop('XDG_CONFIG_HOME', None)
407 399 cfgdir=os.path.join(path.get_home_dir(), '.config')
408 400 if not os.path.exists(cfgdir):
409 401 os.makedirs(cfgdir)
410 402
411 403 nt.assert_equal(path.get_xdg_dir(), None)
412 404
413 405 def test_filefind():
414 406 """Various tests for filefind"""
415 407 f = tempfile.NamedTemporaryFile()
416 408 # print 'fname:',f.name
417 409 alt_dirs = path.get_ipython_dir()
418 410 t = path.filefind(f.name, alt_dirs)
419 411 # print 'found:',t
420 412
421 413 @with_environment
422 414 def test_get_ipython_cache_dir():
423 415 os.environ["HOME"] = HOME_TEST_DIR
424 416 if os.name == 'posix' and sys.platform != 'darwin':
425 417 # test default
426 418 os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
427 419 os.environ.pop("XDG_CACHE_HOME", None)
428 420 ipdir = path.get_ipython_cache_dir()
429 421 nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"),
430 422 ipdir)
431 423 nt.assert_true(os.path.isdir(ipdir))
432 424
433 425 # test env override
434 426 os.environ["XDG_CACHE_HOME"] = XDG_CACHE_DIR
435 427 ipdir = path.get_ipython_cache_dir()
436 428 nt.assert_true(os.path.isdir(ipdir))
437 429 nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython"))
438 430 else:
439 431 nt.assert_equal(path.get_ipython_cache_dir(),
440 432 path.get_ipython_dir())
441 433
442 434 def test_get_ipython_package_dir():
443 435 ipdir = path.get_ipython_package_dir()
444 436 nt.assert_true(os.path.isdir(ipdir))
445 437
446 438
447 439 def test_get_ipython_module_path():
448 440 ipapp_path = path.get_ipython_module_path('IPython.terminal.ipapp')
449 441 nt.assert_true(os.path.isfile(ipapp_path))
450 442
451 443
452 444 @dec.skip_if_not_win32
453 445 def test_get_long_path_name_win32():
454 446 with TemporaryDirectory() as tmpdir:
455 447
456 448 # Make a long path. Expands the path of tmpdir prematurely as it may already have a long
457 449 # path component, so ensure we include the long form of it
458 450 long_path = os.path.join(path.get_long_path_name(tmpdir), u'this is my long path name')
459 451 os.makedirs(long_path)
460 452
461 453 # Test to see if the short path evaluates correctly.
462 454 short_path = os.path.join(tmpdir, u'THISIS~1')
463 455 evaluated_path = path.get_long_path_name(short_path)
464 456 nt.assert_equal(evaluated_path.lower(), long_path.lower())
465 457
466 458
467 459 @dec.skip_win32
468 460 def test_get_long_path_name():
469 461 p = path.get_long_path_name('/usr/local')
470 462 nt.assert_equal(p,'/usr/local')
471 463
472 464 @dec.skip_win32 # can't create not-user-writable dir on win
473 465 @with_environment
474 466 def test_not_writable_ipdir():
475 467 tmpdir = tempfile.mkdtemp()
476 468 os.name = "posix"
477 469 env.pop('IPYTHON_DIR', None)
478 470 env.pop('IPYTHONDIR', None)
479 471 env.pop('XDG_CONFIG_HOME', None)
480 472 env['HOME'] = tmpdir
481 473 ipdir = os.path.join(tmpdir, '.ipython')
482 474 os.mkdir(ipdir)
483 475 os.chmod(ipdir, 600)
484 476 with AssertPrints('is not a writable location', channel='stderr'):
485 477 ipdir = path.get_ipython_dir()
486 478 env.pop('IPYTHON_DIR', None)
487 479
488 480 def test_unquote_filename():
489 481 for win32 in (True, False):
490 482 nt.assert_equal(path.unquote_filename('foo.py', win32=win32), 'foo.py')
491 483 nt.assert_equal(path.unquote_filename('foo bar.py', win32=win32), 'foo bar.py')
492 484 nt.assert_equal(path.unquote_filename('"foo.py"', win32=True), 'foo.py')
493 485 nt.assert_equal(path.unquote_filename('"foo bar.py"', win32=True), 'foo bar.py')
494 486 nt.assert_equal(path.unquote_filename("'foo.py'", win32=True), 'foo.py')
495 487 nt.assert_equal(path.unquote_filename("'foo bar.py'", win32=True), 'foo bar.py')
496 488 nt.assert_equal(path.unquote_filename('"foo.py"', win32=False), '"foo.py"')
497 489 nt.assert_equal(path.unquote_filename('"foo bar.py"', win32=False), '"foo bar.py"')
498 490 nt.assert_equal(path.unquote_filename("'foo.py'", win32=False), "'foo.py'")
499 491 nt.assert_equal(path.unquote_filename("'foo bar.py'", win32=False), "'foo bar.py'")
500 492
501 493 @with_environment
502 494 def test_get_py_filename():
503 495 os.chdir(TMP_TEST_DIR)
504 496 for win32 in (True, False):
505 497 with make_tempfile('foo.py'):
506 498 nt.assert_equal(path.get_py_filename('foo.py', force_win32=win32), 'foo.py')
507 499 nt.assert_equal(path.get_py_filename('foo', force_win32=win32), 'foo.py')
508 500 with make_tempfile('foo'):
509 501 nt.assert_equal(path.get_py_filename('foo', force_win32=win32), 'foo')
510 502 nt.assert_raises(IOError, path.get_py_filename, 'foo.py', force_win32=win32)
511 503 nt.assert_raises(IOError, path.get_py_filename, 'foo', force_win32=win32)
512 504 nt.assert_raises(IOError, path.get_py_filename, 'foo.py', force_win32=win32)
513 505 true_fn = 'foo with spaces.py'
514 506 with make_tempfile(true_fn):
515 507 nt.assert_equal(path.get_py_filename('foo with spaces', force_win32=win32), true_fn)
516 508 nt.assert_equal(path.get_py_filename('foo with spaces.py', force_win32=win32), true_fn)
517 509 if win32:
518 510 nt.assert_equal(path.get_py_filename('"foo with spaces.py"', force_win32=True), true_fn)
519 511 nt.assert_equal(path.get_py_filename("'foo with spaces.py'", force_win32=True), true_fn)
520 512 else:
521 513 nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"', force_win32=False)
522 514 nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'", force_win32=False)
523 515
524 516 @onlyif_unicode_paths
525 517 def test_unicode_in_filename():
526 518 """When a file doesn't exist, the exception raised should be safe to call
527 519 str() on - i.e. in Python 2 it must only have ASCII characters.
528 520
529 521 https://github.com/ipython/ipython/issues/875
530 522 """
531 523 try:
532 524 # these calls should not throw unicode encode exceptions
533 525 path.get_py_filename(u'fooéè.py', force_win32=False)
534 526 except IOError as ex:
535 527 str(ex)
536 528
537 529
538 530 class TestShellGlob(object):
539 531
540 532 @classmethod
541 533 def setUpClass(cls):
542 534 cls.filenames_start_with_a = ['a0', 'a1', 'a2']
543 535 cls.filenames_end_with_b = ['0b', '1b', '2b']
544 536 cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b
545 537 cls.tempdir = TemporaryDirectory()
546 538 td = cls.tempdir.name
547 539
548 540 with cls.in_tempdir():
549 541 # Create empty files
550 542 for fname in cls.filenames:
551 543 open(os.path.join(td, fname), 'w').close()
552 544
553 545 @classmethod
554 546 def tearDownClass(cls):
555 547 cls.tempdir.cleanup()
556 548
557 549 @classmethod
558 550 @contextmanager
559 551 def in_tempdir(cls):
560 552 save = py3compat.getcwd()
561 553 try:
562 554 os.chdir(cls.tempdir.name)
563 555 yield
564 556 finally:
565 557 os.chdir(save)
566 558
567 559 def check_match(self, patterns, matches):
568 560 with self.in_tempdir():
569 561 # glob returns unordered list. that's why sorted is required.
570 562 nt.assert_equals(sorted(path.shellglob(patterns)),
571 563 sorted(matches))
572 564
573 565 def common_cases(self):
574 566 return [
575 567 (['*'], self.filenames),
576 568 (['a*'], self.filenames_start_with_a),
577 569 (['*c'], ['*c']),
578 570 (['*', 'a*', '*b', '*c'], self.filenames
579 571 + self.filenames_start_with_a
580 572 + self.filenames_end_with_b
581 573 + ['*c']),
582 574 (['a[012]'], self.filenames_start_with_a),
583 575 ]
584 576
585 577 @skip_win32
586 578 def test_match_posix(self):
587 579 for (patterns, matches) in self.common_cases() + [
588 580 ([r'\*'], ['*']),
589 581 ([r'a\*', 'a*'], ['a*'] + self.filenames_start_with_a),
590 582 ([r'a\[012]'], ['a[012]']),
591 583 ]:
592 584 yield (self.check_match, patterns, matches)
593 585
594 586 @skip_if_not_win32
595 587 def test_match_windows(self):
596 588 for (patterns, matches) in self.common_cases() + [
597 589 # In windows, backslash is interpreted as path
598 590 # separator. Therefore, you can't escape glob
599 591 # using it.
600 592 ([r'a\*', 'a*'], [r'a\*'] + self.filenames_start_with_a),
601 593 ([r'a\[012]'], [r'a\[012]']),
602 594 ]:
603 595 yield (self.check_match, patterns, matches)
604 596
605 597
606 598 def test_unescape_glob():
607 599 nt.assert_equals(path.unescape_glob(r'\*\[\!\]\?'), '*[!]?')
608 600 nt.assert_equals(path.unescape_glob(r'\\*'), r'\*')
609 601 nt.assert_equals(path.unescape_glob(r'\\\*'), r'\*')
610 602 nt.assert_equals(path.unescape_glob(r'\\a'), r'\a')
611 603 nt.assert_equals(path.unescape_glob(r'\a'), r'\a')
612 604
613 605
614 606 class TestLinkOrCopy(object):
615 607 def setUp(self):
616 608 self.tempdir = TemporaryDirectory()
617 609 self.src = self.dst("src")
618 610 with open(self.src, "w") as f:
619 611 f.write("Hello, world!")
620 612
621 613 def tearDown(self):
622 614 self.tempdir.cleanup()
623 615
624 616 def dst(self, *args):
625 617 return os.path.join(self.tempdir.name, *args)
626 618
627 619 def assert_inode_not_equal(self, a, b):
628 620 nt.assert_not_equals(os.stat(a).st_ino, os.stat(b).st_ino,
629 621 "%r and %r do reference the same indoes" %(a, b))
630 622
631 623 def assert_inode_equal(self, a, b):
632 624 nt.assert_equals(os.stat(a).st_ino, os.stat(b).st_ino,
633 625 "%r and %r do not reference the same indoes" %(a, b))
634 626
635 627 def assert_content_equal(self, a, b):
636 628 with open(a) as a_f:
637 629 with open(b) as b_f:
638 630 nt.assert_equals(a_f.read(), b_f.read())
639 631
640 632 @skip_win32
641 633 def test_link_successful(self):
642 634 dst = self.dst("target")
643 635 path.link_or_copy(self.src, dst)
644 636 self.assert_inode_equal(self.src, dst)
645 637
646 638 @skip_win32
647 639 def test_link_into_dir(self):
648 640 dst = self.dst("some_dir")
649 641 os.mkdir(dst)
650 642 path.link_or_copy(self.src, dst)
651 643 expected_dst = self.dst("some_dir", os.path.basename(self.src))
652 644 self.assert_inode_equal(self.src, expected_dst)
653 645
654 646 @skip_win32
655 647 def test_target_exists(self):
656 648 dst = self.dst("target")
657 649 open(dst, "w").close()
658 650 path.link_or_copy(self.src, dst)
659 651 self.assert_inode_equal(self.src, dst)
660 652
661 653 @skip_win32
662 654 def test_no_link(self):
663 655 real_link = os.link
664 656 try:
665 657 del os.link
666 658 dst = self.dst("target")
667 659 path.link_or_copy(self.src, dst)
668 660 self.assert_content_equal(self.src, dst)
669 661 self.assert_inode_not_equal(self.src, dst)
670 662 finally:
671 663 os.link = real_link
672 664
673 665 @skip_if_not_win32
674 666 def test_windows(self):
675 667 dst = self.dst("target")
676 668 path.link_or_copy(self.src, dst)
677 669 self.assert_content_equal(self.src, dst)
General Comments 0
You need to be logged in to leave comments. Login now