##// END OF EJS Templates
Make last-ditch attempt to find $HOME when environment is broken....
Fernando Perez -
Show More
@@ -1,383 +1,393 b''
1 1 # encoding: utf-8
2 2 """
3 3 Utilities for path handling.
4 4 """
5 5
6 6 #-----------------------------------------------------------------------------
7 7 # Copyright (C) 2008-2009 The IPython Development Team
8 8 #
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12
13 13 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 import os
18 18 import sys
19 19
20 20 import IPython
21 21 from IPython.utils.process import system
22 22 from IPython.utils.importstring import import_item
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Code
26 26 #-----------------------------------------------------------------------------
27 27
28 28
29 29 def _get_long_path_name(path):
30 30 """Dummy no-op."""
31 31 return path
32 32
33 33
34 34 if sys.platform == 'win32':
35 35 def _get_long_path_name(path):
36 36 """Get a long path name (expand ~) on Windows using ctypes.
37 37
38 38 Examples
39 39 --------
40 40
41 41 >>> get_long_path_name('c:\\docume~1')
42 42 u'c:\\\\Documents and Settings'
43 43
44 44 """
45 45 try:
46 46 import ctypes
47 47 except ImportError:
48 48 raise ImportError('you need to have ctypes installed for this to work')
49 49 _GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
50 50 _GetLongPathName.argtypes = [ctypes.c_wchar_p, ctypes.c_wchar_p,
51 51 ctypes.c_uint ]
52 52
53 53 buf = ctypes.create_unicode_buffer(260)
54 54 rv = _GetLongPathName(path, buf, 260)
55 55 if rv == 0 or rv > 260:
56 56 return path
57 57 else:
58 58 return buf.value
59 59
60 60
61 61 def get_long_path_name(path):
62 62 """Expand a path into its long form.
63 63
64 64 On Windows this expands any ~ in the paths. On other platforms, it is
65 65 a null operation.
66 66 """
67 67 return _get_long_path_name(path)
68 68
69 69
70 70 def get_py_filename(name):
71 71 """Return a valid python filename in the current directory.
72 72
73 73 If the given name is not a file, it adds '.py' and searches again.
74 74 Raises IOError with an informative message if the file isn't found."""
75 75
76 76 name = os.path.expanduser(name)
77 77 if not os.path.isfile(name) and not name.endswith('.py'):
78 78 name += '.py'
79 79 if os.path.isfile(name):
80 80 return name
81 81 else:
82 82 raise IOError,'File `%s` not found.' % name
83 83
84 84
85 85 def filefind(filename, path_dirs=None):
86 86 """Find a file by looking through a sequence of paths.
87 87
88 88 This iterates through a sequence of paths looking for a file and returns
89 89 the full, absolute path of the first occurence of the file. If no set of
90 90 path dirs is given, the filename is tested as is, after running through
91 91 :func:`expandvars` and :func:`expanduser`. Thus a simple call::
92 92
93 93 filefind('myfile.txt')
94 94
95 95 will find the file in the current working dir, but::
96 96
97 97 filefind('~/myfile.txt')
98 98
99 99 Will find the file in the users home directory. This function does not
100 100 automatically try any paths, such as the cwd or the user's home directory.
101 101
102 102 Parameters
103 103 ----------
104 104 filename : str
105 105 The filename to look for.
106 106 path_dirs : str, None or sequence of str
107 107 The sequence of paths to look for the file in. If None, the filename
108 108 need to be absolute or be in the cwd. If a string, the string is
109 109 put into a sequence and the searched. If a sequence, walk through
110 110 each element and join with ``filename``, calling :func:`expandvars`
111 111 and :func:`expanduser` before testing for existence.
112 112
113 113 Returns
114 114 -------
115 115 Raises :exc:`IOError` or returns absolute path to file.
116 116 """
117 117
118 118 # If paths are quoted, abspath gets confused, strip them...
119 119 filename = filename.strip('"').strip("'")
120 120 # If the input is an absolute path, just check it exists
121 121 if os.path.isabs(filename) and os.path.isfile(filename):
122 122 return filename
123 123
124 124 if path_dirs is None:
125 125 path_dirs = ("",)
126 126 elif isinstance(path_dirs, basestring):
127 127 path_dirs = (path_dirs,)
128 128
129 129 for path in path_dirs:
130 130 if path == '.': path = os.getcwd()
131 131 testname = expand_path(os.path.join(path, filename))
132 132 if os.path.isfile(testname):
133 133 return os.path.abspath(testname)
134 134
135 135 raise IOError("File %r does not exist in any of the search paths: %r" %
136 136 (filename, path_dirs) )
137 137
138 138
139 139 class HomeDirError(Exception):
140 140 pass
141 141
142 142
143 143 def get_home_dir():
144 144 """Return the closest possible equivalent to a 'home' directory.
145 145
146 146 * On POSIX, we try $HOME.
147 147 * On Windows we try:
148 148 - %HOMESHARE%
149 149 - %HOMEDRIVE\%HOMEPATH%
150 150 - %USERPROFILE%
151 151 - Registry hack for My Documents
152 152 - %HOME%: rare, but some people with unix-like setups may have defined it
153 153 * On Dos C:\
154 154
155 155 Currently only Posix and NT are implemented, a HomeDirError exception is
156 156 raised for all other OSes.
157 157 """
158 158
159 159 isdir = os.path.isdir
160 160 env = os.environ
161 161
162 162 # first, check py2exe distribution root directory for _ipython.
163 163 # This overrides all. Normally does not exist.
164 164
165 165 if hasattr(sys, "frozen"): #Is frozen by py2exe
166 166 if '\\library.zip\\' in IPython.__file__.lower():#libraries compressed to zip-file
167 167 root, rest = IPython.__file__.lower().split('library.zip')
168 168 else:
169 169 root=os.path.join(os.path.split(IPython.__file__)[0],"../../")
170 170 root=os.path.abspath(root).rstrip('\\')
171 171 if isdir(os.path.join(root, '_ipython')):
172 172 os.environ["IPYKITROOT"] = root
173 173 return root.decode(sys.getfilesystemencoding())
174 174
175 175 if os.name == 'posix':
176 176 # Linux, Unix, AIX, OS X
177 177 try:
178 178 homedir = env['HOME']
179 179 except KeyError:
180 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
180 # Last-ditch attempt at finding a suitable $HOME, on systems where
181 # it may not be defined in the environment but the system shell
182 # still knows it - reported once as:
183 # https://github.com/ipython/ipython/issues/154
184 from subprocess import Popen, PIPE
185 homedir = Popen('echo $HOME', shell=True,
186 stdout=PIPE).communicate()[0].strip()
187 if homedir:
188 return homedir.decode(sys.getfilesystemencoding())
189 else:
190 raise HomeDirError('Undefined $HOME, IPython cannot proceed.')
181 191 else:
182 192 return homedir.decode(sys.getfilesystemencoding())
183 193 elif os.name == 'nt':
184 194 # Now for win9x, XP, Vista, 7?
185 195 # For some strange reason all of these return 'nt' for os.name.
186 196 # First look for a network home directory. This will return the UNC
187 197 # path (\\server\\Users\%username%) not the mapped path (Z:\). This
188 198 # is needed when running IPython on cluster where all paths have to
189 199 # be UNC.
190 200 try:
191 201 homedir = env['HOMESHARE']
192 202 except KeyError:
193 203 pass
194 204 else:
195 205 if isdir(homedir):
196 206 return homedir.decode(sys.getfilesystemencoding())
197 207
198 208 # Now look for a local home directory
199 209 try:
200 210 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
201 211 except KeyError:
202 212 pass
203 213 else:
204 214 if isdir(homedir):
205 215 return homedir.decode(sys.getfilesystemencoding())
206 216
207 217 # Now the users profile directory
208 218 try:
209 219 homedir = os.path.join(env['USERPROFILE'])
210 220 except KeyError:
211 221 pass
212 222 else:
213 223 if isdir(homedir):
214 224 return homedir.decode(sys.getfilesystemencoding())
215 225
216 226 # Use the registry to get the 'My Documents' folder.
217 227 try:
218 228 import _winreg as wreg
219 229 key = wreg.OpenKey(
220 230 wreg.HKEY_CURRENT_USER,
221 231 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
222 232 )
223 233 homedir = wreg.QueryValueEx(key,'Personal')[0]
224 234 key.Close()
225 235 except:
226 236 pass
227 237 else:
228 238 if isdir(homedir):
229 239 return homedir.decode(sys.getfilesystemencoding())
230 240
231 241 # A user with a lot of unix tools in win32 may have defined $HOME.
232 242 # Try this as a last ditch option.
233 243 try:
234 244 homedir = env['HOME']
235 245 except KeyError:
236 246 pass
237 247 else:
238 248 if isdir(homedir):
239 249 return homedir.decode(sys.getfilesystemencoding())
240 250
241 251 # If all else fails, raise HomeDirError
242 252 raise HomeDirError('No valid home directory could be found')
243 253 elif os.name == 'dos':
244 254 # Desperate, may do absurd things in classic MacOS. May work under DOS.
245 255 return 'C:\\'.decode(sys.getfilesystemencoding())
246 256 else:
247 257 raise HomeDirError('No valid home directory could be found for your OS')
248 258
249 259 def get_xdg_dir():
250 260 """Return the XDG_CONFIG_HOME, if it is defined and exists, else None.
251 261
252 262 This is only for posix (Linux,Unix,OS X, etc) systems.
253 263 """
254 264
255 265 isdir = os.path.isdir
256 266 env = os.environ
257 267
258 268 if os.name == 'posix':
259 269 # Linux, Unix, AIX, OS X
260 270 # use ~/.config if not set OR empty
261 271 xdg = env.get("XDG_CONFIG_HOME", None) or os.path.join(get_home_dir(), '.config')
262 272 if xdg and isdir(xdg):
263 273 return xdg.decode(sys.getfilesystemencoding())
264 274
265 275 return None
266 276
267 277
268 278 def get_ipython_dir():
269 279 """Get the IPython directory for this platform and user.
270 280
271 281 This uses the logic in `get_home_dir` to find the home directory
272 282 and the adds .ipython to the end of the path.
273 283 """
274 284
275 285 env = os.environ
276 286 pjoin = os.path.join
277 287 exists = os.path.exists
278 288
279 289 ipdir_def = '.ipython'
280 290 xdg_def = 'ipython'
281 291
282 292 home_dir = get_home_dir()
283 293 xdg_dir = get_xdg_dir()
284 294 # import pdb; pdb.set_trace() # dbg
285 295 ipdir = env.get('IPYTHON_DIR', env.get('IPYTHONDIR', None))
286 296 if ipdir is None:
287 297 # not set explicitly, use XDG_CONFIG_HOME or HOME
288 298 home_ipdir = pjoin(home_dir, ipdir_def)
289 299 if xdg_dir:
290 300 # use XDG, as long as the user isn't already
291 301 # using $HOME/.ipython and *not* XDG/ipython
292 302
293 303 xdg_ipdir = pjoin(xdg_dir, xdg_def)
294 304
295 305 if exists(xdg_ipdir) or not exists(home_ipdir):
296 306 ipdir = xdg_ipdir
297 307
298 308 if ipdir is None:
299 309 # not using XDG
300 310 ipdir = home_ipdir
301 311
302 312 return ipdir.decode(sys.getfilesystemencoding())
303 313
304 314
305 315 def get_ipython_package_dir():
306 316 """Get the base directory where IPython itself is installed."""
307 317 ipdir = os.path.dirname(IPython.__file__)
308 318 return ipdir.decode(sys.getfilesystemencoding())
309 319
310 320
311 321 def get_ipython_module_path(module_str):
312 322 """Find the path to an IPython module in this version of IPython.
313 323
314 324 This will always find the version of the module that is in this importable
315 325 IPython package. This will always return the path to the ``.py``
316 326 version of the module.
317 327 """
318 328 if module_str == 'IPython':
319 329 return os.path.join(get_ipython_package_dir(), '__init__.py')
320 330 mod = import_item(module_str)
321 331 the_path = mod.__file__.replace('.pyc', '.py')
322 332 the_path = the_path.replace('.pyo', '.py')
323 333 return the_path.decode(sys.getfilesystemencoding())
324 334
325 335
326 336 def expand_path(s):
327 337 """Expand $VARS and ~names in a string, like a shell
328 338
329 339 :Examples:
330 340
331 341 In [2]: os.environ['FOO']='test'
332 342
333 343 In [3]: expand_path('variable FOO is $FOO')
334 344 Out[3]: 'variable FOO is test'
335 345 """
336 346 # This is a pretty subtle hack. When expand user is given a UNC path
337 347 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
338 348 # the $ to get (\\server\share\%username%). I think it considered $
339 349 # alone an empty var. But, we need the $ to remains there (it indicates
340 350 # a hidden share).
341 351 if os.name=='nt':
342 352 s = s.replace('$\\', 'IPYTHON_TEMP')
343 353 s = os.path.expandvars(os.path.expanduser(s))
344 354 if os.name=='nt':
345 355 s = s.replace('IPYTHON_TEMP', '$\\')
346 356 return s
347 357
348 358
349 359 def target_outdated(target,deps):
350 360 """Determine whether a target is out of date.
351 361
352 362 target_outdated(target,deps) -> 1/0
353 363
354 364 deps: list of filenames which MUST exist.
355 365 target: single filename which may or may not exist.
356 366
357 367 If target doesn't exist or is older than any file listed in deps, return
358 368 true, otherwise return false.
359 369 """
360 370 try:
361 371 target_time = os.path.getmtime(target)
362 372 except os.error:
363 373 return 1
364 374 for dep in deps:
365 375 dep_time = os.path.getmtime(dep)
366 376 if dep_time > target_time:
367 377 #print "For target",target,"Dep failed:",dep # dbg
368 378 #print "times (dep,tar):",dep_time,target_time # dbg
369 379 return 1
370 380 return 0
371 381
372 382
373 383 def target_update(target,deps,cmd):
374 384 """Update a target with a given command given a list of dependencies.
375 385
376 386 target_update(target,deps,cmd) -> runs cmd if target is outdated.
377 387
378 388 This is just a wrapper around target_outdated() which calls the given
379 389 command if target is outdated."""
380 390
381 391 if target_outdated(target,deps):
382 392 system(cmd)
383 393
@@ -1,358 +1,359 b''
1 1 # encoding: utf-8
2 2 """Tests for IPython.utils.path.py"""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2008 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 import os
16 16 import shutil
17 17 import sys
18 18 import tempfile
19 19
20 20 from os.path import join, abspath, split
21 21
22 22 import nose.tools as nt
23 23
24 24 from nose import with_setup
25 25
26 26 import IPython
27 27 from IPython.testing import decorators as dec
28 28 from IPython.testing.decorators import skip_if_not_win32, skip_win32
29 29 from IPython.utils import path
30 30
31 31 # Platform-dependent imports
32 32 try:
33 33 import _winreg as wreg
34 34 except ImportError:
35 35 #Fake _winreg module on none windows platforms
36 36 import new
37 37 sys.modules["_winreg"] = new.module("_winreg")
38 38 import _winreg as wreg
39 39 #Add entries that needs to be stubbed by the testing code
40 40 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
41 41
42 42 #-----------------------------------------------------------------------------
43 43 # Globals
44 44 #-----------------------------------------------------------------------------
45 45 env = os.environ
46 46 TEST_FILE_PATH = split(abspath(__file__))[0]
47 47 TMP_TEST_DIR = tempfile.mkdtemp()
48 48 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
49 49 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
50 50 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
51 51 #
52 52 # Setup/teardown functions/decorators
53 53 #
54 54
55 55 def setup():
56 56 """Setup testenvironment for the module:
57 57
58 58 - Adds dummy home dir tree
59 59 """
60 60 # Do not mask exceptions here. In particular, catching WindowsError is a
61 61 # problem because that exception is only defined on Windows...
62 62 os.makedirs(IP_TEST_DIR)
63 63 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
64 64
65 65
66 66 def teardown():
67 67 """Teardown testenvironment for the module:
68 68
69 69 - Remove dummy home dir tree
70 70 """
71 71 # Note: we remove the parent test dir, which is the root of all test
72 72 # subdirs we may have created. Use shutil instead of os.removedirs, so
73 73 # that non-empty directories are all recursively removed.
74 74 shutil.rmtree(TMP_TEST_DIR)
75 75
76 76
77 77 def setup_environment():
78 78 """Setup testenvironment for some functions that are tested
79 79 in this module. In particular this functions stores attributes
80 80 and other things that we need to stub in some test functions.
81 81 This needs to be done on a function level and not module level because
82 82 each testfunction needs a pristine environment.
83 83 """
84 84 global oldstuff, platformstuff
85 85 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
86 86
87 87 if os.name == 'nt':
88 88 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
89 89
90 90
91 91 def teardown_environment():
92 92 """Restore things that were remebered by the setup_environment function
93 93 """
94 94 (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff
95 95
96 96 for key in env.keys():
97 97 if key not in oldenv:
98 98 del env[key]
99 99 env.update(oldenv)
100 100 if hasattr(sys, 'frozen'):
101 101 del sys.frozen
102 102 if os.name == 'nt':
103 103 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
104 104
105 105 # Build decorator that uses the setup_environment/setup_environment
106 106 with_environment = with_setup(setup_environment, teardown_environment)
107 107
108 108
109 109 @skip_if_not_win32
110 110 @with_environment
111 111 def test_get_home_dir_1():
112 112 """Testcase for py2exe logic, un-compressed lib
113 113 """
114 114 sys.frozen = True
115 115
116 116 #fake filename for IPython.__init__
117 117 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
118 118
119 119 home_dir = path.get_home_dir()
120 120 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
121 121
122 122
123 123 @skip_if_not_win32
124 124 @with_environment
125 125 def test_get_home_dir_2():
126 126 """Testcase for py2exe logic, compressed lib
127 127 """
128 128 sys.frozen = True
129 129 #fake filename for IPython.__init__
130 130 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
131 131
132 132 home_dir = path.get_home_dir()
133 133 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
134 134
135 135
136 136 @with_environment
137 137 @skip_win32
138 138 def test_get_home_dir_3():
139 139 """Testcase $HOME is set, then use its value as home directory."""
140 140 env["HOME"] = HOME_TEST_DIR
141 141 home_dir = path.get_home_dir()
142 142 nt.assert_equal(home_dir, env["HOME"])
143 143
144 144
145 145 @with_environment
146 146 def test_get_home_dir_4():
147 147 """Testcase $HOME is not set, os=='posix'.
148 148 This should fail with HomeDirError"""
149 149
150 150 os.name = 'posix'
151 151 if 'HOME' in env: del env['HOME']
152 152 nt.assert_raises(path.HomeDirError, path.get_home_dir)
153 153
154 154
155 155 @skip_if_not_win32
156 156 @with_environment
157 157 def test_get_home_dir_5():
158 158 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
159 159
160 160 HOMESHARE is missing.
161 161 """
162 162
163 163 os.name = 'nt'
164 164 env.pop('HOMESHARE', None)
165 165 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
166 166 home_dir = path.get_home_dir()
167 167 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
168 168
169 169
170 170 @skip_if_not_win32
171 171 @with_environment
172 172 def test_get_home_dir_6():
173 173 """Using USERPROFILE, os=='nt'.
174 174
175 175 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
176 176 """
177 177
178 178 os.name = 'nt'
179 179 env.pop('HOMESHARE', None)
180 180 env.pop('HOMEDRIVE', None)
181 181 env.pop('HOMEPATH', None)
182 182 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
183 183 home_dir = path.get_home_dir()
184 184 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
185 185
186 186
187 187 @skip_if_not_win32
188 188 @with_environment
189 189 def test_get_home_dir_7():
190 190 """Using HOMESHARE, os=='nt'."""
191 191
192 192 os.name = 'nt'
193 193 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
194 194 home_dir = path.get_home_dir()
195 195 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
196
196 197
197 198 # Should we stub wreg fully so we can run the test on all platforms?
198 199 @skip_if_not_win32
199 200 @with_environment
200 201 def test_get_home_dir_8():
201 202 """Using registry hack for 'My Documents', os=='nt'
202 203
203 204 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
204 205 """
205 206 os.name = 'nt'
206 207 # Remove from stub environment all keys that may be set
207 208 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
208 209 env.pop(key, None)
209 210
210 211 #Stub windows registry functions
211 212 def OpenKey(x, y):
212 213 class key:
213 214 def Close(self):
214 215 pass
215 216 return key()
216 217 def QueryValueEx(x, y):
217 218 return [abspath(HOME_TEST_DIR)]
218 219
219 220 wreg.OpenKey = OpenKey
220 221 wreg.QueryValueEx = QueryValueEx
221 222
222 223 home_dir = path.get_home_dir()
223 224 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
224 225
225 226
226 227 @with_environment
227 228 def test_get_ipython_dir_1():
228 229 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
229 230 env['IPYTHON_DIR'] = "someplace/.ipython"
230 231 ipdir = path.get_ipython_dir()
231 232 nt.assert_equal(ipdir, "someplace/.ipython")
232 233
233 234
234 235 @with_environment
235 236 def test_get_ipython_dir_2():
236 237 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
237 238 path.get_home_dir = lambda : "someplace"
238 239 os.name = "posix"
239 240 env.pop('IPYTHON_DIR', None)
240 241 env.pop('IPYTHONDIR', None)
241 242 env.pop('XDG_CONFIG_HOME', None)
242 243 ipdir = path.get_ipython_dir()
243 244 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
244 245
245 246 @with_environment
246 247 def test_get_ipython_dir_3():
247 248 """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist."""
248 249 path.get_home_dir = lambda : "someplace"
249 250 os.name = "posix"
250 251 env.pop('IPYTHON_DIR', None)
251 252 env.pop('IPYTHONDIR', None)
252 253 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
253 254 ipdir = path.get_ipython_dir()
254 255 nt.assert_equal(ipdir, os.path.join(XDG_TEST_DIR, "ipython"))
255 256
256 257 @with_environment
257 258 def test_get_ipython_dir_4():
258 259 """test_get_ipython_dir_4, use XDG if both exist."""
259 260 path.get_home_dir = lambda : HOME_TEST_DIR
260 261 os.name = "posix"
261 262 env.pop('IPYTHON_DIR', None)
262 263 env.pop('IPYTHONDIR', None)
263 264 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
264 265 xdg_ipdir = os.path.join(XDG_TEST_DIR, "ipython")
265 266 ipdir = path.get_ipython_dir()
266 267 nt.assert_equal(ipdir, xdg_ipdir)
267 268
268 269 @with_environment
269 270 def test_get_ipython_dir_5():
270 271 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
271 272 os.name = "posix"
272 273 env.pop('IPYTHON_DIR', None)
273 274 env.pop('IPYTHONDIR', None)
274 275 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
275 276 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
276 277 ipdir = path.get_ipython_dir()
277 278 nt.assert_equal(ipdir, IP_TEST_DIR)
278 279
279 280 @with_environment
280 281 def test_get_ipython_dir_6():
281 282 """test_get_ipython_dir_6, use XDG if defined and neither exist."""
282 283 path.get_home_dir = lambda : 'somehome'
283 284 path.get_xdg_dir = lambda : 'somexdg'
284 285 os.name = "posix"
285 286 env.pop('IPYTHON_DIR', None)
286 287 env.pop('IPYTHONDIR', None)
287 288 xdg_ipdir = os.path.join("somexdg", "ipython")
288 289 ipdir = path.get_ipython_dir()
289 290 nt.assert_equal(ipdir, xdg_ipdir)
290 291
291 292 @with_environment
292 293 def test_get_xdg_dir_1():
293 294 """test_get_xdg_dir_1, check xdg_dir"""
294 295 reload(path)
295 296 path.get_home_dir = lambda : 'somewhere'
296 297 os.name = "posix"
297 298 env.pop('IPYTHON_DIR', None)
298 299 env.pop('IPYTHONDIR', None)
299 300 env.pop('XDG_CONFIG_HOME', None)
300 301
301 302 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
302 303
303 304
304 305 @with_environment
305 306 def test_get_xdg_dir_1():
306 307 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
307 308 reload(path)
308 309 path.get_home_dir = lambda : HOME_TEST_DIR
309 310 os.name = "posix"
310 311 env.pop('IPYTHON_DIR', None)
311 312 env.pop('IPYTHONDIR', None)
312 313 env.pop('XDG_CONFIG_HOME', None)
313 314 nt.assert_equal(path.get_xdg_dir(), None)
314 315
315 316 @with_environment
316 317 def test_get_xdg_dir_2():
317 318 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
318 319 reload(path)
319 320 path.get_home_dir = lambda : HOME_TEST_DIR
320 321 os.name = "posix"
321 322 env.pop('IPYTHON_DIR', None)
322 323 env.pop('IPYTHONDIR', None)
323 324 env.pop('XDG_CONFIG_HOME', None)
324 325 cfgdir=os.path.join(path.get_home_dir(), '.config')
325 326 os.makedirs(cfgdir)
326 327
327 328 nt.assert_equal(path.get_xdg_dir(), cfgdir)
328 329
329 330 def test_filefind():
330 331 """Various tests for filefind"""
331 332 f = tempfile.NamedTemporaryFile()
332 333 # print 'fname:',f.name
333 334 alt_dirs = path.get_ipython_dir()
334 335 t = path.filefind(f.name, alt_dirs)
335 336 # print 'found:',t
336 337
337 338
338 339 def test_get_ipython_package_dir():
339 340 ipdir = path.get_ipython_package_dir()
340 341 nt.assert_true(os.path.isdir(ipdir))
341 342
342 343
343 344 def test_get_ipython_module_path():
344 345 ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp')
345 346 nt.assert_true(os.path.isfile(ipapp_path))
346 347
347 348
348 349 @dec.skip_if_not_win32
349 350 def test_get_long_path_name_win32():
350 351 p = path.get_long_path_name('c:\\docume~1')
351 352 nt.assert_equals(p,u'c:\\Documents and Settings')
352 353
353 354
354 355 @dec.skip_win32
355 356 def test_get_long_path_name():
356 357 p = path.get_long_path_name('/usr/local')
357 358 nt.assert_equals(p,'/usr/local')
358 359
General Comments 0
You need to be logged in to leave comments. Login now