##// END OF EJS Templates
Add test for installing, loading, unloading an extension.
Thomas Kluyver -
Show More
@@ -0,0 +1,12 b''
1 # -*- coding: utf-8 -*-
2 """
3 Useless IPython extension to test installing and loading extensions.
4 """
5 some_vars = {'arq': 185}
6
7 def load_ipython_extension(ip):
8 # set up simplified quantity input
9 ip.push(some_vars)
10
11 def unload_ipython_extension(ip):
12 ip.drop_by_id(some_vars)
@@ -1,396 +1,414 b''
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 from __future__ import absolute_import
6 6
7 7 #-----------------------------------------------------------------------------
8 8 # Imports
9 9 #-----------------------------------------------------------------------------
10 10
11 11 import os
12 12
13 13 import nose.tools as nt
14 14
15 15 from IPython.testing import decorators as dec
16 16 from IPython.testing import tools as tt
17 17 from IPython.utils import py3compat
18 from IPython.utils.tempdir import TemporaryDirectory
18 19
19 20 #-----------------------------------------------------------------------------
20 21 # Test functions begin
21 22 #-----------------------------------------------------------------------------
22 23
23 24 def test_rehashx():
24 25 # clear up everything
25 26 _ip = get_ipython()
26 27 _ip.alias_manager.alias_table.clear()
27 28 del _ip.db['syscmdlist']
28 29
29 30 _ip.magic('rehashx')
30 31 # Practically ALL ipython development systems will have more than 10 aliases
31 32
32 33 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
33 34 for key, val in _ip.alias_manager.alias_table.iteritems():
34 35 # we must strip dots from alias names
35 36 nt.assert_true('.' not in key)
36 37
37 38 # rehashx must fill up syscmdlist
38 39 scoms = _ip.db['syscmdlist']
39 40 yield (nt.assert_true, len(scoms) > 10)
40 41
41 42
42 43 def test_magic_parse_options():
43 44 """Test that we don't mangle paths when parsing magic options."""
44 45 ip = get_ipython()
45 46 path = 'c:\\x'
46 47 opts = ip.parse_options('-f %s' % path,'f:')[0]
47 48 # argv splitting is os-dependent
48 49 if os.name == 'posix':
49 50 expected = 'c:x'
50 51 else:
51 52 expected = path
52 53 nt.assert_equals(opts['f'], expected)
53 54
54 55
55 56 @dec.skip_without('sqlite3')
56 57 def doctest_hist_f():
57 58 """Test %hist -f with temporary filename.
58 59
59 60 In [9]: import tempfile
60 61
61 62 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
62 63
63 64 In [11]: %hist -nl -f $tfile 3
64 65
65 66 In [13]: import os; os.unlink(tfile)
66 67 """
67 68
68 69
69 70 @dec.skip_without('sqlite3')
70 71 def doctest_hist_r():
71 72 """Test %hist -r
72 73
73 74 XXX - This test is not recording the output correctly. For some reason, in
74 75 testing mode the raw history isn't getting populated. No idea why.
75 76 Disabling the output checking for now, though at least we do run it.
76 77
77 78 In [1]: 'hist' in _ip.lsmagic()
78 79 Out[1]: True
79 80
80 81 In [2]: x=1
81 82
82 83 In [3]: %hist -rl 2
83 84 x=1 # random
84 85 %hist -r 2
85 86 """
86 87
87 88
88 89 @dec.skip_without('sqlite3')
89 90 def doctest_hist_op():
90 91 """Test %hist -op
91 92
92 93 In [1]: class b(float):
93 94 ...: pass
94 95 ...:
95 96
96 97 In [2]: class s(object):
97 98 ...: def __str__(self):
98 99 ...: return 's'
99 100 ...:
100 101
101 102 In [3]:
102 103
103 104 In [4]: class r(b):
104 105 ...: def __repr__(self):
105 106 ...: return 'r'
106 107 ...:
107 108
108 109 In [5]: class sr(s,r): pass
109 110 ...:
110 111
111 112 In [6]:
112 113
113 114 In [7]: bb=b()
114 115
115 116 In [8]: ss=s()
116 117
117 118 In [9]: rr=r()
118 119
119 120 In [10]: ssrr=sr()
120 121
121 122 In [11]: 4.5
122 123 Out[11]: 4.5
123 124
124 125 In [12]: str(ss)
125 126 Out[12]: 's'
126 127
127 128 In [13]:
128 129
129 130 In [14]: %hist -op
130 131 >>> class b:
131 132 ... pass
132 133 ...
133 134 >>> class s(b):
134 135 ... def __str__(self):
135 136 ... return 's'
136 137 ...
137 138 >>>
138 139 >>> class r(b):
139 140 ... def __repr__(self):
140 141 ... return 'r'
141 142 ...
142 143 >>> class sr(s,r): pass
143 144 >>>
144 145 >>> bb=b()
145 146 >>> ss=s()
146 147 >>> rr=r()
147 148 >>> ssrr=sr()
148 149 >>> 4.5
149 150 4.5
150 151 >>> str(ss)
151 152 's'
152 153 >>>
153 154 """
154 155
155 156
156 157 @dec.skip_without('sqlite3')
157 158 def test_macro():
158 159 ip = get_ipython()
159 160 ip.history_manager.reset() # Clear any existing history.
160 161 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
161 162 for i, cmd in enumerate(cmds, start=1):
162 163 ip.history_manager.store_inputs(i, cmd)
163 164 ip.magic("macro test 1-3")
164 165 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
165 166
166 167 # List macros.
167 168 assert "test" in ip.magic("macro")
168 169
169 170
170 171 @dec.skip_without('sqlite3')
171 172 def test_macro_run():
172 173 """Test that we can run a multi-line macro successfully."""
173 174 ip = get_ipython()
174 175 ip.history_manager.reset()
175 176 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
176 177 "%macro test 2-3"]
177 178 for cmd in cmds:
178 179 ip.run_cell(cmd, store_history=True)
179 180 nt.assert_equal(ip.user_ns["test"].value,
180 181 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
181 182 with tt.AssertPrints("12"):
182 183 ip.run_cell("test")
183 184 with tt.AssertPrints("13"):
184 185 ip.run_cell("test")
185 186
186 187
187 188 @dec.skipif_not_numpy
188 189 def test_numpy_reset_array_undec():
189 190 "Test '%reset array' functionality"
190 191 _ip.ex('import numpy as np')
191 192 _ip.ex('a = np.empty(2)')
192 193 yield (nt.assert_true, 'a' in _ip.user_ns)
193 194 _ip.magic('reset -f array')
194 195 yield (nt.assert_false, 'a' in _ip.user_ns)
195 196
196 197 def test_reset_out():
197 198 "Test '%reset out' magic"
198 199 _ip.run_cell("parrot = 'dead'", store_history=True)
199 200 # test '%reset -f out', make an Out prompt
200 201 _ip.run_cell("parrot", store_history=True)
201 202 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
202 203 _ip.magic('reset -f out')
203 204 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
204 205 nt.assert_true(len(_ip.user_ns['Out']) == 0)
205 206
206 207 def test_reset_in():
207 208 "Test '%reset in' magic"
208 209 # test '%reset -f in'
209 210 _ip.run_cell("parrot", store_history=True)
210 211 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
211 212 _ip.magic('%reset -f in')
212 213 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
213 214 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
214 215
215 216 def test_reset_dhist():
216 217 "Test '%reset dhist' magic"
217 218 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
218 219 _ip.magic('cd ' + os.path.dirname(nt.__file__))
219 220 _ip.magic('cd -')
220 221 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
221 222 _ip.magic('reset -f dhist')
222 223 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
223 224 _ip.run_cell("_dh = [d for d in tmp]") #restore
224 225
225 226 def test_reset_in_length():
226 227 "Test that '%reset in' preserves In[] length"
227 228 _ip.run_cell("print 'foo'")
228 229 _ip.run_cell("reset -f in")
229 230 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
230 231
231 232 def test_time():
232 233 _ip.magic('time None')
233 234
234 235
235 236 @py3compat.doctest_refactor_print
236 237 def doctest_time():
237 238 """
238 239 In [10]: %time None
239 240 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
240 241 Wall time: 0.00 s
241 242
242 243 In [11]: def f(kmjy):
243 244 ....: %time print 2*kmjy
244 245
245 246 In [12]: f(3)
246 247 6
247 248 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
248 249 Wall time: 0.00 s
249 250 """
250 251
251 252
252 253 def test_doctest_mode():
253 254 "Toggle doctest_mode twice, it should be a no-op and run without error"
254 255 _ip.magic('doctest_mode')
255 256 _ip.magic('doctest_mode')
256 257
257 258
258 259 def test_parse_options():
259 260 """Tests for basic options parsing in magics."""
260 261 # These are only the most minimal of tests, more should be added later. At
261 262 # the very least we check that basic text/unicode calls work OK.
262 263 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
263 264 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
264 265
265 266
266 267 def test_dirops():
267 268 """Test various directory handling operations."""
268 269 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
269 270 curpath = os.getcwdu
270 271 startdir = os.getcwdu()
271 272 ipdir = os.path.realpath(_ip.ipython_dir)
272 273 try:
273 274 _ip.magic('cd "%s"' % ipdir)
274 275 nt.assert_equal(curpath(), ipdir)
275 276 _ip.magic('cd -')
276 277 nt.assert_equal(curpath(), startdir)
277 278 _ip.magic('pushd "%s"' % ipdir)
278 279 nt.assert_equal(curpath(), ipdir)
279 280 _ip.magic('popd')
280 281 nt.assert_equal(curpath(), startdir)
281 282 finally:
282 283 os.chdir(startdir)
283 284
284 285
285 286 def test_xmode():
286 287 # Calling xmode three times should be a no-op
287 288 xmode = _ip.InteractiveTB.mode
288 289 for i in range(3):
289 290 _ip.magic("xmode")
290 291 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
291 292
292 293 def test_reset_hard():
293 294 monitor = []
294 295 class A(object):
295 296 def __del__(self):
296 297 monitor.append(1)
297 298 def __repr__(self):
298 299 return "<A instance>"
299 300
300 301 _ip.user_ns["a"] = A()
301 302 _ip.run_cell("a")
302 303
303 304 nt.assert_equal(monitor, [])
304 305 _ip.magic_reset("-f")
305 306 nt.assert_equal(monitor, [1])
306 307
307 308 class TestXdel(tt.TempFileMixin):
308 309 def test_xdel(self):
309 310 """Test that references from %run are cleared by xdel."""
310 311 src = ("class A(object):\n"
311 312 " monitor = []\n"
312 313 " def __del__(self):\n"
313 314 " self.monitor.append(1)\n"
314 315 "a = A()\n")
315 316 self.mktmp(src)
316 317 # %run creates some hidden references...
317 318 _ip.magic("run %s" % self.fname)
318 319 # ... as does the displayhook.
319 320 _ip.run_cell("a")
320 321
321 322 monitor = _ip.user_ns["A"].monitor
322 323 nt.assert_equal(monitor, [])
323 324
324 325 _ip.magic("xdel a")
325 326
326 327 # Check that a's __del__ method has been called.
327 328 nt.assert_equal(monitor, [1])
328 329
329 330 def doctest_who():
330 331 """doctest for %who
331 332
332 333 In [1]: %reset -f
333 334
334 335 In [2]: alpha = 123
335 336
336 337 In [3]: beta = 'beta'
337 338
338 339 In [4]: %who int
339 340 alpha
340 341
341 342 In [5]: %who str
342 343 beta
343 344
344 345 In [6]: %whos
345 346 Variable Type Data/Info
346 347 ----------------------------
347 348 alpha int 123
348 349 beta str beta
349 350
350 351 In [7]: %who_ls
351 352 Out[7]: ['alpha', 'beta']
352 353 """
353 354
354 355 @py3compat.u_format
355 356 def doctest_precision():
356 357 """doctest for %precision
357 358
358 359 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
359 360
360 361 In [2]: %precision 5
361 362 Out[2]: {u}'%.5f'
362 363
363 364 In [3]: f.float_format
364 365 Out[3]: {u}'%.5f'
365 366
366 367 In [4]: %precision %e
367 368 Out[4]: {u}'%e'
368 369
369 370 In [5]: f(3.1415927)
370 371 Out[5]: {u}'3.141593e+00'
371 372 """
372 373
373 374 def test_psearch():
374 375 with tt.AssertPrints("dict.fromkeys"):
375 376 _ip.run_cell("dict.fr*?")
376 377
377 378 def test_timeit_shlex():
378 379 """test shlex issues with timeit (#1109)"""
379 380 _ip.ex("def f(*a,**kw): pass")
380 381 _ip.magic('timeit -n1 "this is a bug".count(" ")')
381 382 _ip.magic('timeit -r1 -n1 f(" ", 1)')
382 383 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
383 384 _ip.magic('timeit -r1 -n1 ("a " + "b")')
384 385 _ip.magic('timeit -r1 -n1 f("a " + "b")')
385 386 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
386 387
387 388
388 389 def test_timeit_arguments():
389 390 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
390 391 _ip.magic("timeit ('#')")
391 392
392 393 @dec.skipif(_ip.magic_prun == _ip.profile_missing_notice)
393 394 def test_prun_quotes():
394 395 "Test that prun does not clobber string escapes (GH #1302)"
395 396 _ip.magic("prun -q x = '\t'")
396 397 nt.assert_equal(_ip.user_ns['x'], '\t')
398
399 def test_extension():
400 tmpdir = TemporaryDirectory()
401 orig_ipython_dir = _ip.ipython_dir
402 try:
403 _ip.ipython_dir = tmpdir.name
404 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
405 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
406 _ip.magic("install_ext %s" % url)
407 _ip.user_ns.pop('arq', None)
408 _ip.magic("load_ext daft_extension")
409 tt.assert_equal(_ip.user_ns['arq'], 185)
410 _ip.magic("unload_ext daft_extension")
411 assert 'arq' not in _ip.user_ns
412 finally:
413 _ip.ipython_dir = orig_ipython_dir
414
General Comments 0
You need to be logged in to leave comments. Login now