##// END OF EJS Templates
Fixing broken tests on win32....
bgranger -
Show More
@@ -1,67 +1,68 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Test process execution and IO redirection.
3 Test process execution and IO redirection.
4 """
4 """
5
5
6 __docformat__ = "restructuredtext en"
6 __docformat__ = "restructuredtext en"
7
7
8 #-----------------------------------------------------------------------------
8 #-----------------------------------------------------------------------------
9 # Copyright (C) 2008-2009 The IPython Development Team
9 # Copyright (C) 2008-2009 The IPython Development Team
10 #
10 #
11 # Distributed under the terms of the BSD License. The full license is
11 # Distributed under the terms of the BSD License. The full license is
12 # in the file COPYING, distributed as part of this software.
12 # in the file COPYING, distributed as part of this software.
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 from cStringIO import StringIO
15 from cStringIO import StringIO
16 from time import sleep
16 from time import sleep
17 import sys
17 import sys
18
18
19 from IPython.frontend.process import PipedProcess
19 from IPython.frontend.process import PipedProcess
20 from IPython.testing import decorators as testdec
20 from IPython.testing import decorators as testdec
21
21
22
22
23 def test_capture_out():
23 def test_capture_out():
24 """ A simple test to see if we can execute a process and get the output.
24 """ A simple test to see if we can execute a process and get the output.
25 """
25 """
26 s = StringIO()
26 s = StringIO()
27 p = PipedProcess('echo 1', out_callback=s.write, )
27 p = PipedProcess('echo 1', out_callback=s.write, )
28 p.start()
28 p.start()
29 p.join()
29 p.join()
30 result = s.getvalue().rstrip()
30 result = s.getvalue().rstrip()
31 assert result == '1'
31 assert result == '1'
32
32
33
33
34 def test_io():
34 def test_io():
35 """ Checks that we can send characters on stdin to the process.
35 """ Checks that we can send characters on stdin to the process.
36 """
36 """
37 s = StringIO()
37 s = StringIO()
38 p = PipedProcess(sys.executable + ' -c "a = raw_input(); print a"',
38 p = PipedProcess(sys.executable + ' -c "a = raw_input(); print a"',
39 out_callback=s.write, )
39 out_callback=s.write, )
40 p.start()
40 p.start()
41 test_string = '12345\n'
41 test_string = '12345\n'
42 while not hasattr(p, 'process'):
42 while not hasattr(p, 'process'):
43 sleep(0.1)
43 sleep(0.1)
44 p.process.stdin.write(test_string)
44 p.process.stdin.write(test_string)
45 p.join()
45 p.join()
46 result = s.getvalue()
46 result = s.getvalue()
47 assert result == test_string
47 assert result == test_string
48
48
49
49
50 @testdec.skip_win32
50 def test_kill():
51 def test_kill():
51 """ Check that we can kill a process, and its subprocess.
52 """ Check that we can kill a process, and its subprocess.
52 """
53 """
53 s = StringIO()
54 s = StringIO()
54 p = PipedProcess(sys.executable + ' -c "a = raw_input();"',
55 p = PipedProcess(sys.executable + ' -c "a = raw_input();"',
55 out_callback=s.write, )
56 out_callback=s.write, )
56 p.start()
57 p.start()
57 while not hasattr(p, 'process'):
58 while not hasattr(p, 'process'):
58 sleep(0.1)
59 sleep(0.1)
59 p.process.kill()
60 p.process.kill()
60 assert p.process.poll() is not None
61 assert p.process.poll() is not None
61
62
62
63
63 if __name__ == '__main__':
64 if __name__ == '__main__':
64 test_capture_out()
65 test_capture_out()
65 test_io()
66 test_io()
66 test_kill()
67 test_kill()
67
68
@@ -1,345 +1,345 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
149 - %HOMESHARE%
148 - %HOMESHARE%
150 - %HOMEDRIVE\%HOMEPATH%
149 - %HOMEDRIVE\%HOMEPATH%
151 - %USERPROFILE%
150 - %USERPROFILE%
152 - Registry hack
151 - Registry hack for My Documents
152 - %HOME%: rare, but some people with unix-like setups may have defined it
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 homedir = env['HOMESHARE']
191 homedir = env['HOMESHARE']
192 except KeyError:
192 except KeyError:
193 pass
193 pass
194 else:
194 else:
195 if isdir(homedir):
195 if isdir(homedir):
196 return homedir.decode(sys.getfilesystemencoding())
196 return homedir.decode(sys.getfilesystemencoding())
197
197
198 # Now look for a local home directory
198 # Now look for a local home directory
199 try:
199 try:
200 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
200 homedir = os.path.join(env['HOMEDRIVE'],env['HOMEPATH'])
201 except KeyError:
201 except KeyError:
202 pass
202 pass
203 else:
203 else:
204 if isdir(homedir):
204 if isdir(homedir):
205 return homedir.decode(sys.getfilesystemencoding())
205 return homedir.decode(sys.getfilesystemencoding())
206
206
207 # Now the users profile directory
207 # Now the users profile directory
208 try:
208 try:
209 homedir = os.path.join(env['USERPROFILE'])
209 homedir = os.path.join(env['USERPROFILE'])
210 except KeyError:
210 except KeyError:
211 pass
211 pass
212 else:
212 else:
213 if isdir(homedir):
213 if isdir(homedir):
214 return homedir.decode(sys.getfilesystemencoding())
214 return homedir.decode(sys.getfilesystemencoding())
215
215
216 # Use the registry to get the 'My Documents' folder.
216 # Use the registry to get the 'My Documents' folder.
217 try:
217 try:
218 import _winreg as wreg
218 import _winreg as wreg
219 key = wreg.OpenKey(
219 key = wreg.OpenKey(
220 wreg.HKEY_CURRENT_USER,
220 wreg.HKEY_CURRENT_USER,
221 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
221 "Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders"
222 )
222 )
223 homedir = wreg.QueryValueEx(key,'Personal')[0]
223 homedir = wreg.QueryValueEx(key,'Personal')[0]
224 key.Close()
224 key.Close()
225 except:
225 except:
226 pass
226 pass
227 else:
227 else:
228 if isdir(homedir):
228 if isdir(homedir):
229 return homedir.decode(sys.getfilesystemencoding())
229 return homedir.decode(sys.getfilesystemencoding())
230
230
231 # A user with a lot of unix tools in win32 may have defined $HOME.
231 # A user with a lot of unix tools in win32 may have defined $HOME.
232 # Try this as a last ditch option.
232 # Try this as a last ditch option.
233 try:
233 try:
234 homedir = env['HOME']
234 homedir = env['HOME']
235 except KeyError:
235 except KeyError:
236 pass
236 pass
237 else:
237 else:
238 if isdir(homedir):
238 if isdir(homedir):
239 return homedir.decode(sys.getfilesystemencoding())
239 return homedir.decode(sys.getfilesystemencoding())
240
240
241 # If all else fails, raise HomeDirError
241 # If all else fails, raise HomeDirError
242 raise HomeDirError('No valid home directory could be found')
242 raise HomeDirError('No valid home directory could be found')
243 elif os.name == 'dos':
243 elif os.name == 'dos':
244 # Desperate, may do absurd things in classic MacOS. May work under DOS.
244 # Desperate, may do absurd things in classic MacOS. May work under DOS.
245 return 'C:\\'.decode(sys.getfilesystemencoding())
245 return 'C:\\'.decode(sys.getfilesystemencoding())
246 else:
246 else:
247 raise HomeDirError('No valid home directory could be found for your OS')
247 raise HomeDirError('No valid home directory could be found for your OS')
248
248
249
249
250 def get_ipython_dir():
250 def get_ipython_dir():
251 """Get the IPython directory for this platform and user.
251 """Get the IPython directory for this platform and user.
252
252
253 This uses the logic in `get_home_dir` to find the home directory
253 This uses the logic in `get_home_dir` to find the home directory
254 and the adds .ipython to the end of the path.
254 and the adds .ipython to the end of the path.
255 """
255 """
256 ipdir_def = '.ipython'
256 ipdir_def = '.ipython'
257 home_dir = get_home_dir()
257 home_dir = get_home_dir()
258 # import pdb; pdb.set_trace() # dbg
258 # import pdb; pdb.set_trace() # dbg
259 ipdir = os.environ.get(
259 ipdir = os.environ.get(
260 'IPYTHON_DIR', os.environ.get(
260 'IPYTHON_DIR', os.environ.get(
261 'IPYTHONDIR', os.path.join(home_dir, ipdir_def)
261 'IPYTHONDIR', os.path.join(home_dir, ipdir_def)
262 )
262 )
263 )
263 )
264 return ipdir.decode(sys.getfilesystemencoding())
264 return ipdir.decode(sys.getfilesystemencoding())
265
265
266
266
267 def get_ipython_package_dir():
267 def get_ipython_package_dir():
268 """Get the base directory where IPython itself is installed."""
268 """Get the base directory where IPython itself is installed."""
269 ipdir = os.path.dirname(IPython.__file__)
269 ipdir = os.path.dirname(IPython.__file__)
270 return ipdir.decode(sys.getfilesystemencoding())
270 return ipdir.decode(sys.getfilesystemencoding())
271
271
272
272
273 def get_ipython_module_path(module_str):
273 def get_ipython_module_path(module_str):
274 """Find the path to an IPython module in this version of IPython.
274 """Find the path to an IPython module in this version of IPython.
275
275
276 This will always find the version of the module that is in this importable
276 This will always find the version of the module that is in this importable
277 IPython package. This will always return the path to the ``.py``
277 IPython package. This will always return the path to the ``.py``
278 version of the module.
278 version of the module.
279 """
279 """
280 if module_str == 'IPython':
280 if module_str == 'IPython':
281 return os.path.join(get_ipython_package_dir(), '__init__.py')
281 return os.path.join(get_ipython_package_dir(), '__init__.py')
282 mod = import_item(module_str)
282 mod = import_item(module_str)
283 the_path = mod.__file__.replace('.pyc', '.py')
283 the_path = mod.__file__.replace('.pyc', '.py')
284 the_path = the_path.replace('.pyo', '.py')
284 the_path = the_path.replace('.pyo', '.py')
285 return the_path.decode(sys.getfilesystemencoding())
285 return the_path.decode(sys.getfilesystemencoding())
286
286
287
287
288 def expand_path(s):
288 def expand_path(s):
289 """Expand $VARS and ~names in a string, like a shell
289 """Expand $VARS and ~names in a string, like a shell
290
290
291 :Examples:
291 :Examples:
292
292
293 In [2]: os.environ['FOO']='test'
293 In [2]: os.environ['FOO']='test'
294
294
295 In [3]: expand_path('variable FOO is $FOO')
295 In [3]: expand_path('variable FOO is $FOO')
296 Out[3]: 'variable FOO is test'
296 Out[3]: 'variable FOO is test'
297 """
297 """
298 # This is a pretty subtle hack. When expand user is given a UNC path
298 # This is a pretty subtle hack. When expand user is given a UNC path
299 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
299 # on Windows (\\server\share$\%username%), os.path.expandvars, removes
300 # the $ to get (\\server\share\%username%). I think it considered $
300 # the $ to get (\\server\share\%username%). I think it considered $
301 # alone an empty var. But, we need the $ to remains there (it indicates
301 # alone an empty var. But, we need the $ to remains there (it indicates
302 # a hidden share).
302 # a hidden share).
303 if os.name=='nt':
303 if os.name=='nt':
304 s = s.replace('$\\', 'IPYTHON_TEMP')
304 s = s.replace('$\\', 'IPYTHON_TEMP')
305 s = os.path.expandvars(os.path.expanduser(s))
305 s = os.path.expandvars(os.path.expanduser(s))
306 if os.name=='nt':
306 if os.name=='nt':
307 s = s.replace('IPYTHON_TEMP', '$\\')
307 s = s.replace('IPYTHON_TEMP', '$\\')
308 return s
308 return s
309
309
310
310
311 def target_outdated(target,deps):
311 def target_outdated(target,deps):
312 """Determine whether a target is out of date.
312 """Determine whether a target is out of date.
313
313
314 target_outdated(target,deps) -> 1/0
314 target_outdated(target,deps) -> 1/0
315
315
316 deps: list of filenames which MUST exist.
316 deps: list of filenames which MUST exist.
317 target: single filename which may or may not exist.
317 target: single filename which may or may not exist.
318
318
319 If target doesn't exist or is older than any file listed in deps, return
319 If target doesn't exist or is older than any file listed in deps, return
320 true, otherwise return false.
320 true, otherwise return false.
321 """
321 """
322 try:
322 try:
323 target_time = os.path.getmtime(target)
323 target_time = os.path.getmtime(target)
324 except os.error:
324 except os.error:
325 return 1
325 return 1
326 for dep in deps:
326 for dep in deps:
327 dep_time = os.path.getmtime(dep)
327 dep_time = os.path.getmtime(dep)
328 if dep_time > target_time:
328 if dep_time > target_time:
329 #print "For target",target,"Dep failed:",dep # dbg
329 #print "For target",target,"Dep failed:",dep # dbg
330 #print "times (dep,tar):",dep_time,target_time # dbg
330 #print "times (dep,tar):",dep_time,target_time # dbg
331 return 1
331 return 1
332 return 0
332 return 0
333
333
334
334
335 def target_update(target,deps,cmd):
335 def target_update(target,deps,cmd):
336 """Update a target with a given command given a list of dependencies.
336 """Update a target with a given command given a list of dependencies.
337
337
338 target_update(target,deps,cmd) -> runs cmd if target is outdated.
338 target_update(target,deps,cmd) -> runs cmd if target is outdated.
339
339
340 This is just a wrapper around target_outdated() which calls the given
340 This is just a wrapper around target_outdated() which calls the given
341 command if target is outdated."""
341 command if target is outdated."""
342
342
343 if target_outdated(target,deps):
343 if target_outdated(target,deps):
344 xsys(cmd)
344 xsys(cmd)
345
345
@@ -1,260 +1,272 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, skip_win32
29 from IPython.utils import path
29 from IPython.utils import path
30
30
31 # Platform-dependent imports
31 # Platform-dependent imports
32 try:
32 try:
33 import _winreg as wreg
33 import _winreg as wreg
34 except ImportError:
34 except ImportError:
35 #Fake _winreg module on none windows platforms
35 #Fake _winreg module on none windows platforms
36 import new
36 import new
37 sys.modules["_winreg"] = new.module("_winreg")
37 sys.modules["_winreg"] = new.module("_winreg")
38 import _winreg as wreg
38 import _winreg as wreg
39 #Add entries that needs to be stubbed by the testing code
39 #Add entries that needs to be stubbed by the testing code
40 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
40 (wreg.OpenKey, wreg.QueryValueEx,) = (None, None)
41
41
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43 # Globals
43 # Globals
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 env = os.environ
45 env = os.environ
46 TEST_FILE_PATH = split(abspath(__file__))[0]
46 TEST_FILE_PATH = split(abspath(__file__))[0]
47 TMP_TEST_DIR = tempfile.mkdtemp()
47 TMP_TEST_DIR = tempfile.mkdtemp()
48 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
48 HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir")
49 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
49 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
50 #
50 #
51 # Setup/teardown functions/decorators
51 # Setup/teardown functions/decorators
52 #
52 #
53
53
54 def setup():
54 def setup():
55 """Setup testenvironment for the module:
55 """Setup testenvironment for the module:
56
56
57 - Adds dummy home dir tree
57 - Adds dummy home dir tree
58 """
58 """
59 # Do not mask exceptions here. In particular, catching WindowsError is a
59 # Do not mask exceptions here. In particular, catching WindowsError is a
60 # problem because that exception is only defined on Windows...
60 # problem because that exception is only defined on Windows...
61 os.makedirs(IP_TEST_DIR)
61 os.makedirs(IP_TEST_DIR)
62
62
63
63
64 def teardown():
64 def teardown():
65 """Teardown testenvironment for the module:
65 """Teardown testenvironment for the module:
66
66
67 - Remove dummy home dir tree
67 - Remove dummy home dir tree
68 """
68 """
69 # 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
70 # 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
71 # that non-empty directories are all recursively removed.
71 # that non-empty directories are all recursively removed.
72 shutil.rmtree(TMP_TEST_DIR)
72 shutil.rmtree(TMP_TEST_DIR)
73
73
74
74
75 def setup_environment():
75 def setup_environment():
76 """Setup testenvironment for some functions that are tested
76 """Setup testenvironment for some functions that are tested
77 in this module. In particular this functions stores attributes
77 in this module. In particular this functions stores attributes
78 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.
79 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
80 each testfunction needs a pristine environment.
80 each testfunction needs a pristine environment.
81 """
81 """
82 global oldstuff, platformstuff
82 global oldstuff, platformstuff
83 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
83 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
84
84
85 if os.name == 'nt':
85 if os.name == 'nt':
86 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
86 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
87
87
88
88
89 def teardown_environment():
89 def teardown_environment():
90 """Restore things that were remebered by the setup_environment function
90 """Restore things that were remebered by the setup_environment function
91 """
91 """
92 (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff
92 (oldenv, os.name, get_home_dir, IPython.__file__,) = oldstuff
93
93
94 for key in env.keys():
94 for key in env.keys():
95 if key not in oldenv:
95 if key not in oldenv:
96 del env[key]
96 del env[key]
97 env.update(oldenv)
97 env.update(oldenv)
98 if hasattr(sys, 'frozen'):
98 if hasattr(sys, 'frozen'):
99 del sys.frozen
99 del sys.frozen
100 if os.name == 'nt':
100 if os.name == 'nt':
101 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
101 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
102
102
103 # Build decorator that uses the setup_environment/setup_environment
103 # Build decorator that uses the setup_environment/setup_environment
104 with_environment = with_setup(setup_environment, teardown_environment)
104 with_environment = with_setup(setup_environment, teardown_environment)
105
105
106
106
107 @skip_if_not_win32
107 @skip_if_not_win32
108 @with_environment
108 @with_environment
109 def test_get_home_dir_1():
109 def test_get_home_dir_1():
110 """Testcase for py2exe logic, un-compressed lib
110 """Testcase for py2exe logic, un-compressed lib
111 """
111 """
112 sys.frozen = True
112 sys.frozen = True
113
113
114 #fake filename for IPython.__init__
114 #fake filename for IPython.__init__
115 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
115 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
116
116
117 path.home_dir = get_home_dir()
117 home_dir = path.get_home_dir()
118 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
118 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
119
119
120
120
121 @skip_if_not_win32
121 @skip_if_not_win32
122 @with_environment
122 @with_environment
123 def test_get_home_dir_2():
123 def test_get_home_dir_2():
124 """Testcase for py2exe logic, compressed lib
124 """Testcase for py2exe logic, compressed lib
125 """
125 """
126 sys.frozen = True
126 sys.frozen = True
127 #fake filename for IPython.__init__
127 #fake filename for IPython.__init__
128 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()
129
129
130 home_dir = path.get_home_dir()
130 home_dir = path.get_home_dir()
131 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
131 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
132
132
133
133
134 @with_environment
134 @with_environment
135 @skip_win32
135 def test_get_home_dir_3():
136 def test_get_home_dir_3():
136 """Testcase $HOME is set, then use its value as home directory."""
137 """Testcase $HOME is set, then use its value as home directory."""
137 env["HOME"] = HOME_TEST_DIR
138 env["HOME"] = HOME_TEST_DIR
138 home_dir = path.get_home_dir()
139 home_dir = path.get_home_dir()
139 nt.assert_equal(home_dir, env["HOME"])
140 nt.assert_equal(home_dir, env["HOME"])
140
141
141
142
142 @with_environment
143 @with_environment
143 def test_get_home_dir_4():
144 def test_get_home_dir_4():
144 """Testcase $HOME is not set, os=='posix'.
145 """Testcase $HOME is not set, os=='posix'.
145 This should fail with HomeDirError"""
146 This should fail with HomeDirError"""
146
147
147 os.name = 'posix'
148 os.name = 'posix'
148 if 'HOME' in env: del env['HOME']
149 if 'HOME' in env: del env['HOME']
149 nt.assert_raises(path.HomeDirError, path.get_home_dir)
150 nt.assert_raises(path.HomeDirError, path.get_home_dir)
150
151
151
152
152 @skip_if_not_win32
153 @skip_if_not_win32
153 @with_environment
154 @with_environment
154 def test_get_home_dir_5():
155 def test_get_home_dir_5():
155 """Testcase $HOME is not set, os=='nt'
156 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
156 env['HOMEDRIVE'],env['HOMEPATH'] points to path."""
157
158 HOMESHARE is missing.
159 """
157
160
158 os.name = 'nt'
161 os.name = 'nt'
159 if 'HOME' in env: del env['HOME']
162 env.pop('HOMESHARE', None)
160 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
163 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
161
162 home_dir = path.get_home_dir()
164 home_dir = path.get_home_dir()
163 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
165 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
164
166
165
167
166 @skip_if_not_win32
168 @skip_if_not_win32
167 @with_environment
169 @with_environment
168 def test_get_home_dir_6():
170 def test_get_home_dir_6():
169 """Testcase $HOME is not set, os=='nt'
171 """Using USERPROFILE, os=='nt'.
170 env['HOMEDRIVE'],env['HOMEPATH'] do not point to path.
172
171 env['USERPROFILE'] points to path
173 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
172 """
174 """
173
175
174 os.name = 'nt'
176 os.name = 'nt'
175 if 'HOME' in env: del env['HOME']
177 env.pop('HOMESHARE', None)
176 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.abspath(TEST_FILE_PATH), "DOES NOT EXIST"
178 env.pop('HOMEDRIVE', None)
179 env.pop('HOMEPATH', None)
177 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
180 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
178
179 home_dir = path.get_home_dir()
181 home_dir = path.get_home_dir()
180 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
182 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
181
183
182
184
183 # Should we stub wreg fully so we can run the test on all platforms?
184 @skip_if_not_win32
185 @skip_if_not_win32
185 @with_environment
186 @with_environment
186 def test_get_home_dir_7():
187 def test_get_home_dir_7():
187 """Testcase $HOME is not set, os=='nt'
188 """Using HOMESHARE, os=='nt'."""
189
190 os.name = 'nt'
191 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
192 home_dir = path.get_home_dir()
193 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
194
195 # Should we stub wreg fully so we can run the test on all platforms?
196 @skip_if_not_win32
197 @with_environment
198 def test_get_home_dir_8():
199 """Using registry hack for 'My Documents', os=='nt'
188
200
189 env['HOMEDRIVE'],env['HOMEPATH'], env['USERPROFILE'] and others missing
201 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
190 """
202 """
191 os.name = 'nt'
203 os.name = 'nt'
192 # Remove from stub environment all keys that may be set
204 # Remove from stub environment all keys that may be set
193 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
205 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
194 env.pop(key, None)
206 env.pop(key, None)
195
207
196 #Stub windows registry functions
208 #Stub windows registry functions
197 def OpenKey(x, y):
209 def OpenKey(x, y):
198 class key:
210 class key:
199 def Close(self):
211 def Close(self):
200 pass
212 pass
201 return key()
213 return key()
202 def QueryValueEx(x, y):
214 def QueryValueEx(x, y):
203 return [abspath(HOME_TEST_DIR)]
215 return [abspath(HOME_TEST_DIR)]
204
216
205 wreg.OpenKey = OpenKey
217 wreg.OpenKey = OpenKey
206 wreg.QueryValueEx = QueryValueEx
218 wreg.QueryValueEx = QueryValueEx
207
219
208 home_dir = path.get_home_dir()
220 home_dir = path.get_home_dir()
209 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
221 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
210
222
211
223
212 @with_environment
224 @with_environment
213 def test_get_ipython_dir_1():
225 def test_get_ipython_dir_1():
214 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
226 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
215 env['IPYTHON_DIR'] = "someplace/.ipython"
227 env['IPYTHON_DIR'] = "someplace/.ipython"
216 ipdir = path.get_ipython_dir()
228 ipdir = path.get_ipython_dir()
217 nt.assert_equal(ipdir, "someplace/.ipython")
229 nt.assert_equal(ipdir, "someplace/.ipython")
218
230
219
231
220 @with_environment
232 @with_environment
221 def test_get_ipython_dir_2():
233 def test_get_ipython_dir_2():
222 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
234 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
223 path.get_home_dir = lambda : "someplace"
235 path.get_home_dir = lambda : "someplace"
224 os.name = "posix"
236 os.name = "posix"
225 env.pop('IPYTHON_DIR', None)
237 env.pop('IPYTHON_DIR', None)
226 env.pop('IPYTHONDIR', None)
238 env.pop('IPYTHONDIR', None)
227 ipdir = path.get_ipython_dir()
239 ipdir = path.get_ipython_dir()
228 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
240 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
229
241
230
242
231 def test_filefind():
243 def test_filefind():
232 """Various tests for filefind"""
244 """Various tests for filefind"""
233 f = tempfile.NamedTemporaryFile()
245 f = tempfile.NamedTemporaryFile()
234 # print 'fname:',f.name
246 # print 'fname:',f.name
235 alt_dirs = path.get_ipython_dir()
247 alt_dirs = path.get_ipython_dir()
236 t = path.filefind(f.name, alt_dirs)
248 t = path.filefind(f.name, alt_dirs)
237 # print 'found:',t
249 # print 'found:',t
238
250
239
251
240 def test_get_ipython_package_dir():
252 def test_get_ipython_package_dir():
241 ipdir = path.get_ipython_package_dir()
253 ipdir = path.get_ipython_package_dir()
242 nt.assert_true(os.path.isdir(ipdir))
254 nt.assert_true(os.path.isdir(ipdir))
243
255
244
256
245 def test_get_ipython_module_path():
257 def test_get_ipython_module_path():
246 ipapp_path = path.get_ipython_module_path('IPython.core.ipapp')
258 ipapp_path = path.get_ipython_module_path('IPython.core.ipapp')
247 nt.assert_true(os.path.isfile(ipapp_path))
259 nt.assert_true(os.path.isfile(ipapp_path))
248
260
249
261
250 @dec.skip_if_not_win32
262 @dec.skip_if_not_win32
251 def test_get_long_path_name_win32():
263 def test_get_long_path_name_win32():
252 p = path.get_long_path_name('c:\\docume~1')
264 p = path.get_long_path_name('c:\\docume~1')
253 nt.assert_equals(p,u'c:\\Documents and Settings')
265 nt.assert_equals(p,u'c:\\Documents and Settings')
254
266
255
267
256 @dec.skip_win32
268 @dec.skip_win32
257 def test_get_long_path_name():
269 def test_get_long_path_name():
258 p = path.get_long_path_name('/usr/local')
270 p = path.get_long_path_name('/usr/local')
259 nt.assert_equals(p,'/usr/local')
271 nt.assert_equals(p,'/usr/local')
260
272
General Comments 0
You need to be logged in to leave comments. Login now