##// END OF EJS Templates
Merging -r 1200 from lp:ipython.
Brian Granger -
r2154:a02653fa merge
parent child Browse files
Show More
@@ -1,295 +1,302
1 1 """Tests for various magic functions.
2 2
3 3 Needs to be run by nose (to make ipython session available).
4 4 """
5 5
6 6 import os
7 7 import sys
8 8 import tempfile
9 9 import types
10 10
11 11 import nose.tools as nt
12 12
13 13 from IPython.utils.platutils import find_cmd, get_long_path_name
14 14 from IPython.testing import decorators as dec
15 15 from IPython.testing import tools as tt
16 16
17 17 #-----------------------------------------------------------------------------
18 18 # Test functions begin
19 19
20 20 def test_rehashx():
21 21 # clear up everything
22 22 _ip.IP.alias_table.clear()
23 23 del _ip.db['syscmdlist']
24 24
25 25 _ip.magic('rehashx')
26 26 # Practically ALL ipython development systems will have more than 10 aliases
27 27
28 28 yield (nt.assert_true, len(_ip.IP.alias_table) > 10)
29 29 for key, val in _ip.IP.alias_table.items():
30 30 # we must strip dots from alias names
31 31 nt.assert_true('.' not in key)
32 32
33 33 # rehashx must fill up syscmdlist
34 34 scoms = _ip.db['syscmdlist']
35 35 yield (nt.assert_true, len(scoms) > 10)
36 36
37 37
38 38 def doctest_hist_f():
39 39 """Test %hist -f with temporary filename.
40 40
41 41 In [9]: import tempfile
42 42
43 43 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
44 44
45 45 In [11]: %hist -n -f $tfile 3
46 46 """
47 47
48 48
49 49 def doctest_hist_r():
50 50 """Test %hist -r
51 51
52 52 XXX - This test is not recording the output correctly. Not sure why...
53 53
54 54 In [20]: 'hist' in _ip.IP.lsmagic()
55 55 Out[20]: True
56 56
57 57 In [6]: x=1
58 58
59 59 In [7]: %hist -n -r 2
60 60 x=1 # random
61 61 hist -n -r 2 # random
62 62 """
63 63
64 64 # This test is known to fail on win32.
65 65 # See ticket https://bugs.launchpad.net/bugs/366334
66 66 def test_obj_del():
67 67 """Test that object's __del__ methods are called on exit."""
68 68 test_dir = os.path.dirname(__file__)
69 69 del_file = os.path.join(test_dir,'obj_del.py')
70 70 ipython_cmd = find_cmd('ipython')
71 71 out = _ip.IP.getoutput('%s %s' % (ipython_cmd, del_file))
72 72 nt.assert_equals(out,'obj_del.py: object A deleted')
73 73
74 74
75 75 def test_shist():
76 76 # Simple tests of ShadowHist class - test generator.
77 77 import os, shutil, tempfile
78 78
79 79 from IPython.extensions import pickleshare
80 80 from IPython.core.history import ShadowHist
81 81
82 82 tfile = tempfile.mktemp('','tmp-ipython-')
83 83
84 84 db = pickleshare.PickleShareDB(tfile)
85 85 s = ShadowHist(db)
86 86 s.add('hello')
87 87 s.add('world')
88 88 s.add('hello')
89 89 s.add('hello')
90 90 s.add('karhu')
91 91
92 92 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
93 93
94 94 yield nt.assert_equal,s.get(2),'world'
95 95
96 96 shutil.rmtree(tfile)
97 97
98 98 @dec.skipif_not_numpy
99 99 def test_numpy_clear_array_undec():
100 100 from IPython.extensions import clearcmd
101 101
102 102 _ip.ex('import numpy as np')
103 103 _ip.ex('a = np.empty(2)')
104 104 yield (nt.assert_true, 'a' in _ip.user_ns)
105 105 _ip.magic('clear array')
106 106 yield (nt.assert_false, 'a' in _ip.user_ns)
107 107
108 108
109 109 @dec.skip()
110 110 def test_fail_dec(*a,**k):
111 111 yield nt.assert_true, False
112 112
113 113 @dec.skip('This one shouldn not run')
114 114 def test_fail_dec2(*a,**k):
115 115 yield nt.assert_true, False
116 116
117 117 @dec.skipknownfailure
118 118 def test_fail_dec3(*a,**k):
119 119 yield nt.assert_true, False
120 120
121 121
122 122 def doctest_refbug():
123 123 """Very nasty problem with references held by multiple runs of a script.
124 124 See: https://bugs.launchpad.net/ipython/+bug/269966
125 125
126 126 In [1]: _ip.IP.clear_main_mod_cache()
127 127
128 128 In [2]: run refbug
129 129
130 130 In [3]: call_f()
131 131 lowercased: hello
132 132
133 133 In [4]: run refbug
134 134
135 135 In [5]: call_f()
136 136 lowercased: hello
137 137 lowercased: hello
138 138 """
139 139
140 140 #-----------------------------------------------------------------------------
141 141 # Tests for %run
142 142 #-----------------------------------------------------------------------------
143 143
144 144 # %run is critical enough that it's a good idea to have a solid collection of
145 145 # tests for it, some as doctests and some as normal tests.
146 146
147 147 def doctest_run_ns():
148 148 """Classes declared %run scripts must be instantiable afterwards.
149 149
150 150 In [11]: run tclass foo
151 151
152 152 In [12]: isinstance(f(),foo)
153 153 Out[12]: True
154 154 """
155 155
156 156
157 157 def doctest_run_ns2():
158 158 """Classes declared %run scripts must be instantiable afterwards.
159 159
160 160 In [4]: run tclass C-first_pass
161 161
162 162 In [5]: run tclass C-second_pass
163 163 tclass.py: deleting object: C-first_pass
164 164 """
165 165
166 166 def doctest_run_builtins():
167 167 """Check that %run doesn't damage __builtins__ via a doctest.
168 168
169 169 This is similar to the test_run_builtins, but I want *both* forms of the
170 170 test to catch any possible glitches in our testing machinery, since that
171 171 modifies %run somewhat. So for this, we have both a normal test (below)
172 172 and a doctest (this one).
173 173
174 174 In [1]: import tempfile
175 175
176 176 In [2]: bid1 = id(__builtins__)
177 177
178 178 In [3]: fname = tempfile.mkstemp()[1]
179 179
180 180 In [3]: f = open(fname,'w')
181 181
182 182 In [4]: f.write('pass\\n')
183 183
184 184 In [5]: f.flush()
185 185
186 186 In [6]: print type(__builtins__)
187 187 <type 'module'>
188 188
189 189 In [7]: %run "$fname"
190 190
191 191 In [7]: f.close()
192 192
193 193 In [8]: bid2 = id(__builtins__)
194 194
195 195 In [9]: print type(__builtins__)
196 196 <type 'module'>
197 197
198 198 In [10]: bid1 == bid2
199 199 Out[10]: True
200 200
201 201 In [12]: try:
202 202 ....: os.unlink(fname)
203 203 ....: except:
204 204 ....: pass
205 205 ....:
206 206 """
207 207
208 208 # For some tests, it will be handy to organize them in a class with a common
209 209 # setup that makes a temp file
210 210
211 211 class TestMagicRun(object):
212 212
213 213 def setup(self):
214 214 """Make a valid python temp file."""
215 215 fname = tempfile.mkstemp()[1]
216 216 f = open(fname,'w')
217 217 f.write('pass\n')
218 218 f.flush()
219 219 self.tmpfile = f
220 220 self.fname = fname
221 221
222 222 def run_tmpfile(self):
223 223 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
224 224 # See below and ticket https://bugs.launchpad.net/bugs/366353
225 225 _ip.magic('run "%s"' % self.fname)
226 226
227 227 def test_builtins_id(self):
228 228 """Check that %run doesn't damage __builtins__ """
229 229
230 230 # Test that the id of __builtins__ is not modified by %run
231 231 bid1 = id(_ip.user_ns['__builtins__'])
232 232 self.run_tmpfile()
233 233 bid2 = id(_ip.user_ns['__builtins__'])
234 234 tt.assert_equals(bid1, bid2)
235 235
236 236 def test_builtins_type(self):
237 237 """Check that the type of __builtins__ doesn't change with %run.
238 238
239 239 However, the above could pass if __builtins__ was already modified to
240 240 be a dict (it should be a module) by a previous use of %run. So we
241 241 also check explicitly that it really is a module:
242 242 """
243 243 self.run_tmpfile()
244 244 tt.assert_equals(type(_ip.user_ns['__builtins__']),type(sys))
245 245
246 246 def test_prompts(self):
247 247 """Test that prompts correctly generate after %run"""
248 248 self.run_tmpfile()
249 249 p2 = str(_ip.IP.outputcache.prompt2).strip()
250 250 nt.assert_equals(p2[:3], '...')
251 251
252 252 def teardown(self):
253 253 self.tmpfile.close()
254 254 try:
255 255 os.unlink(self.fname)
256 256 except:
257 257 # On Windows, even though we close the file, we still can't delete
258 258 # it. I have no clue why
259 259 pass
260 260
261 261 # Multiple tests for clipboard pasting
262 262 def test_paste():
263 263
264 264 def paste(txt):
265 265 hooks.clipboard_get = lambda : txt
266 266 _ip.magic('paste')
267 267
268 268 # Inject fake clipboard hook but save original so we can restore it later
269 269 hooks = _ip.IP.hooks
270 270 user_ns = _ip.user_ns
271 271 original_clip = hooks.clipboard_get
272 272
273 273 try:
274 # This try/except with an emtpy except clause is here only because
275 # try/yield/finally is invalid syntax in Python 2.4. This will be
276 # removed when we drop 2.4-compatibility, and the emtpy except below
277 # will be changed to a finally.
278
274 279 # Run tests with fake clipboard function
275 280 user_ns.pop('x', None)
276 281 paste('x=1')
277 282 yield (nt.assert_equal, user_ns['x'], 1)
278 283
279 284 user_ns.pop('x', None)
280 285 paste('>>> x=2')
281 286 yield (nt.assert_equal, user_ns['x'], 2)
282 287
283 288 paste("""
284 289 >>> x = [1,2,3]
285 290 >>> y = []
286 291 >>> for i in x:
287 292 ... y.append(i**2)
288 293 ...
289 294 """)
290 295 yield (nt.assert_equal, user_ns['x'], [1,2,3])
291 296 yield (nt.assert_equal, user_ns['y'], [1,4,9])
297 except:
298 pass
292 299
293 finally:
300 # This should be in a finally clause, instead of the bare except above.
294 301 # Restore original hook
295 302 hooks.clipboard_get = original_clip
General Comments 0
You need to be logged in to leave comments. Login now