##// END OF EJS Templates
fix various tests on Windows...
Min RK -
Show More

The requested changes are too big and content was truncated. Show full diff

1 NO CONTENT: modified file
NO CONTENT: modified file
The requested commit or file is too big and content was truncated. Show full diff
@@ -1,158 +1,183 b''
1 """Tests for the IPython tab-completion machinery.
1 """Tests for the IPython tab-completion machinery.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # stdlib
7 # stdlib
8 import os
8 import os
9 import sys
9 import sys
10 import unittest
10 import unittest
11
11
12 # third party
12 # third party
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 # our own packages
15 # our own packages
16 from IPython.core import completer
16 from IPython.core import completer
17 from IPython.external.decorators import knownfailureif
17 from IPython.utils.tempdir import TemporaryDirectory
18 from IPython.utils.tempdir import TemporaryDirectory
18
19
19 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
20 # Test functions
21 # Test functions
21 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
22 def test_protect_filename():
23 def test_protect_filename():
23 pairs = [ ('abc','abc'),
24 pairs = [ ('abc','abc'),
24 (' abc',r'\ abc'),
25 (' abc',r'\ abc'),
25 ('a bc',r'a\ bc'),
26 ('a bc',r'a\ bc'),
26 ('a bc',r'a\ \ bc'),
27 ('a bc',r'a\ \ bc'),
27 (' bc',r'\ \ bc'),
28 (' bc',r'\ \ bc'),
28 ]
29 ]
29 # On posix, we also protect parens and other special characters
30 # On posix, we also protect parens and other special characters
30 if sys.platform != 'win32':
31 if sys.platform != 'win32':
31 pairs.extend( [('a(bc',r'a\(bc'),
32 pairs.extend( [('a(bc',r'a\(bc'),
32 ('a)bc',r'a\)bc'),
33 ('a)bc',r'a\)bc'),
33 ('a( )bc',r'a\(\ \)bc'),
34 ('a( )bc',r'a\(\ \)bc'),
34 ('a[1]bc', r'a\[1\]bc'),
35 ('a[1]bc', r'a\[1\]bc'),
35 ('a{1}bc', r'a\{1\}bc'),
36 ('a{1}bc', r'a\{1\}bc'),
36 ('a#bc', r'a\#bc'),
37 ('a#bc', r'a\#bc'),
37 ('a?bc', r'a\?bc'),
38 ('a?bc', r'a\?bc'),
38 ('a=bc', r'a\=bc'),
39 ('a=bc', r'a\=bc'),
39 ('a\\bc', r'a\\bc'),
40 ('a\\bc', r'a\\bc'),
40 ('a|bc', r'a\|bc'),
41 ('a|bc', r'a\|bc'),
41 ('a;bc', r'a\;bc'),
42 ('a;bc', r'a\;bc'),
42 ('a:bc', r'a\:bc'),
43 ('a:bc', r'a\:bc'),
43 ("a'bc", r"a\'bc"),
44 ("a'bc", r"a\'bc"),
44 ('a*bc', r'a\*bc'),
45 ('a*bc', r'a\*bc'),
45 ('a"bc', r'a\"bc'),
46 ('a"bc', r'a\"bc'),
46 ('a^bc', r'a\^bc'),
47 ('a^bc', r'a\^bc'),
47 ('a&bc', r'a\&bc'),
48 ('a&bc', r'a\&bc'),
48 ] )
49 ] )
49 # run the actual tests
50 # run the actual tests
50 for s1, s2 in pairs:
51 for s1, s2 in pairs:
51 s1p = completer.protect_filename(s1)
52 s1p = completer.protect_filename(s1)
52 nt.assert_equals(s1p, s2)
53 nt.assert_equals(s1p, s2)
53
54
54
55
55 def check_line_split(splitter, test_specs):
56 def check_line_split(splitter, test_specs):
56 for part1, part2, split in test_specs:
57 for part1, part2, split in test_specs:
57 cursor_pos = len(part1)
58 cursor_pos = len(part1)
58 line = part1+part2
59 line = part1+part2
59 out = splitter.split_line(line, cursor_pos)
60 out = splitter.split_line(line, cursor_pos)
60 nt.assert_equal(out, split)
61 nt.assert_equal(out, split)
61
62
62
63
63 def test_line_split():
64 def test_line_split():
64 """Basice line splitter test with default specs."""
65 """Basice line splitter test with default specs."""
65 sp = completer.CompletionSplitter()
66 sp = completer.CompletionSplitter()
66 # The format of the test specs is: part1, part2, expected answer. Parts 1
67 # The format of the test specs is: part1, part2, expected answer. Parts 1
67 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
68 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
68 # was at the end of part1. So an empty part2 represents someone hitting
69 # was at the end of part1. So an empty part2 represents someone hitting
69 # tab at the end of the line, the most common case.
70 # tab at the end of the line, the most common case.
70 t = [('run some/scrip', '', 'some/scrip'),
71 t = [('run some/scrip', '', 'some/scrip'),
71 ('run scripts/er', 'ror.py foo', 'scripts/er'),
72 ('run scripts/er', 'ror.py foo', 'scripts/er'),
72 ('echo $HOM', '', 'HOM'),
73 ('echo $HOM', '', 'HOM'),
73 ('print sys.pa', '', 'sys.pa'),
74 ('print sys.pa', '', 'sys.pa'),
74 ('print(sys.pa', '', 'sys.pa'),
75 ('print(sys.pa', '', 'sys.pa'),
75 ("execfile('scripts/er", '', 'scripts/er'),
76 ("execfile('scripts/er", '', 'scripts/er'),
76 ('a[x.', '', 'x.'),
77 ('a[x.', '', 'x.'),
77 ('a[x.', 'y', 'x.'),
78 ('a[x.', 'y', 'x.'),
78 ('cd "some_file/', '', 'some_file/'),
79 ('cd "some_file/', '', 'some_file/'),
79 ]
80 ]
80 check_line_split(sp, t)
81 check_line_split(sp, t)
81 # Ensure splitting works OK with unicode by re-running the tests with
82 # Ensure splitting works OK with unicode by re-running the tests with
82 # all inputs turned into unicode
83 # all inputs turned into unicode
83 check_line_split(sp, [ map(unicode, p) for p in t] )
84 check_line_split(sp, [ map(unicode, p) for p in t] )
84
85
85
86
86 def test_unicode_completions():
87 def test_unicode_completions():
87 ip = get_ipython()
88 ip = get_ipython()
88 # Some strings that trigger different types of completion. Check them both
89 # Some strings that trigger different types of completion. Check them both
89 # in str and unicode forms
90 # in str and unicode forms
90 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
91 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
91 for t in s + map(unicode, s):
92 for t in s + map(unicode, s):
92 # We don't need to check exact completion values (they may change
93 # We don't need to check exact completion values (they may change
93 # depending on the state of the namespace, but at least no exceptions
94 # depending on the state of the namespace, but at least no exceptions
94 # should be thrown and the return value should be a pair of text, list
95 # should be thrown and the return value should be a pair of text, list
95 # values.
96 # values.
96 text, matches = ip.complete(t)
97 text, matches = ip.complete(t)
97 nt.assert_true(isinstance(text, basestring))
98 nt.assert_true(isinstance(text, basestring))
98 nt.assert_true(isinstance(matches, list))
99 nt.assert_true(isinstance(matches, list))
99
100
100
101
101 class CompletionSplitterTestCase(unittest.TestCase):
102 class CompletionSplitterTestCase(unittest.TestCase):
102 def setUp(self):
103 def setUp(self):
103 self.sp = completer.CompletionSplitter()
104 self.sp = completer.CompletionSplitter()
104
105
105 def test_delim_setting(self):
106 def test_delim_setting(self):
106 self.sp.set_delims(' ')
107 self.sp.set_delims(' ')
107 nt.assert_equal(self.sp.get_delims(), ' ')
108 nt.assert_equal(self.sp.get_delims(), ' ')
108 nt.assert_equal(self.sp._delim_expr, '[\ ]')
109 nt.assert_equal(self.sp._delim_expr, '[\ ]')
109
110
110 def test_spaces(self):
111 def test_spaces(self):
111 """Test with only spaces as split chars."""
112 """Test with only spaces as split chars."""
112 self.sp.delims = ' '
113 self.sp.delims = ' '
113 t = [('foo', '', 'foo'),
114 t = [('foo', '', 'foo'),
114 ('run foo', '', 'foo'),
115 ('run foo', '', 'foo'),
115 ('run foo', 'bar', 'foo'),
116 ('run foo', 'bar', 'foo'),
116 ]
117 ]
117 check_line_split(self.sp, t)
118 check_line_split(self.sp, t)
118
119
119
120
120 def test_has_open_quotes1():
121 def test_has_open_quotes1():
121 for s in ["'", "'''", "'hi' '"]:
122 for s in ["'", "'''", "'hi' '"]:
122 nt.assert_equal(completer.has_open_quotes(s), "'")
123 nt.assert_equal(completer.has_open_quotes(s), "'")
123
124
124
125
125 def test_has_open_quotes2():
126 def test_has_open_quotes2():
126 for s in ['"', '"""', '"hi" "']:
127 for s in ['"', '"""', '"hi" "']:
127 nt.assert_equal(completer.has_open_quotes(s), '"')
128 nt.assert_equal(completer.has_open_quotes(s), '"')
128
129
129
130
130 def test_has_open_quotes3():
131 def test_has_open_quotes3():
131 for s in ["''", "''' '''", "'hi' 'ipython'"]:
132 for s in ["''", "''' '''", "'hi' 'ipython'"]:
132 nt.assert_false(completer.has_open_quotes(s))
133 nt.assert_false(completer.has_open_quotes(s))
133
134
134
135
135 def test_has_open_quotes4():
136 def test_has_open_quotes4():
136 for s in ['""', '""" """', '"hi" "ipython"']:
137 for s in ['""', '""" """', '"hi" "ipython"']:
137 nt.assert_false(completer.has_open_quotes(s))
138 nt.assert_false(completer.has_open_quotes(s))
138
139
139
140 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
140 def test_file_completions():
141 def test_abspath_file_completions():
141
142 ip = get_ipython()
142 ip = get_ipython()
143 with TemporaryDirectory() as tmpdir:
143 with TemporaryDirectory() as tmpdir:
144 prefix = os.path.join(tmpdir, 'foo')
144 prefix = os.path.join(tmpdir, 'foo')
145 suffixes = map(str, [1,2])
145 suffixes = map(str, [1,2])
146 names = [prefix+s for s in suffixes]
146 names = [prefix+s for s in suffixes]
147 for n in names:
147 for n in names:
148 open(n, 'w').close()
148 open(n, 'w').close()
149
149
150 # Check simple completion
150 # Check simple completion
151 c = ip.complete(prefix)[1]
151 c = ip.complete(prefix)[1]
152 nt.assert_equal(c, names)
152 nt.assert_equal(c, names)
153
153
154 # Now check with a function call
154 # Now check with a function call
155 cmd = 'a = f("%s' % prefix
155 cmd = 'a = f("%s' % prefix
156 c = ip.complete(prefix, cmd)[1]
156 c = ip.complete(prefix, cmd)[1]
157 comp = [prefix+s for s in suffixes]
157 comp = [prefix+s for s in suffixes]
158 nt.assert_equal(c, comp)
158 nt.assert_equal(c, comp)
159
160 def test_local_file_completions():
161 ip = get_ipython()
162 cwd = os.getcwdu()
163 try:
164 with TemporaryDirectory() as tmpdir:
165 os.chdir(tmpdir)
166 prefix = './foo'
167 suffixes = map(str, [1,2])
168 names = [prefix+s for s in suffixes]
169 for n in names:
170 open(n, 'w').close()
171
172 # Check simple completion
173 c = ip.complete(prefix)[1]
174 nt.assert_equal(c, names)
175
176 # Now check with a function call
177 cmd = 'a = f("%s' % prefix
178 c = ip.complete(prefix, cmd)[1]
179 comp = [prefix+s for s in suffixes]
180 nt.assert_equal(c, comp)
181 finally:
182 # prevent failures from making chdir stick
183 os.chdir(cwd)
@@ -1,462 +1,462 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12 import sys
12 import sys
13 import tempfile
13 import tempfile
14 import types
14 import types
15 from cStringIO import StringIO
15 from cStringIO import StringIO
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.utils.path import get_long_path_name
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Test functions begin
24 # Test functions begin
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 def test_rehashx():
26 def test_rehashx():
27 # clear up everything
27 # clear up everything
28 _ip = get_ipython()
28 _ip = get_ipython()
29 _ip.alias_manager.alias_table.clear()
29 _ip.alias_manager.alias_table.clear()
30 del _ip.db['syscmdlist']
30 del _ip.db['syscmdlist']
31
31
32 _ip.magic('rehashx')
32 _ip.magic('rehashx')
33 # Practically ALL ipython development systems will have more than 10 aliases
33 # Practically ALL ipython development systems will have more than 10 aliases
34
34
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
36 for key, val in _ip.alias_manager.alias_table.iteritems():
36 for key, val in _ip.alias_manager.alias_table.iteritems():
37 # we must strip dots from alias names
37 # we must strip dots from alias names
38 nt.assert_true('.' not in key)
38 nt.assert_true('.' not in key)
39
39
40 # rehashx must fill up syscmdlist
40 # rehashx must fill up syscmdlist
41 scoms = _ip.db['syscmdlist']
41 scoms = _ip.db['syscmdlist']
42 yield (nt.assert_true, len(scoms) > 10)
42 yield (nt.assert_true, len(scoms) > 10)
43
43
44
44
45 def test_magic_parse_options():
45 def test_magic_parse_options():
46 """Test that we don't mangle paths when parsing magic options."""
46 """Test that we don't mangle paths when parsing magic options."""
47 ip = get_ipython()
47 ip = get_ipython()
48 path = 'c:\\x'
48 path = 'c:\\x'
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
50 # argv splitting is os-dependent
50 # argv splitting is os-dependent
51 if os.name == 'posix':
51 if os.name == 'posix':
52 expected = 'c:x'
52 expected = 'c:x'
53 else:
53 else:
54 expected = path
54 expected = path
55 nt.assert_equals(opts['f'], expected)
55 nt.assert_equals(opts['f'], expected)
56
56
57
57
58 def doctest_hist_f():
58 def doctest_hist_f():
59 """Test %hist -f with temporary filename.
59 """Test %hist -f with temporary filename.
60
60
61 In [9]: import tempfile
61 In [9]: import tempfile
62
62
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64
64
65 In [11]: %hist -nl -f $tfile 3
65 In [11]: %hist -nl -f $tfile 3
66
66
67 In [13]: import os; os.unlink(tfile)
67 In [13]: import os; os.unlink(tfile)
68 """
68 """
69
69
70
70
71 def doctest_hist_r():
71 def doctest_hist_r():
72 """Test %hist -r
72 """Test %hist -r
73
73
74 XXX - This test is not recording the output correctly. For some reason, in
74 XXX - This test is not recording the output correctly. For some reason, in
75 testing mode the raw history isn't getting populated. No idea why.
75 testing mode the raw history isn't getting populated. No idea why.
76 Disabling the output checking for now, though at least we do run it.
76 Disabling the output checking for now, though at least we do run it.
77
77
78 In [1]: 'hist' in _ip.lsmagic()
78 In [1]: 'hist' in _ip.lsmagic()
79 Out[1]: True
79 Out[1]: True
80
80
81 In [2]: x=1
81 In [2]: x=1
82
82
83 In [3]: %hist -rl 2
83 In [3]: %hist -rl 2
84 x=1 # random
84 x=1 # random
85 %hist -r 2
85 %hist -r 2
86 """
86 """
87
87
88 def doctest_hist_op():
88 def doctest_hist_op():
89 """Test %hist -op
89 """Test %hist -op
90
90
91 In [1]: class b:
91 In [1]: class b:
92 ...: pass
92 ...: pass
93 ...:
93 ...:
94
94
95 In [2]: class s(b):
95 In [2]: class s(b):
96 ...: def __str__(self):
96 ...: def __str__(self):
97 ...: return 's'
97 ...: return 's'
98 ...:
98 ...:
99
99
100 In [3]:
100 In [3]:
101
101
102 In [4]: class r(b):
102 In [4]: class r(b):
103 ...: def __repr__(self):
103 ...: def __repr__(self):
104 ...: return 'r'
104 ...: return 'r'
105 ...:
105 ...:
106
106
107 In [5]: class sr(s,r): pass
107 In [5]: class sr(s,r): pass
108 ...:
108 ...:
109
109
110 In [6]:
110 In [6]:
111
111
112 In [7]: bb=b()
112 In [7]: bb=b()
113
113
114 In [8]: ss=s()
114 In [8]: ss=s()
115
115
116 In [9]: rr=r()
116 In [9]: rr=r()
117
117
118 In [10]: ssrr=sr()
118 In [10]: ssrr=sr()
119
119
120 In [11]: bb
120 In [11]: bb
121 Out[11]: <...b instance at ...>
121 Out[11]: <...b instance at ...>
122
122
123 In [12]: ss
123 In [12]: ss
124 Out[12]: <...s instance at ...>
124 Out[12]: <...s instance at ...>
125
125
126 In [13]:
126 In [13]:
127
127
128 In [14]: %hist -op
128 In [14]: %hist -op
129 >>> class b:
129 >>> class b:
130 ... pass
130 ... pass
131 ...
131 ...
132 >>> class s(b):
132 >>> class s(b):
133 ... def __str__(self):
133 ... def __str__(self):
134 ... return 's'
134 ... return 's'
135 ...
135 ...
136 >>>
136 >>>
137 >>> class r(b):
137 >>> class r(b):
138 ... def __repr__(self):
138 ... def __repr__(self):
139 ... return 'r'
139 ... return 'r'
140 ...
140 ...
141 >>> class sr(s,r): pass
141 >>> class sr(s,r): pass
142 >>>
142 >>>
143 >>> bb=b()
143 >>> bb=b()
144 >>> ss=s()
144 >>> ss=s()
145 >>> rr=r()
145 >>> rr=r()
146 >>> ssrr=sr()
146 >>> ssrr=sr()
147 >>> bb
147 >>> bb
148 <...b instance at ...>
148 <...b instance at ...>
149 >>> ss
149 >>> ss
150 <...s instance at ...>
150 <...s instance at ...>
151 >>>
151 >>>
152 """
152 """
153
153
154 def test_macro():
154 def test_macro():
155 ip = get_ipython()
155 ip = get_ipython()
156 ip.history_manager.reset() # Clear any existing history.
156 ip.history_manager.reset() # Clear any existing history.
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
158 for i, cmd in enumerate(cmds, start=1):
158 for i, cmd in enumerate(cmds, start=1):
159 ip.history_manager.store_inputs(i, cmd)
159 ip.history_manager.store_inputs(i, cmd)
160 ip.magic("macro test 1-3")
160 ip.magic("macro test 1-3")
161 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
161 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
162
162
163 # List macros.
163 # List macros.
164 assert "test" in ip.magic("macro")
164 assert "test" in ip.magic("macro")
165
165
166 def test_macro_run():
166 def test_macro_run():
167 """Test that we can run a multi-line macro successfully."""
167 """Test that we can run a multi-line macro successfully."""
168 ip = get_ipython()
168 ip = get_ipython()
169 ip.history_manager.reset()
169 ip.history_manager.reset()
170 cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"]
170 cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"]
171 for cmd in cmds:
171 for cmd in cmds:
172 ip.run_cell(cmd)
172 ip.run_cell(cmd)
173 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n")
173 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n")
174 original_stdout = sys.stdout
174 original_stdout = sys.stdout
175 new_stdout = StringIO()
175 new_stdout = StringIO()
176 sys.stdout = new_stdout
176 sys.stdout = new_stdout
177 try:
177 try:
178 ip.run_cell("test")
178 ip.run_cell("test")
179 nt.assert_true("12" in new_stdout.getvalue())
179 nt.assert_true("12" in new_stdout.getvalue())
180 ip.run_cell("test")
180 ip.run_cell("test")
181 nt.assert_true("13" in new_stdout.getvalue())
181 nt.assert_true("13" in new_stdout.getvalue())
182 finally:
182 finally:
183 sys.stdout = original_stdout
183 sys.stdout = original_stdout
184 new_stdout.close()
184 new_stdout.close()
185
185
186
186
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
188 # fix this and revert the skip to happen only if numpy is not around.
188 # fix this and revert the skip to happen only if numpy is not around.
189 #@dec.skipif_not_numpy
189 #@dec.skipif_not_numpy
190 @dec.skip_known_failure
190 @dec.skip_known_failure
191 def test_numpy_clear_array_undec():
191 def test_numpy_clear_array_undec():
192 from IPython.extensions import clearcmd
192 from IPython.extensions import clearcmd
193
193
194 _ip.ex('import numpy as np')
194 _ip.ex('import numpy as np')
195 _ip.ex('a = np.empty(2)')
195 _ip.ex('a = np.empty(2)')
196 yield (nt.assert_true, 'a' in _ip.user_ns)
196 yield (nt.assert_true, 'a' in _ip.user_ns)
197 _ip.magic('clear array')
197 _ip.magic('clear array')
198 yield (nt.assert_false, 'a' in _ip.user_ns)
198 yield (nt.assert_false, 'a' in _ip.user_ns)
199
199
200
200
201 # Multiple tests for clipboard pasting
201 # Multiple tests for clipboard pasting
202 @dec.parametric
202 @dec.parametric
203 def test_paste():
203 def test_paste():
204 _ip = get_ipython()
204 _ip = get_ipython()
205 def paste(txt, flags='-q'):
205 def paste(txt, flags='-q'):
206 """Paste input text, by default in quiet mode"""
206 """Paste input text, by default in quiet mode"""
207 hooks.clipboard_get = lambda : txt
207 hooks.clipboard_get = lambda : txt
208 _ip.magic('paste '+flags)
208 _ip.magic('paste '+flags)
209
209
210 # Inject fake clipboard hook but save original so we can restore it later
210 # Inject fake clipboard hook but save original so we can restore it later
211 hooks = _ip.hooks
211 hooks = _ip.hooks
212 user_ns = _ip.user_ns
212 user_ns = _ip.user_ns
213 original_clip = hooks.clipboard_get
213 original_clip = hooks.clipboard_get
214
214
215 try:
215 try:
216 # This try/except with an emtpy except clause is here only because
216 # This try/except with an emtpy except clause is here only because
217 # try/yield/finally is invalid syntax in Python 2.4. This will be
217 # try/yield/finally is invalid syntax in Python 2.4. This will be
218 # removed when we drop 2.4-compatibility, and the emtpy except below
218 # removed when we drop 2.4-compatibility, and the emtpy except below
219 # will be changed to a finally.
219 # will be changed to a finally.
220
220
221 # Run tests with fake clipboard function
221 # Run tests with fake clipboard function
222 user_ns.pop('x', None)
222 user_ns.pop('x', None)
223 paste('x=1')
223 paste('x=1')
224 yield nt.assert_equal(user_ns['x'], 1)
224 yield nt.assert_equal(user_ns['x'], 1)
225
225
226 user_ns.pop('x', None)
226 user_ns.pop('x', None)
227 paste('>>> x=2')
227 paste('>>> x=2')
228 yield nt.assert_equal(user_ns['x'], 2)
228 yield nt.assert_equal(user_ns['x'], 2)
229
229
230 paste("""
230 paste("""
231 >>> x = [1,2,3]
231 >>> x = [1,2,3]
232 >>> y = []
232 >>> y = []
233 >>> for i in x:
233 >>> for i in x:
234 ... y.append(i**2)
234 ... y.append(i**2)
235 ...
235 ...
236 """)
236 """)
237 yield nt.assert_equal(user_ns['x'], [1,2,3])
237 yield nt.assert_equal(user_ns['x'], [1,2,3])
238 yield nt.assert_equal(user_ns['y'], [1,4,9])
238 yield nt.assert_equal(user_ns['y'], [1,4,9])
239
239
240 # Now, test that paste -r works
240 # Now, test that paste -r works
241 user_ns.pop('x', None)
241 user_ns.pop('x', None)
242 yield nt.assert_false('x' in user_ns)
242 yield nt.assert_false('x' in user_ns)
243 _ip.magic('paste -r')
243 _ip.magic('paste -r')
244 yield nt.assert_equal(user_ns['x'], [1,2,3])
244 yield nt.assert_equal(user_ns['x'], [1,2,3])
245
245
246 # Also test paste echoing, by temporarily faking the writer
246 # Also test paste echoing, by temporarily faking the writer
247 w = StringIO()
247 w = StringIO()
248 writer = _ip.write
248 writer = _ip.write
249 _ip.write = w.write
249 _ip.write = w.write
250 code = """
250 code = """
251 a = 100
251 a = 100
252 b = 200"""
252 b = 200"""
253 try:
253 try:
254 paste(code,'')
254 paste(code,'')
255 out = w.getvalue()
255 out = w.getvalue()
256 finally:
256 finally:
257 _ip.write = writer
257 _ip.write = writer
258 yield nt.assert_equal(user_ns['a'], 100)
258 yield nt.assert_equal(user_ns['a'], 100)
259 yield nt.assert_equal(user_ns['b'], 200)
259 yield nt.assert_equal(user_ns['b'], 200)
260 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
260 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
261
261
262 finally:
262 finally:
263 # This should be in a finally clause, instead of the bare except above.
263 # This should be in a finally clause, instead of the bare except above.
264 # Restore original hook
264 # Restore original hook
265 hooks.clipboard_get = original_clip
265 hooks.clipboard_get = original_clip
266
266
267
267
268 def test_time():
268 def test_time():
269 _ip.magic('time None')
269 _ip.magic('time None')
270
270
271
271
272 def doctest_time():
272 def doctest_time():
273 """
273 """
274 In [10]: %time None
274 In [10]: %time None
275 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
276 Wall time: 0.00 s
276 Wall time: 0.00 s
277
277
278 In [11]: def f(kmjy):
278 In [11]: def f(kmjy):
279 ....: %time print 2*kmjy
279 ....: %time print 2*kmjy
280
280
281 In [12]: f(3)
281 In [12]: f(3)
282 6
282 6
283 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
283 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
284 Wall time: 0.00 s
284 Wall time: 0.00 s
285 """
285 """
286
286
287
287
288 def test_doctest_mode():
288 def test_doctest_mode():
289 "Toggle doctest_mode twice, it should be a no-op and run without error"
289 "Toggle doctest_mode twice, it should be a no-op and run without error"
290 _ip.magic('doctest_mode')
290 _ip.magic('doctest_mode')
291 _ip.magic('doctest_mode')
291 _ip.magic('doctest_mode')
292
292
293
293
294 def test_parse_options():
294 def test_parse_options():
295 """Tests for basic options parsing in magics."""
295 """Tests for basic options parsing in magics."""
296 # These are only the most minimal of tests, more should be added later. At
296 # These are only the most minimal of tests, more should be added later. At
297 # the very least we check that basic text/unicode calls work OK.
297 # the very least we check that basic text/unicode calls work OK.
298 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
298 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
299 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
299 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
300
300
301
301
302 def test_dirops():
302 def test_dirops():
303 """Test various directory handling operations."""
303 """Test various directory handling operations."""
304 curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
304 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
305
305 curpath = os.getcwdu
306 startdir = os.getcwdu()
306 startdir = os.getcwdu()
307 ipdir = _ip.ipython_dir
307 ipdir = _ip.ipython_dir
308 try:
308 try:
309 _ip.magic('cd "%s"' % ipdir)
309 _ip.magic('cd "%s"' % ipdir)
310 nt.assert_equal(curpath(), ipdir)
310 nt.assert_equal(curpath(), ipdir)
311 _ip.magic('cd -')
311 _ip.magic('cd -')
312 nt.assert_equal(curpath(), startdir)
312 nt.assert_equal(curpath(), startdir)
313 _ip.magic('pushd "%s"' % ipdir)
313 _ip.magic('pushd "%s"' % ipdir)
314 nt.assert_equal(curpath(), ipdir)
314 nt.assert_equal(curpath(), ipdir)
315 _ip.magic('popd')
315 _ip.magic('popd')
316 nt.assert_equal(curpath(), startdir)
316 nt.assert_equal(curpath(), startdir)
317 finally:
317 finally:
318 os.chdir(startdir)
318 os.chdir(startdir)
319
319
320
320
321 def check_cpaste(code, should_fail=False):
321 def check_cpaste(code, should_fail=False):
322 """Execute code via 'cpaste' and ensure it was executed, unless
322 """Execute code via 'cpaste' and ensure it was executed, unless
323 should_fail is set.
323 should_fail is set.
324 """
324 """
325 _ip.user_ns['code_ran'] = False
325 _ip.user_ns['code_ran'] = False
326
326
327 src = StringIO()
327 src = StringIO()
328 src.write('\n')
328 src.write('\n')
329 src.write(code)
329 src.write(code)
330 src.write('\n--\n')
330 src.write('\n--\n')
331 src.seek(0)
331 src.seek(0)
332
332
333 stdin_save = sys.stdin
333 stdin_save = sys.stdin
334 sys.stdin = src
334 sys.stdin = src
335
335
336 try:
336 try:
337 _ip.magic('cpaste')
337 _ip.magic('cpaste')
338 except:
338 except:
339 if not should_fail:
339 if not should_fail:
340 raise AssertionError("Failure not expected : '%s'" %
340 raise AssertionError("Failure not expected : '%s'" %
341 code)
341 code)
342 else:
342 else:
343 assert _ip.user_ns['code_ran']
343 assert _ip.user_ns['code_ran']
344 if should_fail:
344 if should_fail:
345 raise AssertionError("Failure expected : '%s'" % code)
345 raise AssertionError("Failure expected : '%s'" % code)
346 finally:
346 finally:
347 sys.stdin = stdin_save
347 sys.stdin = stdin_save
348
348
349
349
350 def test_cpaste():
350 def test_cpaste():
351 """Test cpaste magic"""
351 """Test cpaste magic"""
352
352
353 def run():
353 def run():
354 """Marker function: sets a flag when executed.
354 """Marker function: sets a flag when executed.
355 """
355 """
356 _ip.user_ns['code_ran'] = True
356 _ip.user_ns['code_ran'] = True
357 return 'run' # return string so '+ run()' doesn't result in success
357 return 'run' # return string so '+ run()' doesn't result in success
358
358
359 tests = {'pass': ["> > > run()",
359 tests = {'pass': ["> > > run()",
360 ">>> > run()",
360 ">>> > run()",
361 "+++ run()",
361 "+++ run()",
362 "++ run()",
362 "++ run()",
363 " >>> run()"],
363 " >>> run()"],
364
364
365 'fail': ["+ + run()",
365 'fail': ["+ + run()",
366 " ++ run()"]}
366 " ++ run()"]}
367
367
368 _ip.user_ns['run'] = run
368 _ip.user_ns['run'] = run
369
369
370 for code in tests['pass']:
370 for code in tests['pass']:
371 check_cpaste(code)
371 check_cpaste(code)
372
372
373 for code in tests['fail']:
373 for code in tests['fail']:
374 check_cpaste(code, should_fail=True)
374 check_cpaste(code, should_fail=True)
375
375
376 def test_xmode():
376 def test_xmode():
377 # Calling xmode three times should be a no-op
377 # Calling xmode three times should be a no-op
378 xmode = _ip.InteractiveTB.mode
378 xmode = _ip.InteractiveTB.mode
379 for i in range(3):
379 for i in range(3):
380 _ip.magic("xmode")
380 _ip.magic("xmode")
381 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
381 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
382
382
383 def test_reset_hard():
383 def test_reset_hard():
384 monitor = []
384 monitor = []
385 class A(object):
385 class A(object):
386 def __del__(self):
386 def __del__(self):
387 monitor.append(1)
387 monitor.append(1)
388 def __repr__(self):
388 def __repr__(self):
389 return "<A instance>"
389 return "<A instance>"
390
390
391 _ip.user_ns["a"] = A()
391 _ip.user_ns["a"] = A()
392 _ip.run_cell("a")
392 _ip.run_cell("a")
393
393
394 nt.assert_equal(monitor, [])
394 nt.assert_equal(monitor, [])
395 _ip.magic_reset("-f")
395 _ip.magic_reset("-f")
396 nt.assert_equal(monitor, [1])
396 nt.assert_equal(monitor, [1])
397
397
398 class TestXdel(tt.TempFileMixin):
398 class TestXdel(tt.TempFileMixin):
399 def test_xdel(self):
399 def test_xdel(self):
400 """Test that references from %run are cleared by xdel."""
400 """Test that references from %run are cleared by xdel."""
401 src = ("class A(object):\n"
401 src = ("class A(object):\n"
402 " monitor = []\n"
402 " monitor = []\n"
403 " def __del__(self):\n"
403 " def __del__(self):\n"
404 " self.monitor.append(1)\n"
404 " self.monitor.append(1)\n"
405 "a = A()\n")
405 "a = A()\n")
406 self.mktmp(src)
406 self.mktmp(src)
407 # %run creates some hidden references...
407 # %run creates some hidden references...
408 _ip.magic("run %s" % self.fname)
408 _ip.magic("run %s" % self.fname)
409 # ... as does the displayhook.
409 # ... as does the displayhook.
410 _ip.run_cell("a")
410 _ip.run_cell("a")
411
411
412 monitor = _ip.user_ns["A"].monitor
412 monitor = _ip.user_ns["A"].monitor
413 nt.assert_equal(monitor, [])
413 nt.assert_equal(monitor, [])
414
414
415 _ip.magic("xdel a")
415 _ip.magic("xdel a")
416
416
417 # Check that a's __del__ method has been called.
417 # Check that a's __del__ method has been called.
418 nt.assert_equal(monitor, [1])
418 nt.assert_equal(monitor, [1])
419
419
420 def doctest_who():
420 def doctest_who():
421 """doctest for %who
421 """doctest for %who
422
422
423 In [1]: %reset -f
423 In [1]: %reset -f
424
424
425 In [2]: alpha = 123
425 In [2]: alpha = 123
426
426
427 In [3]: beta = 'beta'
427 In [3]: beta = 'beta'
428
428
429 In [4]: %who int
429 In [4]: %who int
430 alpha
430 alpha
431
431
432 In [5]: %who str
432 In [5]: %who str
433 beta
433 beta
434
434
435 In [6]: %whos
435 In [6]: %whos
436 Variable Type Data/Info
436 Variable Type Data/Info
437 ----------------------------
437 ----------------------------
438 alpha int 123
438 alpha int 123
439 beta str beta
439 beta str beta
440
440
441 In [7]: %who_ls
441 In [7]: %who_ls
442 Out[7]: ['alpha', 'beta']
442 Out[7]: ['alpha', 'beta']
443 """
443 """
444
444
445 def doctest_precision():
445 def doctest_precision():
446 """doctest for %precision
446 """doctest for %precision
447
447
448 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
448 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
449
449
450 In [2]: %precision 5
450 In [2]: %precision 5
451 Out[2]: u'%.5f'
451 Out[2]: u'%.5f'
452
452
453 In [3]: f.float_format
453 In [3]: f.float_format
454 Out[3]: u'%.5f'
454 Out[3]: u'%.5f'
455
455
456 In [4]: %precision %e
456 In [4]: %precision %e
457 Out[4]: u'%e'
457 Out[4]: u'%e'
458
458
459 In [5]: f(3.1415927)
459 In [5]: f(3.1415927)
460 Out[5]: u'3.141593e+00'
460 Out[5]: u'3.141593e+00'
461 """
461 """
462
462
@@ -1,131 +1,133 b''
1 """Tests for the object inspection functionality.
1 """Tests for the object inspection functionality.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (C) 2010 The IPython Development Team.
4 # Copyright (C) 2010 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the BSD License.
6 # Distributed under the terms of the BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 from __future__ import print_function
14 from __future__ import print_function
15
15
16 # Stdlib imports
16 # Stdlib imports
17
17
18 # Third-party imports
18 # Third-party imports
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 # Our own imports
21 # Our own imports
22 from .. import oinspect
22 from .. import oinspect
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Globals and constants
25 # Globals and constants
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 inspector = oinspect.Inspector()
28 inspector = oinspect.Inspector()
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Local utilities
31 # Local utilities
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33
33
34 # A few generic objects we can then inspect in the tests below
34 # A few generic objects we can then inspect in the tests below
35
35
36 class Call(object):
36 class Call(object):
37 """This is the class docstring."""
37 """This is the class docstring."""
38
38
39 def __init__(self, x, y=1):
39 def __init__(self, x, y=1):
40 """This is the constructor docstring."""
40 """This is the constructor docstring."""
41
41
42 def __call__(self, *a, **kw):
42 def __call__(self, *a, **kw):
43 """This is the call docstring."""
43 """This is the call docstring."""
44
44
45 def method(self, x, z=2):
45 def method(self, x, z=2):
46 """Some method's docstring"""
46 """Some method's docstring"""
47
47
48 class OldStyle:
48 class OldStyle:
49 """An old-style class for testing."""
49 """An old-style class for testing."""
50 pass
50 pass
51
51
52 def f(x, y=2, *a, **kw):
52 def f(x, y=2, *a, **kw):
53 """A simple function."""
53 """A simple function."""
54
54
55 def g(y, z=3, *a, **kw):
55 def g(y, z=3, *a, **kw):
56 pass # no docstring
56 pass # no docstring
57
57
58
58
59 def check_calltip(obj, name, call, docstring):
59 def check_calltip(obj, name, call, docstring):
60 """Generic check pattern all calltip tests will use"""
60 """Generic check pattern all calltip tests will use"""
61 info = inspector.info(obj, name)
61 info = inspector.info(obj, name)
62 call_line, ds = oinspect.call_tip(info)
62 call_line, ds = oinspect.call_tip(info)
63 nt.assert_equal(call_line, call)
63 nt.assert_equal(call_line, call)
64 nt.assert_equal(ds, docstring)
64 nt.assert_equal(ds, docstring)
65
65
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67 # Tests
67 # Tests
68 #-----------------------------------------------------------------------------
68 #-----------------------------------------------------------------------------
69
69
70 def test_calltip_class():
70 def test_calltip_class():
71 check_calltip(Call, 'Call', 'Call(x, y=1)', Call.__init__.__doc__)
71 check_calltip(Call, 'Call', 'Call(x, y=1)', Call.__init__.__doc__)
72
72
73
73
74 def test_calltip_instance():
74 def test_calltip_instance():
75 c = Call(1)
75 c = Call(1)
76 check_calltip(c, 'c', 'c(*a, **kw)', c.__call__.__doc__)
76 check_calltip(c, 'c', 'c(*a, **kw)', c.__call__.__doc__)
77
77
78
78
79 def test_calltip_method():
79 def test_calltip_method():
80 c = Call(1)
80 c = Call(1)
81 check_calltip(c.method, 'c.method', 'c.method(x, z=2)', c.method.__doc__)
81 check_calltip(c.method, 'c.method', 'c.method(x, z=2)', c.method.__doc__)
82
82
83
83
84 def test_calltip_function():
84 def test_calltip_function():
85 check_calltip(f, 'f', 'f(x, y=2, *a, **kw)', f.__doc__)
85 check_calltip(f, 'f', 'f(x, y=2, *a, **kw)', f.__doc__)
86
86
87
87
88 def test_calltip_function2():
88 def test_calltip_function2():
89 check_calltip(g, 'g', 'g(y, z=3, *a, **kw)', '<no docstring>')
89 check_calltip(g, 'g', 'g(y, z=3, *a, **kw)', '<no docstring>')
90
90
91
91
92 def test_calltip_builtin():
92 def test_calltip_builtin():
93 check_calltip(sum, 'sum', None, sum.__doc__)
93 check_calltip(sum, 'sum', None, sum.__doc__)
94
94
95 def test_info():
95 def test_info():
96 "Check that Inspector.info fills out various fields as expected."
96 "Check that Inspector.info fills out various fields as expected."
97 i = inspector.info(Call, oname='Call')
97 i = inspector.info(Call, oname='Call')
98 nt.assert_equal(i['type_name'], 'type')
98 nt.assert_equal(i['type_name'], 'type')
99 nt.assert_equal(i['base_class'], "<type 'type'>")
99 nt.assert_equal(i['base_class'], "<type 'type'>")
100 nt.assert_equal(i['string_form'], "<class 'IPython.core.tests.test_oinspect.Call'>")
100 nt.assert_equal(i['string_form'], "<class 'IPython.core.tests.test_oinspect.Call'>")
101 fname = __file__
101 fname = __file__
102 if fname.endswith(".pyc"):
102 if fname.endswith(".pyc"):
103 fname = fname[:-1]
103 fname = fname[:-1]
104 nt.assert_equal(i['file'], fname)
104 # case-insensitive comparison needed on some filesystems
105 # e.g. Windows:
106 nt.assert_equal(i['file'].lower(), fname.lower())
105 nt.assert_equal(i['definition'], 'Call(self, *a, **kw)\n')
107 nt.assert_equal(i['definition'], 'Call(self, *a, **kw)\n')
106 nt.assert_equal(i['docstring'], Call.__doc__)
108 nt.assert_equal(i['docstring'], Call.__doc__)
107 nt.assert_equal(i['source'], None)
109 nt.assert_equal(i['source'], None)
108 nt.assert_true(i['isclass'])
110 nt.assert_true(i['isclass'])
109 nt.assert_equal(i['init_definition'], "Call(self, x, y=1)\n")
111 nt.assert_equal(i['init_definition'], "Call(self, x, y=1)\n")
110 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
112 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
111
113
112 i = inspector.info(Call, detail_level=1)
114 i = inspector.info(Call, detail_level=1)
113 nt.assert_not_equal(i['source'], None)
115 nt.assert_not_equal(i['source'], None)
114 nt.assert_equal(i['docstring'], None)
116 nt.assert_equal(i['docstring'], None)
115
117
116 c = Call(1)
118 c = Call(1)
117 c.__doc__ = "Modified instance docstring"
119 c.__doc__ = "Modified instance docstring"
118 i = inspector.info(c)
120 i = inspector.info(c)
119 nt.assert_equal(i['type_name'], 'Call')
121 nt.assert_equal(i['type_name'], 'Call')
120 nt.assert_equal(i['docstring'], "Modified instance docstring")
122 nt.assert_equal(i['docstring'], "Modified instance docstring")
121 nt.assert_equal(i['class_docstring'], Call.__doc__)
123 nt.assert_equal(i['class_docstring'], Call.__doc__)
122 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
124 nt.assert_equal(i['init_docstring'], Call.__init__.__doc__)
123 nt.assert_equal(i['call_docstring'], c.__call__.__doc__)
125 nt.assert_equal(i['call_docstring'], c.__call__.__doc__)
124
126
125 # Test old-style classes, which for example may not have an __init__ method.
127 # Test old-style classes, which for example may not have an __init__ method.
126 i = inspector.info(OldStyle)
128 i = inspector.info(OldStyle)
127 nt.assert_equal(i['type_name'], 'classobj')
129 nt.assert_equal(i['type_name'], 'classobj')
128
130
129 i = inspector.info(OldStyle())
131 i = inspector.info(OldStyle())
130 nt.assert_equal(i['type_name'], 'instance')
132 nt.assert_equal(i['type_name'], 'instance')
131 nt.assert_equal(i['docstring'], OldStyle.__doc__)
133 nt.assert_equal(i['docstring'], OldStyle.__doc__)
@@ -1,203 +1,208 b''
1 """Tests for code execution (%run and related), which is particularly tricky.
1 """Tests for code execution (%run and related), which is particularly tricky.
2
2
3 Because of how %run manages namespaces, and the fact that we are trying here to
3 Because of how %run manages namespaces, and the fact that we are trying here to
4 verify subtle object deletion and reference counting issues, the %run tests
4 verify subtle object deletion and reference counting issues, the %run tests
5 will be kept in this separate file. This makes it easier to aggregate in one
5 will be kept in this separate file. This makes it easier to aggregate in one
6 place the tricks needed to handle it; most other magics are much easier to test
6 place the tricks needed to handle it; most other magics are much easier to test
7 and we do so in a common test_magic file.
7 and we do so in a common test_magic file.
8 """
8 """
9 from __future__ import absolute_import
9 from __future__ import absolute_import
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 import os
15 import os
16 import sys
16 import sys
17 import tempfile
17 import tempfile
18
18
19 import nose.tools as nt
19 import nose.tools as nt
20 from nose import SkipTest
20
21
21 from IPython.testing import decorators as dec
22 from IPython.testing import decorators as dec
22 from IPython.testing import tools as tt
23 from IPython.testing import tools as tt
23
24
24 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
25 # Test functions begin
26 # Test functions begin
26 #-----------------------------------------------------------------------------
27 #-----------------------------------------------------------------------------
27
28
28 def doctest_refbug():
29 def doctest_refbug():
29 """Very nasty problem with references held by multiple runs of a script.
30 """Very nasty problem with references held by multiple runs of a script.
30 See: https://github.com/ipython/ipython/issues/141
31 See: https://github.com/ipython/ipython/issues/141
31
32
32 In [1]: _ip.clear_main_mod_cache()
33 In [1]: _ip.clear_main_mod_cache()
33 # random
34 # random
34
35
35 In [2]: %run refbug
36 In [2]: %run refbug
36
37
37 In [3]: call_f()
38 In [3]: call_f()
38 lowercased: hello
39 lowercased: hello
39
40
40 In [4]: %run refbug
41 In [4]: %run refbug
41
42
42 In [5]: call_f()
43 In [5]: call_f()
43 lowercased: hello
44 lowercased: hello
44 lowercased: hello
45 lowercased: hello
45 """
46 """
46
47
47
48
48 def doctest_run_builtins():
49 def doctest_run_builtins():
49 r"""Check that %run doesn't damage __builtins__.
50 r"""Check that %run doesn't damage __builtins__.
50
51
51 In [1]: import tempfile
52 In [1]: import tempfile
52
53
53 In [2]: bid1 = id(__builtins__)
54 In [2]: bid1 = id(__builtins__)
54
55
55 In [3]: fname = tempfile.mkstemp('.py')[1]
56 In [3]: fname = tempfile.mkstemp('.py')[1]
56
57
57 In [3]: f = open(fname,'w')
58 In [3]: f = open(fname,'w')
58
59
59 In [4]: f.write('pass\n')
60 In [4]: f.write('pass\n')
60
61
61 In [5]: f.flush()
62 In [5]: f.flush()
62
63
63 In [6]: t1 = type(__builtins__)
64 In [6]: t1 = type(__builtins__)
64
65
65 In [7]: %run $fname
66 In [7]: %run $fname
66
67
67 In [7]: f.close()
68 In [7]: f.close()
68
69
69 In [8]: bid2 = id(__builtins__)
70 In [8]: bid2 = id(__builtins__)
70
71
71 In [9]: t2 = type(__builtins__)
72 In [9]: t2 = type(__builtins__)
72
73
73 In [10]: t1 == t2
74 In [10]: t1 == t2
74 Out[10]: True
75 Out[10]: True
75
76
76 In [10]: bid1 == bid2
77 In [10]: bid1 == bid2
77 Out[10]: True
78 Out[10]: True
78
79
79 In [12]: try:
80 In [12]: try:
80 ....: os.unlink(fname)
81 ....: os.unlink(fname)
81 ....: except:
82 ....: except:
82 ....: pass
83 ....: pass
83 ....:
84 ....:
84 """
85 """
85
86
86 def doctest_reset_del():
87 def doctest_reset_del():
87 """Test that resetting doesn't cause errors in __del__ methods.
88 """Test that resetting doesn't cause errors in __del__ methods.
88
89
89 In [2]: class A(object):
90 In [2]: class A(object):
90 ...: def __del__(self):
91 ...: def __del__(self):
91 ...: print str("Hi")
92 ...: print str("Hi")
92 ...:
93 ...:
93
94
94 In [3]: a = A()
95 In [3]: a = A()
95
96
96 In [4]: get_ipython().reset()
97 In [4]: get_ipython().reset()
97 Hi
98 Hi
98
99
99 In [5]: 1+1
100 In [5]: 1+1
100 Out[5]: 2
101 Out[5]: 2
101 """
102 """
102
103
103 # For some tests, it will be handy to organize them in a class with a common
104 # For some tests, it will be handy to organize them in a class with a common
104 # setup that makes a temp file
105 # setup that makes a temp file
105
106
106 class TestMagicRunPass(tt.TempFileMixin):
107 class TestMagicRunPass(tt.TempFileMixin):
107
108
108 def setup(self):
109 def setup(self):
109 """Make a valid python temp file."""
110 """Make a valid python temp file."""
110 self.mktmp('pass\n')
111 self.mktmp('pass\n')
111
112
112 def run_tmpfile(self):
113 def run_tmpfile(self):
113 _ip = get_ipython()
114 _ip = get_ipython()
114 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
115 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
115 # See below and ticket https://bugs.launchpad.net/bugs/366353
116 # See below and ticket https://bugs.launchpad.net/bugs/366353
116 _ip.magic('run %s' % self.fname)
117 _ip.magic('run %s' % self.fname)
117
118
118 def test_builtins_id(self):
119 def test_builtins_id(self):
119 """Check that %run doesn't damage __builtins__ """
120 """Check that %run doesn't damage __builtins__ """
120 _ip = get_ipython()
121 _ip = get_ipython()
121 # Test that the id of __builtins__ is not modified by %run
122 # Test that the id of __builtins__ is not modified by %run
122 bid1 = id(_ip.user_ns['__builtins__'])
123 bid1 = id(_ip.user_ns['__builtins__'])
123 self.run_tmpfile()
124 self.run_tmpfile()
124 bid2 = id(_ip.user_ns['__builtins__'])
125 bid2 = id(_ip.user_ns['__builtins__'])
125 tt.assert_equals(bid1, bid2)
126 tt.assert_equals(bid1, bid2)
126
127
127 def test_builtins_type(self):
128 def test_builtins_type(self):
128 """Check that the type of __builtins__ doesn't change with %run.
129 """Check that the type of __builtins__ doesn't change with %run.
129
130
130 However, the above could pass if __builtins__ was already modified to
131 However, the above could pass if __builtins__ was already modified to
131 be a dict (it should be a module) by a previous use of %run. So we
132 be a dict (it should be a module) by a previous use of %run. So we
132 also check explicitly that it really is a module:
133 also check explicitly that it really is a module:
133 """
134 """
134 _ip = get_ipython()
135 _ip = get_ipython()
135 self.run_tmpfile()
136 self.run_tmpfile()
136 tt.assert_equals(type(_ip.user_ns['__builtins__']),type(sys))
137 tt.assert_equals(type(_ip.user_ns['__builtins__']),type(sys))
137
138
138 def test_prompts(self):
139 def test_prompts(self):
139 """Test that prompts correctly generate after %run"""
140 """Test that prompts correctly generate after %run"""
140 self.run_tmpfile()
141 self.run_tmpfile()
141 _ip = get_ipython()
142 _ip = get_ipython()
142 p2 = str(_ip.displayhook.prompt2).strip()
143 p2 = str(_ip.displayhook.prompt2).strip()
143 nt.assert_equals(p2[:3], '...')
144 nt.assert_equals(p2[:3], '...')
144
145
145
146
146 class TestMagicRunSimple(tt.TempFileMixin):
147 class TestMagicRunSimple(tt.TempFileMixin):
147
148
148 def test_simpledef(self):
149 def test_simpledef(self):
149 """Test that simple class definitions work."""
150 """Test that simple class definitions work."""
150 src = ("class foo: pass\n"
151 src = ("class foo: pass\n"
151 "def f(): return foo()")
152 "def f(): return foo()")
152 self.mktmp(src)
153 self.mktmp(src)
153 _ip.magic('run %s' % self.fname)
154 _ip.magic('run %s' % self.fname)
154 _ip.run_cell('t = isinstance(f(), foo)')
155 _ip.run_cell('t = isinstance(f(), foo)')
155 nt.assert_true(_ip.user_ns['t'])
156 nt.assert_true(_ip.user_ns['t'])
156
157
157 def test_obj_del(self):
158 def test_obj_del(self):
158 """Test that object's __del__ methods are called on exit."""
159 """Test that object's __del__ methods are called on exit."""
159
160 if sys.platform == 'win32':
161 try:
162 import win32api
163 except ImportError:
164 raise SkipTest("Test requires pywin32")
160 src = ("class A(object):\n"
165 src = ("class A(object):\n"
161 " def __del__(self):\n"
166 " def __del__(self):\n"
162 " print 'object A deleted'\n"
167 " print 'object A deleted'\n"
163 "a = A()\n")
168 "a = A()\n")
164 self.mktmp(src)
169 self.mktmp(src)
165 tt.ipexec_validate(self.fname, 'object A deleted')
170 tt.ipexec_validate(self.fname, 'object A deleted')
166
171
167 @dec.skip_known_failure
172 @dec.skip_known_failure
168 def test_aggressive_namespace_cleanup(self):
173 def test_aggressive_namespace_cleanup(self):
169 """Test that namespace cleanup is not too aggressive GH-238
174 """Test that namespace cleanup is not too aggressive GH-238
170
175
171 Returning from another run magic deletes the namespace"""
176 Returning from another run magic deletes the namespace"""
172 # see ticket https://github.com/ipython/ipython/issues/238
177 # see ticket https://github.com/ipython/ipython/issues/238
173 class secondtmp(tt.TempFileMixin): pass
178 class secondtmp(tt.TempFileMixin): pass
174 empty = secondtmp()
179 empty = secondtmp()
175 empty.mktmp('')
180 empty.mktmp('')
176 src = ("ip = get_ipython()\n"
181 src = ("ip = get_ipython()\n"
177 "for i in range(5):\n"
182 "for i in range(5):\n"
178 " try:\n"
183 " try:\n"
179 " ip.magic('run %s')\n"
184 " ip.magic('run %s')\n"
180 " except NameError, e:\n"
185 " except NameError, e:\n"
181 " print i;break\n" % empty.fname)
186 " print i;break\n" % empty.fname)
182 self.mktmp(src)
187 self.mktmp(src)
183 _ip.magic('run %s' % self.fname)
188 _ip.magic('run %s' % self.fname)
184 _ip.run_cell('ip == get_ipython()')
189 _ip.run_cell('ip == get_ipython()')
185 tt.assert_equals(_ip.user_ns['i'], 5)
190 tt.assert_equals(_ip.user_ns['i'], 5)
186
191
187 @dec.skip_win32
192 @dec.skip_win32
188 def test_tclass(self):
193 def test_tclass(self):
189 mydir = os.path.dirname(__file__)
194 mydir = os.path.dirname(__file__)
190 tc = os.path.join(mydir, 'tclass')
195 tc = os.path.join(mydir, 'tclass')
191 src = ("%%run '%s' C-first\n"
196 src = ("%%run '%s' C-first\n"
192 "%%run '%s' C-second\n"
197 "%%run '%s' C-second\n"
193 "%%run '%s' C-third\n") % (tc, tc, tc)
198 "%%run '%s' C-third\n") % (tc, tc, tc)
194 self.mktmp(src, '.ipy')
199 self.mktmp(src, '.ipy')
195 out = """\
200 out = """\
196 ARGV 1-: [u'C-first']
201 ARGV 1-: [u'C-first']
197 ARGV 1-: [u'C-second']
202 ARGV 1-: [u'C-second']
198 tclass.py: deleting object: C-first
203 tclass.py: deleting object: C-first
199 ARGV 1-: [u'C-third']
204 ARGV 1-: [u'C-third']
200 tclass.py: deleting object: C-second
205 tclass.py: deleting object: C-second
201 tclass.py: deleting object: C-third
206 tclass.py: deleting object: C-third
202 """
207 """
203 tt.ipexec_validate(self.fname, out)
208 tt.ipexec_validate(self.fname, out)
@@ -1,369 +1,371 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, skip_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 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
49 XDG_TEST_DIR = join(HOME_TEST_DIR, "xdg_test_dir")
50 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
50 IP_TEST_DIR = join(HOME_TEST_DIR,'.ipython')
51 #
51 #
52 # Setup/teardown functions/decorators
52 # Setup/teardown functions/decorators
53 #
53 #
54
54
55 def setup():
55 def setup():
56 """Setup testenvironment for the module:
56 """Setup testenvironment for the module:
57
57
58 - Adds dummy home dir tree
58 - Adds dummy home dir tree
59 """
59 """
60 # Do not mask exceptions here. In particular, catching WindowsError is a
60 # Do not mask exceptions here. In particular, catching WindowsError is a
61 # problem because that exception is only defined on Windows...
61 # problem because that exception is only defined on Windows...
62 os.makedirs(IP_TEST_DIR)
62 os.makedirs(IP_TEST_DIR)
63 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
63 os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython'))
64
64
65
65
66 def teardown():
66 def teardown():
67 """Teardown testenvironment for the module:
67 """Teardown testenvironment for the module:
68
68
69 - Remove dummy home dir tree
69 - Remove dummy home dir tree
70 """
70 """
71 # Note: we remove the parent test dir, which is the root of all test
71 # Note: we remove the parent test dir, which is the root of all test
72 # subdirs we may have created. Use shutil instead of os.removedirs, so
72 # subdirs we may have created. Use shutil instead of os.removedirs, so
73 # that non-empty directories are all recursively removed.
73 # that non-empty directories are all recursively removed.
74 shutil.rmtree(TMP_TEST_DIR)
74 shutil.rmtree(TMP_TEST_DIR)
75
75
76
76
77 def setup_environment():
77 def setup_environment():
78 """Setup testenvironment for some functions that are tested
78 """Setup testenvironment for some functions that are tested
79 in this module. In particular this functions stores attributes
79 in this module. In particular this functions stores attributes
80 and other things that we need to stub in some test functions.
80 and other things that we need to stub in some test functions.
81 This needs to be done on a function level and not module level because
81 This needs to be done on a function level and not module level because
82 each testfunction needs a pristine environment.
82 each testfunction needs a pristine environment.
83 """
83 """
84 global oldstuff, platformstuff
84 global oldstuff, platformstuff
85 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
85 oldstuff = (env.copy(), os.name, path.get_home_dir, IPython.__file__)
86
86
87 if os.name == 'nt':
87 if os.name == 'nt':
88 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
88 platformstuff = (wreg.OpenKey, wreg.QueryValueEx,)
89
89
90
90
91 def teardown_environment():
91 def teardown_environment():
92 """Restore things that were remebered by the setup_environment function
92 """Restore things that were remebered by the setup_environment function
93 """
93 """
94 (oldenv, os.name, path.get_home_dir, IPython.__file__,) = oldstuff
94 (oldenv, os.name, path.get_home_dir, IPython.__file__,) = oldstuff
95
95
96 for key in env.keys():
96 for key in env.keys():
97 if key not in oldenv:
97 if key not in oldenv:
98 del env[key]
98 del env[key]
99 env.update(oldenv)
99 env.update(oldenv)
100 if hasattr(sys, 'frozen'):
100 if hasattr(sys, 'frozen'):
101 del sys.frozen
101 del sys.frozen
102 if os.name == 'nt':
102 if os.name == 'nt':
103 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
103 (wreg.OpenKey, wreg.QueryValueEx,) = platformstuff
104
104
105 # Build decorator that uses the setup_environment/setup_environment
105 # Build decorator that uses the setup_environment/setup_environment
106 with_environment = with_setup(setup_environment, teardown_environment)
106 with_environment = with_setup(setup_environment, teardown_environment)
107
107
108
108
109 @skip_if_not_win32
109 @skip_if_not_win32
110 @with_environment
110 @with_environment
111 def test_get_home_dir_1():
111 def test_get_home_dir_1():
112 """Testcase for py2exe logic, un-compressed lib
112 """Testcase for py2exe logic, un-compressed lib
113 """
113 """
114 sys.frozen = True
114 sys.frozen = True
115
115
116 #fake filename for IPython.__init__
116 #fake filename for IPython.__init__
117 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
117 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py"))
118
118
119 home_dir = path.get_home_dir()
119 home_dir = path.get_home_dir()
120 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
120 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
121
121
122
122
123 @skip_if_not_win32
123 @skip_if_not_win32
124 @with_environment
124 @with_environment
125 def test_get_home_dir_2():
125 def test_get_home_dir_2():
126 """Testcase for py2exe logic, compressed lib
126 """Testcase for py2exe logic, compressed lib
127 """
127 """
128 sys.frozen = True
128 sys.frozen = True
129 #fake filename for IPython.__init__
129 #fake filename for IPython.__init__
130 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
130 IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower()
131
131
132 home_dir = path.get_home_dir()
132 home_dir = path.get_home_dir()
133 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
133 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR).lower())
134
134
135
135
136 @with_environment
136 @with_environment
137 @skip_win32
137 @skip_win32
138 def test_get_home_dir_3():
138 def test_get_home_dir_3():
139 """Testcase $HOME is set, then use its value as home directory."""
139 """Testcase $HOME is set, then use its value as home directory."""
140 env["HOME"] = HOME_TEST_DIR
140 env["HOME"] = HOME_TEST_DIR
141 home_dir = path.get_home_dir()
141 home_dir = path.get_home_dir()
142 nt.assert_equal(home_dir, env["HOME"])
142 nt.assert_equal(home_dir, env["HOME"])
143
143
144
144
145 @with_environment
145 @with_environment
146 @skip_win32
146 def test_get_home_dir_4():
147 def test_get_home_dir_4():
147 """Testcase $HOME is not set, os=='posix'.
148 """Testcase $HOME is not set, os=='posix'.
148 This should fail with HomeDirError"""
149 This should fail with HomeDirError"""
149
150
150 os.name = 'posix'
151 os.name = 'posix'
151 if 'HOME' in env: del env['HOME']
152 if 'HOME' in env: del env['HOME']
152 nt.assert_raises(path.HomeDirError, path.get_home_dir)
153 nt.assert_raises(path.HomeDirError, path.get_home_dir)
153
154
154
155
155 @skip_if_not_win32
156 @skip_if_not_win32
156 @with_environment
157 @with_environment
157 def test_get_home_dir_5():
158 def test_get_home_dir_5():
158 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
159 """Using HOMEDRIVE + HOMEPATH, os=='nt'.
159
160
160 HOMESHARE is missing.
161 HOMESHARE is missing.
161 """
162 """
162
163
163 os.name = 'nt'
164 os.name = 'nt'
164 env.pop('HOMESHARE', None)
165 env.pop('HOMESHARE', None)
165 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
166 env['HOMEDRIVE'], env['HOMEPATH'] = os.path.splitdrive(HOME_TEST_DIR)
166 home_dir = path.get_home_dir()
167 home_dir = path.get_home_dir()
167 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
168 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
168
169
169
170
170 @skip_if_not_win32
171 @skip_if_not_win32
171 @with_environment
172 @with_environment
172 def test_get_home_dir_6():
173 def test_get_home_dir_6():
173 """Using USERPROFILE, os=='nt'.
174 """Using USERPROFILE, os=='nt'.
174
175
175 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
176 HOMESHARE, HOMEDRIVE, HOMEPATH are missing.
176 """
177 """
177
178
178 os.name = 'nt'
179 os.name = 'nt'
179 env.pop('HOMESHARE', None)
180 env.pop('HOMESHARE', None)
180 env.pop('HOMEDRIVE', None)
181 env.pop('HOMEDRIVE', None)
181 env.pop('HOMEPATH', None)
182 env.pop('HOMEPATH', None)
182 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
183 env["USERPROFILE"] = abspath(HOME_TEST_DIR)
183 home_dir = path.get_home_dir()
184 home_dir = path.get_home_dir()
184 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
185 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
185
186
186
187
187 @skip_if_not_win32
188 @skip_if_not_win32
188 @with_environment
189 @with_environment
189 def test_get_home_dir_7():
190 def test_get_home_dir_7():
190 """Using HOMESHARE, os=='nt'."""
191 """Using HOMESHARE, os=='nt'."""
191
192
192 os.name = 'nt'
193 os.name = 'nt'
193 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
194 env["HOMESHARE"] = abspath(HOME_TEST_DIR)
194 home_dir = path.get_home_dir()
195 home_dir = path.get_home_dir()
195 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
196 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
196
197
197
198
198 # Should we stub wreg fully so we can run the test on all platforms?
199 # Should we stub wreg fully so we can run the test on all platforms?
199 @skip_if_not_win32
200 @skip_if_not_win32
200 @with_environment
201 @with_environment
201 def test_get_home_dir_8():
202 def test_get_home_dir_8():
202 """Using registry hack for 'My Documents', os=='nt'
203 """Using registry hack for 'My Documents', os=='nt'
203
204
204 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
205 HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing.
205 """
206 """
206 os.name = 'nt'
207 os.name = 'nt'
207 # Remove from stub environment all keys that may be set
208 # Remove from stub environment all keys that may be set
208 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
209 for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']:
209 env.pop(key, None)
210 env.pop(key, None)
210
211
211 #Stub windows registry functions
212 #Stub windows registry functions
212 def OpenKey(x, y):
213 def OpenKey(x, y):
213 class key:
214 class key:
214 def Close(self):
215 def Close(self):
215 pass
216 pass
216 return key()
217 return key()
217 def QueryValueEx(x, y):
218 def QueryValueEx(x, y):
218 return [abspath(HOME_TEST_DIR)]
219 return [abspath(HOME_TEST_DIR)]
219
220
220 wreg.OpenKey = OpenKey
221 wreg.OpenKey = OpenKey
221 wreg.QueryValueEx = QueryValueEx
222 wreg.QueryValueEx = QueryValueEx
222
223
223 home_dir = path.get_home_dir()
224 home_dir = path.get_home_dir()
224 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
225 nt.assert_equal(home_dir, abspath(HOME_TEST_DIR))
225
226
226
227
227 @with_environment
228 @with_environment
228 def test_get_ipython_dir_1():
229 def test_get_ipython_dir_1():
229 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
230 """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions."""
230 env['IPYTHON_DIR'] = "someplace/.ipython"
231 env_ipdir = os.path.join("someplace", ".ipython")
232 env['IPYTHON_DIR'] = env_ipdir
231 ipdir = path.get_ipython_dir()
233 ipdir = path.get_ipython_dir()
232 nt.assert_equal(ipdir, "someplace/.ipython")
234 nt.assert_equal(ipdir, env_ipdir)
233
235
234
236
235 @with_environment
237 @with_environment
236 def test_get_ipython_dir_2():
238 def test_get_ipython_dir_2():
237 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
239 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
238 path.get_home_dir = lambda : "someplace"
240 path.get_home_dir = lambda : "someplace"
239 os.name = "posix"
241 os.name = "posix"
240 env.pop('IPYTHON_DIR', None)
242 env.pop('IPYTHON_DIR', None)
241 env.pop('IPYTHONDIR', None)
243 env.pop('IPYTHONDIR', None)
242 env.pop('XDG_CONFIG_HOME', None)
244 env.pop('XDG_CONFIG_HOME', None)
243 ipdir = path.get_ipython_dir()
245 ipdir = path.get_ipython_dir()
244 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
246 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
245
247
246 @with_environment
248 @with_environment
247 def test_get_ipython_dir_3():
249 def test_get_ipython_dir_3():
248 """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist."""
250 """test_get_ipython_dir_3, use XDG if defined, and .ipython doesn't exist."""
249 path.get_home_dir = lambda : "someplace"
251 path.get_home_dir = lambda : "someplace"
250 os.name = "posix"
252 os.name = "posix"
251 env.pop('IPYTHON_DIR', None)
253 env.pop('IPYTHON_DIR', None)
252 env.pop('IPYTHONDIR', None)
254 env.pop('IPYTHONDIR', None)
253 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
255 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
254 ipdir = path.get_ipython_dir()
256 ipdir = path.get_ipython_dir()
255 nt.assert_equal(ipdir, os.path.join(XDG_TEST_DIR, "ipython"))
257 nt.assert_equal(ipdir, os.path.join(XDG_TEST_DIR, "ipython"))
256
258
257 @with_environment
259 @with_environment
258 def test_get_ipython_dir_4():
260 def test_get_ipython_dir_4():
259 """test_get_ipython_dir_4, use XDG if both exist."""
261 """test_get_ipython_dir_4, use XDG if both exist."""
260 path.get_home_dir = lambda : HOME_TEST_DIR
262 path.get_home_dir = lambda : HOME_TEST_DIR
261 os.name = "posix"
263 os.name = "posix"
262 env.pop('IPYTHON_DIR', None)
264 env.pop('IPYTHON_DIR', None)
263 env.pop('IPYTHONDIR', None)
265 env.pop('IPYTHONDIR', None)
264 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
266 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
265 xdg_ipdir = os.path.join(XDG_TEST_DIR, "ipython")
267 xdg_ipdir = os.path.join(XDG_TEST_DIR, "ipython")
266 ipdir = path.get_ipython_dir()
268 ipdir = path.get_ipython_dir()
267 nt.assert_equal(ipdir, xdg_ipdir)
269 nt.assert_equal(ipdir, xdg_ipdir)
268
270
269 @with_environment
271 @with_environment
270 def test_get_ipython_dir_5():
272 def test_get_ipython_dir_5():
271 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
273 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
272 path.get_home_dir = lambda : HOME_TEST_DIR
274 path.get_home_dir = lambda : HOME_TEST_DIR
273 os.name = "posix"
275 os.name = "posix"
274 env.pop('IPYTHON_DIR', None)
276 env.pop('IPYTHON_DIR', None)
275 env.pop('IPYTHONDIR', None)
277 env.pop('IPYTHONDIR', None)
276 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
278 env['XDG_CONFIG_HOME'] = XDG_TEST_DIR
277 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
279 os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython'))
278 ipdir = path.get_ipython_dir()
280 ipdir = path.get_ipython_dir()
279 nt.assert_equal(ipdir, IP_TEST_DIR)
281 nt.assert_equal(ipdir, IP_TEST_DIR)
280
282
281 @with_environment
283 @with_environment
282 def test_get_ipython_dir_6():
284 def test_get_ipython_dir_6():
283 """test_get_ipython_dir_6, use XDG if defined and neither exist."""
285 """test_get_ipython_dir_6, use XDG if defined and neither exist."""
284 path.get_home_dir = lambda : 'somehome'
286 path.get_home_dir = lambda : 'somehome'
285 path.get_xdg_dir = lambda : 'somexdg'
287 path.get_xdg_dir = lambda : 'somexdg'
286 os.name = "posix"
288 os.name = "posix"
287 env.pop('IPYTHON_DIR', None)
289 env.pop('IPYTHON_DIR', None)
288 env.pop('IPYTHONDIR', None)
290 env.pop('IPYTHONDIR', None)
289 xdg_ipdir = os.path.join("somexdg", "ipython")
291 xdg_ipdir = os.path.join("somexdg", "ipython")
290 ipdir = path.get_ipython_dir()
292 ipdir = path.get_ipython_dir()
291 nt.assert_equal(ipdir, xdg_ipdir)
293 nt.assert_equal(ipdir, xdg_ipdir)
292
294
293 @with_environment
295 @with_environment
294 def test_get_ipython_dir_7():
296 def test_get_ipython_dir_7():
295 """test_get_ipython_dir_7, test home directory expansion on IPYTHON_DIR"""
297 """test_get_ipython_dir_7, test home directory expansion on IPYTHON_DIR"""
296 home_dir = os.path.expanduser('~/')
298 home_dir = os.path.expanduser('~')
297 env['IPYTHON_DIR'] = '~/somewhere'
299 env['IPYTHON_DIR'] = os.path.join('~', 'somewhere')
298 ipdir = path.get_ipython_dir()
300 ipdir = path.get_ipython_dir()
299 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
301 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
300
302
301
303
302 @with_environment
304 @with_environment
303 def test_get_xdg_dir_1():
305 def test_get_xdg_dir_1():
304 """test_get_xdg_dir_1, check xdg_dir"""
306 """test_get_xdg_dir_1, check xdg_dir"""
305 reload(path)
307 reload(path)
306 path.get_home_dir = lambda : 'somewhere'
308 path.get_home_dir = lambda : 'somewhere'
307 os.name = "posix"
309 os.name = "posix"
308 env.pop('IPYTHON_DIR', None)
310 env.pop('IPYTHON_DIR', None)
309 env.pop('IPYTHONDIR', None)
311 env.pop('IPYTHONDIR', None)
310 env.pop('XDG_CONFIG_HOME', None)
312 env.pop('XDG_CONFIG_HOME', None)
311
313
312 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
314 nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config'))
313
315
314
316
315 @with_environment
317 @with_environment
316 def test_get_xdg_dir_1():
318 def test_get_xdg_dir_1():
317 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
319 """test_get_xdg_dir_1, check nonexistant xdg_dir"""
318 reload(path)
320 reload(path)
319 path.get_home_dir = lambda : HOME_TEST_DIR
321 path.get_home_dir = lambda : HOME_TEST_DIR
320 os.name = "posix"
322 os.name = "posix"
321 env.pop('IPYTHON_DIR', None)
323 env.pop('IPYTHON_DIR', None)
322 env.pop('IPYTHONDIR', None)
324 env.pop('IPYTHONDIR', None)
323 env.pop('XDG_CONFIG_HOME', None)
325 env.pop('XDG_CONFIG_HOME', None)
324 nt.assert_equal(path.get_xdg_dir(), None)
326 nt.assert_equal(path.get_xdg_dir(), None)
325
327
326 @with_environment
328 @with_environment
327 def test_get_xdg_dir_2():
329 def test_get_xdg_dir_2():
328 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
330 """test_get_xdg_dir_2, check xdg_dir default to ~/.config"""
329 reload(path)
331 reload(path)
330 path.get_home_dir = lambda : HOME_TEST_DIR
332 path.get_home_dir = lambda : HOME_TEST_DIR
331 os.name = "posix"
333 os.name = "posix"
332 env.pop('IPYTHON_DIR', None)
334 env.pop('IPYTHON_DIR', None)
333 env.pop('IPYTHONDIR', None)
335 env.pop('IPYTHONDIR', None)
334 env.pop('XDG_CONFIG_HOME', None)
336 env.pop('XDG_CONFIG_HOME', None)
335 cfgdir=os.path.join(path.get_home_dir(), '.config')
337 cfgdir=os.path.join(path.get_home_dir(), '.config')
336 os.makedirs(cfgdir)
338 os.makedirs(cfgdir)
337
339
338 nt.assert_equal(path.get_xdg_dir(), cfgdir)
340 nt.assert_equal(path.get_xdg_dir(), cfgdir)
339
341
340 def test_filefind():
342 def test_filefind():
341 """Various tests for filefind"""
343 """Various tests for filefind"""
342 f = tempfile.NamedTemporaryFile()
344 f = tempfile.NamedTemporaryFile()
343 # print 'fname:',f.name
345 # print 'fname:',f.name
344 alt_dirs = path.get_ipython_dir()
346 alt_dirs = path.get_ipython_dir()
345 t = path.filefind(f.name, alt_dirs)
347 t = path.filefind(f.name, alt_dirs)
346 # print 'found:',t
348 # print 'found:',t
347
349
348
350
349 def test_get_ipython_package_dir():
351 def test_get_ipython_package_dir():
350 ipdir = path.get_ipython_package_dir()
352 ipdir = path.get_ipython_package_dir()
351 nt.assert_true(os.path.isdir(ipdir))
353 nt.assert_true(os.path.isdir(ipdir))
352
354
353
355
354 def test_get_ipython_module_path():
356 def test_get_ipython_module_path():
355 ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp')
357 ipapp_path = path.get_ipython_module_path('IPython.frontend.terminal.ipapp')
356 nt.assert_true(os.path.isfile(ipapp_path))
358 nt.assert_true(os.path.isfile(ipapp_path))
357
359
358
360
359 @dec.skip_if_not_win32
361 @dec.skip_if_not_win32
360 def test_get_long_path_name_win32():
362 def test_get_long_path_name_win32():
361 p = path.get_long_path_name('c:\\docume~1')
363 p = path.get_long_path_name('c:\\docume~1')
362 nt.assert_equals(p,u'c:\\Documents and Settings')
364 nt.assert_equals(p,u'c:\\Documents and Settings')
363
365
364
366
365 @dec.skip_win32
367 @dec.skip_win32
366 def test_get_long_path_name():
368 def test_get_long_path_name():
367 p = path.get_long_path_name('/usr/local')
369 p = path.get_long_path_name('/usr/local')
368 nt.assert_equals(p,'/usr/local')
370 nt.assert_equals(p,'/usr/local')
369
371
General Comments 0
You need to be logged in to leave comments. Login now