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