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