##// END OF EJS Templates
Merge pull request #13206 from sgaist/nose_cleanup_first_step...
Matthias Bussonnier -
r26949:24290cb1 merge
parent child Browse files
Show More
@@ -0,0 +1,16 b''
1 # See https://pre-commit.com for more information
2 # See https://pre-commit.com/hooks.html for more hooks
3 repos:
4 - repo: https://github.com/pre-commit/pre-commit-hooks
5 rev: v3.2.0
6 hooks:
7 - id: trailing-whitespace
8 - id: end-of-file-fixer
9 - id: check-yaml
10 - id: check-added-large-files
11
12 - repo: https://github.com/akaihola/darker
13 rev: 1.3.1
14 hooks:
15 - id: darker
16
@@ -4,8 +4,6 b''
4 import os
4 import os
5 import tempfile
5 import tempfile
6
6
7 import nose.tools as nt
8
9 from traitlets import Unicode
7 from traitlets import Unicode
10
8
11 from IPython.core.application import BaseIPythonApplication
9 from IPython.core.application import BaseIPythonApplication
@@ -65,9 +63,8 b' def test_cli_priority():'
65 f.write("c.TestApp.test = 'config file'")
63 f.write("c.TestApp.test = 'config file'")
66
64
67 app = TestApp()
65 app = TestApp()
68 app.initialize(['--profile-dir', td])
66 app.initialize(["--profile-dir", td])
69 nt.assert_equal(app.test, 'config file')
67 assert app.test == "config file"
70 app = TestApp()
68 app = TestApp()
71 app.initialize(['--profile-dir', td, '--TestApp.test=cli'])
69 app.initialize(["--profile-dir", td, "--TestApp.test=cli"])
72 nt.assert_equal(app.test, 'cli')
70 assert app.test == "cli"
73
@@ -4,7 +4,6 b' Test for async helpers.'
4 Should only trigger on python 3.5+ or will have syntax errors.
4 Should only trigger on python 3.5+ or will have syntax errors.
5 """
5 """
6 from itertools import chain, repeat
6 from itertools import chain, repeat
7 import nose.tools as nt
8 from textwrap import dedent, indent
7 from textwrap import dedent, indent
9 from unittest import TestCase
8 from unittest import TestCase
10 from IPython.testing.decorators import skip_without
9 from IPython.testing.decorators import skip_without
@@ -24,10 +23,10 b' from IPython.core.async_helpers import _should_be_async'
24
23
25 class AsyncTest(TestCase):
24 class AsyncTest(TestCase):
26 def test_should_be_async(self):
25 def test_should_be_async(self):
27 nt.assert_false(_should_be_async("False"))
26 self.assertFalse(_should_be_async("False"))
28 nt.assert_true(_should_be_async("await bar()"))
27 self.assertTrue(_should_be_async("await bar()"))
29 nt.assert_true(_should_be_async("x = await bar()"))
28 self.assertTrue(_should_be_async("x = await bar()"))
30 nt.assert_false(
29 self.assertFalse(
31 _should_be_async(
30 _should_be_async(
32 dedent(
31 dedent(
33 """
32 """
@@ -298,7 +297,7 b' class AsyncTest(TestCase):'
298 import asyncio
297 import asyncio
299 await asyncio.sleep(0)
298 await asyncio.sleep(0)
300 """)
299 """)
301 with nt.assert_raises(TypeError):
300 with self.assertRaises(TypeError):
302 res.raise_error()
301 res.raise_error()
303
302
304 @skip_without('trio')
303 @skip_without('trio')
@@ -308,7 +307,7 b' class AsyncTest(TestCase):'
308 import trio
307 import trio
309 await trio.sleep(0)
308 await trio.sleep(0)
310 """)
309 """)
311 with nt.assert_raises(RuntimeError):
310 with self.assertRaises(RuntimeError):
312 res.raise_error()
311 res.raise_error()
313
312
314
313
@@ -11,8 +11,6 b' import unittest'
11
11
12 from contextlib import contextmanager
12 from contextlib import contextmanager
13
13
14 import nose.tools as nt
15
16 from traitlets.config.loader import Config
14 from traitlets.config.loader import Config
17 from IPython import get_ipython
15 from IPython import get_ipython
18 from IPython.core import completer
16 from IPython.core import completer
@@ -27,7 +25,6 b' from IPython.core.completer import ('
27 match_dict_keys,
25 match_dict_keys,
28 _deduplicate_completions,
26 _deduplicate_completions,
29 )
27 )
30 from nose.tools import assert_in, assert_not_in
31
28
32 # -----------------------------------------------------------------------------
29 # -----------------------------------------------------------------------------
33 # Test functions
30 # Test functions
@@ -150,7 +147,7 b' def test_protect_filename():'
150 # run the actual tests
147 # run the actual tests
151 for s1, s2 in pairs:
148 for s1, s2 in pairs:
152 s1p = completer.protect_filename(s1)
149 s1p = completer.protect_filename(s1)
153 nt.assert_equal(s1p, s2)
150 assert s1p == s2
154
151
155
152
156 def check_line_split(splitter, test_specs):
153 def check_line_split(splitter, test_specs):
@@ -158,7 +155,7 b' def check_line_split(splitter, test_specs):'
158 cursor_pos = len(part1)
155 cursor_pos = len(part1)
159 line = part1 + part2
156 line = part1 + part2
160 out = splitter.split_line(line, cursor_pos)
157 out = splitter.split_line(line, cursor_pos)
161 nt.assert_equal(out, split)
158 assert out == split
162
159
163
160
164 def test_line_split():
161 def test_line_split():
@@ -267,8 +264,8 b' class TestCompleter(unittest.TestCase):'
267 # should be thrown and the return value should be a pair of text, list
264 # should be thrown and the return value should be a pair of text, list
268 # values.
265 # values.
269 text, matches = ip.complete(t)
266 text, matches = ip.complete(t)
270 nt.assert_true(isinstance(text, str))
267 self.assertIsInstance(text, str)
271 nt.assert_true(isinstance(matches, list))
268 self.assertIsInstance(matches, list)
272
269
273 def test_latex_completions(self):
270 def test_latex_completions(self):
274 from IPython.core.latex_symbols import latex_symbols
271 from IPython.core.latex_symbols import latex_symbols
@@ -279,16 +276,16 b' class TestCompleter(unittest.TestCase):'
279 keys = random.sample(latex_symbols.keys(), 10)
276 keys = random.sample(latex_symbols.keys(), 10)
280 for k in keys:
277 for k in keys:
281 text, matches = ip.complete(k)
278 text, matches = ip.complete(k)
282 nt.assert_equal(text, k)
279 self.assertEqual(text, k)
283 nt.assert_equal(matches, [latex_symbols[k]])
280 self.assertEqual(matches, [latex_symbols[k]])
284 # Test a more complex line
281 # Test a more complex line
285 text, matches = ip.complete("print(\\alpha")
282 text, matches = ip.complete("print(\\alpha")
286 nt.assert_equal(text, "\\alpha")
283 self.assertEqual(text, "\\alpha")
287 nt.assert_equal(matches[0], latex_symbols["\\alpha"])
284 self.assertEqual(matches[0], latex_symbols["\\alpha"])
288 # Test multiple matching latex symbols
285 # Test multiple matching latex symbols
289 text, matches = ip.complete("\\al")
286 text, matches = ip.complete("\\al")
290 nt.assert_in("\\alpha", matches)
287 self.assertIn("\\alpha", matches)
291 nt.assert_in("\\aleph", matches)
288 self.assertIn("\\aleph", matches)
292
289
293 def test_latex_no_results(self):
290 def test_latex_no_results(self):
294 """
291 """
@@ -296,30 +293,30 b' class TestCompleter(unittest.TestCase):'
296 """
293 """
297 ip = get_ipython()
294 ip = get_ipython()
298 text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing")
295 text, matches = ip.Completer.latex_matches("\\really_i_should_match_nothing")
299 nt.assert_equal(text, "")
296 self.assertEqual(text, "")
300 nt.assert_equal(matches, ())
297 self.assertEqual(matches, ())
301
298
302 def test_back_latex_completion(self):
299 def test_back_latex_completion(self):
303 ip = get_ipython()
300 ip = get_ipython()
304
301
305 # do not return more than 1 matches for \beta, only the latex one.
302 # do not return more than 1 matches for \beta, only the latex one.
306 name, matches = ip.complete("\\β")
303 name, matches = ip.complete("\\β")
307 nt.assert_equal(matches, ['\\beta'])
304 self.assertEqual(matches, ["\\beta"])
308
305
309 def test_back_unicode_completion(self):
306 def test_back_unicode_completion(self):
310 ip = get_ipython()
307 ip = get_ipython()
311
308
312 name, matches = ip.complete("\\Ⅴ")
309 name, matches = ip.complete("\\Ⅴ")
313 nt.assert_equal(matches, ("\\ROMAN NUMERAL FIVE",))
310 self.assertEqual(matches, ("\\ROMAN NUMERAL FIVE",))
314
311
315 def test_forward_unicode_completion(self):
312 def test_forward_unicode_completion(self):
316 ip = get_ipython()
313 ip = get_ipython()
317
314
318 name, matches = ip.complete("\\ROMAN NUMERAL FIVE")
315 name, matches = ip.complete("\\ROMAN NUMERAL FIVE")
319 nt.assert_equal(matches, ["Ⅴ"] ) # This is not a V
316 self.assertEqual(matches, ["Ⅴ"]) # This is not a V
320 nt.assert_equal(matches, ["\u2164"] ) # same as above but explicit.
317 self.assertEqual(matches, ["\u2164"]) # same as above but explicit.
321
318
322 @nt.nottest # now we have a completion for \jmath
319 @unittest.skip("now we have a completion for \jmath")
323 @decorators.knownfailureif(
320 @decorators.knownfailureif(
324 sys.platform == "win32", "Fails if there is a C:\\j... path"
321 sys.platform == "win32", "Fails if there is a C:\\j... path"
325 )
322 )
@@ -329,7 +326,7 b' class TestCompleter(unittest.TestCase):'
329 # single ascii letter that don't have yet completions
326 # single ascii letter that don't have yet completions
330 for letter in "jJ":
327 for letter in "jJ":
331 name, matches = ip.complete("\\" + letter)
328 name, matches = ip.complete("\\" + letter)
332 nt.assert_equal(matches, [])
329 self.assertEqual(matches, [])
333
330
334 class CompletionSplitterTestCase(unittest.TestCase):
331 class CompletionSplitterTestCase(unittest.TestCase):
335 def setUp(self):
332 def setUp(self):
@@ -337,8 +334,8 b' class TestCompleter(unittest.TestCase):'
337
334
338 def test_delim_setting(self):
335 def test_delim_setting(self):
339 self.sp.delims = " "
336 self.sp.delims = " "
340 nt.assert_equal(self.sp.delims, " ")
337 self.assertEqual(self.sp.delims, " ")
341 nt.assert_equal(self.sp._delim_expr, r"[\ ]")
338 self.assertEqual(self.sp._delim_expr, r"[\ ]")
342
339
343 def test_spaces(self):
340 def test_spaces(self):
344 """Test with only spaces as split chars."""
341 """Test with only spaces as split chars."""
@@ -348,19 +345,19 b' class TestCompleter(unittest.TestCase):'
348
345
349 def test_has_open_quotes1(self):
346 def test_has_open_quotes1(self):
350 for s in ["'", "'''", "'hi' '"]:
347 for s in ["'", "'''", "'hi' '"]:
351 nt.assert_equal(completer.has_open_quotes(s), "'")
348 self.assertEqual(completer.has_open_quotes(s), "'")
352
349
353 def test_has_open_quotes2(self):
350 def test_has_open_quotes2(self):
354 for s in ['"', '"""', '"hi" "']:
351 for s in ['"', '"""', '"hi" "']:
355 nt.assert_equal(completer.has_open_quotes(s), '"')
352 self.assertEqual(completer.has_open_quotes(s), '"')
356
353
357 def test_has_open_quotes3(self):
354 def test_has_open_quotes3(self):
358 for s in ["''", "''' '''", "'hi' 'ipython'"]:
355 for s in ["''", "''' '''", "'hi' 'ipython'"]:
359 nt.assert_false(completer.has_open_quotes(s))
356 self.assertFalse(completer.has_open_quotes(s))
360
357
361 def test_has_open_quotes4(self):
358 def test_has_open_quotes4(self):
362 for s in ['""', '""" """', '"hi" "ipython"']:
359 for s in ['""', '""" """', '"hi" "ipython"']:
363 nt.assert_false(completer.has_open_quotes(s))
360 self.assertFalse(completer.has_open_quotes(s))
364
361
365 @decorators.knownfailureif(
362 @decorators.knownfailureif(
366 sys.platform == "win32", "abspath completions fail on Windows"
363 sys.platform == "win32", "abspath completions fail on Windows"
@@ -376,13 +373,13 b' class TestCompleter(unittest.TestCase):'
376
373
377 # Check simple completion
374 # Check simple completion
378 c = ip.complete(prefix)[1]
375 c = ip.complete(prefix)[1]
379 nt.assert_equal(c, names)
376 self.assertEqual(c, names)
380
377
381 # Now check with a function call
378 # Now check with a function call
382 cmd = 'a = f("%s' % prefix
379 cmd = 'a = f("%s' % prefix
383 c = ip.complete(prefix, cmd)[1]
380 c = ip.complete(prefix, cmd)[1]
384 comp = [prefix + s for s in suffixes]
381 comp = [prefix + s for s in suffixes]
385 nt.assert_equal(c, comp)
382 self.assertEqual(c, comp)
386
383
387 def test_local_file_completions(self):
384 def test_local_file_completions(self):
388 ip = get_ipython()
385 ip = get_ipython()
@@ -395,13 +392,13 b' class TestCompleter(unittest.TestCase):'
395
392
396 # Check simple completion
393 # Check simple completion
397 c = ip.complete(prefix)[1]
394 c = ip.complete(prefix)[1]
398 nt.assert_equal(c, names)
395 self.assertEqual(c, names)
399
396
400 # Now check with a function call
397 # Now check with a function call
401 cmd = 'a = f("%s' % prefix
398 cmd = 'a = f("%s' % prefix
402 c = ip.complete(prefix, cmd)[1]
399 c = ip.complete(prefix, cmd)[1]
403 comp = {prefix + s for s in suffixes}
400 comp = {prefix + s for s in suffixes}
404 nt.assert_true(comp.issubset(set(c)))
401 self.assertTrue(comp.issubset(set(c)))
405
402
406 def test_quoted_file_completions(self):
403 def test_quoted_file_completions(self):
407 ip = get_ipython()
404 ip = get_ipython()
@@ -417,21 +414,21 b' class TestCompleter(unittest.TestCase):'
417 c = ip.Completer._complete(
414 c = ip.Completer._complete(
418 cursor_line=0, cursor_pos=len(text), full_text=text
415 cursor_line=0, cursor_pos=len(text), full_text=text
419 )[1]
416 )[1]
420 nt.assert_equal(c, [escaped])
417 self.assertEqual(c, [escaped])
421
418
422 # Double quote requires no escape
419 # Double quote requires no escape
423 text = 'open("foo'
420 text = 'open("foo'
424 c = ip.Completer._complete(
421 c = ip.Completer._complete(
425 cursor_line=0, cursor_pos=len(text), full_text=text
422 cursor_line=0, cursor_pos=len(text), full_text=text
426 )[1]
423 )[1]
427 nt.assert_equal(c, [name])
424 self.assertEqual(c, [name])
428
425
429 # No quote requires an escape
426 # No quote requires an escape
430 text = "%ls foo"
427 text = "%ls foo"
431 c = ip.Completer._complete(
428 c = ip.Completer._complete(
432 cursor_line=0, cursor_pos=len(text), full_text=text
429 cursor_line=0, cursor_pos=len(text), full_text=text
433 )[1]
430 )[1]
434 nt.assert_equal(c, [escaped])
431 self.assertEqual(c, [escaped])
435
432
436 def test_all_completions_dups(self):
433 def test_all_completions_dups(self):
437 """
434 """
@@ -537,18 +534,18 b' class TestCompleter(unittest.TestCase):'
537 ip = get_ipython()
534 ip = get_ipython()
538 ip.ex("a=list(range(5))")
535 ip.ex("a=list(range(5))")
539 _, c = ip.complete(".", line="a[0].")
536 _, c = ip.complete(".", line="a[0].")
540 nt.assert_false(".real" in c, "Shouldn't have completed on a[0]: %s" % c)
537 self.assertFalse(".real" in c, "Shouldn't have completed on a[0]: %s" % c)
541
538
542 def _(line, cursor_pos, expect, message, completion):
539 def _(line, cursor_pos, expect, message, completion):
543 with greedy_completion(), provisionalcompleter():
540 with greedy_completion(), provisionalcompleter():
544 ip.Completer.use_jedi = False
541 ip.Completer.use_jedi = False
545 _, c = ip.complete(".", line=line, cursor_pos=cursor_pos)
542 _, c = ip.complete(".", line=line, cursor_pos=cursor_pos)
546 nt.assert_in(expect, c, message % c)
543 self.assertIn(expect, c, message % c)
547
544
548 ip.Completer.use_jedi = True
545 ip.Completer.use_jedi = True
549 with provisionalcompleter():
546 with provisionalcompleter():
550 completions = ip.Completer.completions(line, cursor_pos)
547 completions = ip.Completer.completions(line, cursor_pos)
551 nt.assert_in(completion, completions)
548 self.assertIn(completion, completions)
552
549
553 with provisionalcompleter():
550 with provisionalcompleter():
554 yield _, "a[0].", 5, "a[0].real", "Should have completed on a[0].: %s", Completion(
551 yield _, "a[0].", 5, "a[0].real", "Should have completed on a[0].: %s", Completion(
@@ -575,13 +572,13 b' class TestCompleter(unittest.TestCase):'
575 with provisionalcompleter():
572 with provisionalcompleter():
576 c.use_jedi = False
573 c.use_jedi = False
577 s, matches = c.complete("ip.")
574 s, matches = c.complete("ip.")
578 nt.assert_in("ip.__str__", matches)
575 self.assertIn("ip.__str__", matches)
579 nt.assert_in("ip._hidden_attr", matches)
576 self.assertIn("ip._hidden_attr", matches)
580
577
581 # c.use_jedi = True
578 # c.use_jedi = True
582 # completions = set(c.completions('ip.', 3))
579 # completions = set(c.completions('ip.', 3))
583 # nt.assert_in(Completion(3, 3, '__str__'), completions)
580 # self.assertIn(Completion(3, 3, '__str__'), completions)
584 # nt.assert_in(Completion(3,3, "_hidden_attr"), completions)
581 # self.assertIn(Completion(3,3, "_hidden_attr"), completions)
585
582
586 cfg = Config()
583 cfg = Config()
587 cfg.IPCompleter.omit__names = 1
584 cfg.IPCompleter.omit__names = 1
@@ -589,13 +586,13 b' class TestCompleter(unittest.TestCase):'
589 with provisionalcompleter():
586 with provisionalcompleter():
590 c.use_jedi = False
587 c.use_jedi = False
591 s, matches = c.complete("ip.")
588 s, matches = c.complete("ip.")
592 nt.assert_not_in("ip.__str__", matches)
589 self.assertNotIn("ip.__str__", matches)
593 # nt.assert_in('ip._hidden_attr', matches)
590 # self.assertIn('ip._hidden_attr', matches)
594
591
595 # c.use_jedi = True
592 # c.use_jedi = True
596 # completions = set(c.completions('ip.', 3))
593 # completions = set(c.completions('ip.', 3))
597 # nt.assert_not_in(Completion(3,3,'__str__'), completions)
594 # self.assertNotIn(Completion(3,3,'__str__'), completions)
598 # nt.assert_in(Completion(3,3, "_hidden_attr"), completions)
595 # self.assertIn(Completion(3,3, "_hidden_attr"), completions)
599
596
600 cfg = Config()
597 cfg = Config()
601 cfg.IPCompleter.omit__names = 2
598 cfg.IPCompleter.omit__names = 2
@@ -603,22 +600,22 b' class TestCompleter(unittest.TestCase):'
603 with provisionalcompleter():
600 with provisionalcompleter():
604 c.use_jedi = False
601 c.use_jedi = False
605 s, matches = c.complete("ip.")
602 s, matches = c.complete("ip.")
606 nt.assert_not_in("ip.__str__", matches)
603 self.assertNotIn("ip.__str__", matches)
607 nt.assert_not_in("ip._hidden_attr", matches)
604 self.assertNotIn("ip._hidden_attr", matches)
608
605
609 # c.use_jedi = True
606 # c.use_jedi = True
610 # completions = set(c.completions('ip.', 3))
607 # completions = set(c.completions('ip.', 3))
611 # nt.assert_not_in(Completion(3,3,'__str__'), completions)
608 # self.assertNotIn(Completion(3,3,'__str__'), completions)
612 # nt.assert_not_in(Completion(3,3, "_hidden_attr"), completions)
609 # self.assertNotIn(Completion(3,3, "_hidden_attr"), completions)
613
610
614 with provisionalcompleter():
611 with provisionalcompleter():
615 c.use_jedi = False
612 c.use_jedi = False
616 s, matches = c.complete("ip._x.")
613 s, matches = c.complete("ip._x.")
617 nt.assert_in("ip._x.keys", matches)
614 self.assertIn("ip._x.keys", matches)
618
615
619 # c.use_jedi = True
616 # c.use_jedi = True
620 # completions = set(c.completions('ip._x.', 6))
617 # completions = set(c.completions('ip._x.', 6))
621 # nt.assert_in(Completion(6,6, "keys"), completions)
618 # self.assertIn(Completion(6,6, "keys"), completions)
622
619
623 del ip._hidden_attr
620 del ip._hidden_attr
624 del ip._x
621 del ip._x
@@ -636,21 +633,21 b' class TestCompleter(unittest.TestCase):'
636 cfg.IPCompleter.limit_to__all__ = False
633 cfg.IPCompleter.limit_to__all__ = False
637 c.update_config(cfg)
634 c.update_config(cfg)
638 s, matches = c.complete("d.")
635 s, matches = c.complete("d.")
639 nt.assert_in("d.x", matches)
636 self.assertIn("d.x", matches)
640
637
641 def test_get__all__entries_ok(self):
638 def test_get__all__entries_ok(self):
642 class A:
639 class A:
643 __all__ = ["x", 1]
640 __all__ = ["x", 1]
644
641
645 words = completer.get__all__entries(A())
642 words = completer.get__all__entries(A())
646 nt.assert_equal(words, ["x"])
643 self.assertEqual(words, ["x"])
647
644
648 def test_get__all__entries_no__all__ok(self):
645 def test_get__all__entries_no__all__ok(self):
649 class A:
646 class A:
650 pass
647 pass
651
648
652 words = completer.get__all__entries(A())
649 words = completer.get__all__entries(A())
653 nt.assert_equal(words, [])
650 self.assertEqual(words, [])
654
651
655 def test_func_kw_completions(self):
652 def test_func_kw_completions(self):
656 ip = get_ipython()
653 ip = get_ipython()
@@ -658,39 +655,39 b' class TestCompleter(unittest.TestCase):'
658 c.use_jedi = False
655 c.use_jedi = False
659 ip.ex("def myfunc(a=1,b=2): return a+b")
656 ip.ex("def myfunc(a=1,b=2): return a+b")
660 s, matches = c.complete(None, "myfunc(1,b")
657 s, matches = c.complete(None, "myfunc(1,b")
661 nt.assert_in("b=", matches)
658 self.assertIn("b=", matches)
662 # Simulate completing with cursor right after b (pos==10):
659 # Simulate completing with cursor right after b (pos==10):
663 s, matches = c.complete(None, "myfunc(1,b)", 10)
660 s, matches = c.complete(None, "myfunc(1,b)", 10)
664 nt.assert_in("b=", matches)
661 self.assertIn("b=", matches)
665 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
662 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
666 nt.assert_in("b=", matches)
663 self.assertIn("b=", matches)
667 # builtin function
664 # builtin function
668 s, matches = c.complete(None, "min(k, k")
665 s, matches = c.complete(None, "min(k, k")
669 nt.assert_in("key=", matches)
666 self.assertIn("key=", matches)
670
667
671 def test_default_arguments_from_docstring(self):
668 def test_default_arguments_from_docstring(self):
672 ip = get_ipython()
669 ip = get_ipython()
673 c = ip.Completer
670 c = ip.Completer
674 kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value")
671 kwd = c._default_arguments_from_docstring("min(iterable[, key=func]) -> value")
675 nt.assert_equal(kwd, ["key"])
672 self.assertEqual(kwd, ["key"])
676 # with cython type etc
673 # with cython type etc
677 kwd = c._default_arguments_from_docstring(
674 kwd = c._default_arguments_from_docstring(
678 "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
675 "Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
679 )
676 )
680 nt.assert_equal(kwd, ["ncall", "resume", "nsplit"])
677 self.assertEqual(kwd, ["ncall", "resume", "nsplit"])
681 # white spaces
678 # white spaces
682 kwd = c._default_arguments_from_docstring(
679 kwd = c._default_arguments_from_docstring(
683 "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
680 "\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n"
684 )
681 )
685 nt.assert_equal(kwd, ["ncall", "resume", "nsplit"])
682 self.assertEqual(kwd, ["ncall", "resume", "nsplit"])
686
683
687 def test_line_magics(self):
684 def test_line_magics(self):
688 ip = get_ipython()
685 ip = get_ipython()
689 c = ip.Completer
686 c = ip.Completer
690 s, matches = c.complete(None, "lsmag")
687 s, matches = c.complete(None, "lsmag")
691 nt.assert_in("%lsmagic", matches)
688 self.assertIn("%lsmagic", matches)
692 s, matches = c.complete(None, "%lsmag")
689 s, matches = c.complete(None, "%lsmag")
693 nt.assert_in("%lsmagic", matches)
690 self.assertIn("%lsmagic", matches)
694
691
695 def test_cell_magics(self):
692 def test_cell_magics(self):
696 from IPython.core.magic import register_cell_magic
693 from IPython.core.magic import register_cell_magic
@@ -703,9 +700,9 b' class TestCompleter(unittest.TestCase):'
703 c = ip.Completer
700 c = ip.Completer
704
701
705 s, matches = c.complete(None, "_foo_ce")
702 s, matches = c.complete(None, "_foo_ce")
706 nt.assert_in("%%_foo_cellm", matches)
703 self.assertIn("%%_foo_cellm", matches)
707 s, matches = c.complete(None, "%%_foo_ce")
704 s, matches = c.complete(None, "%%_foo_ce")
708 nt.assert_in("%%_foo_cellm", matches)
705 self.assertIn("%%_foo_cellm", matches)
709
706
710 def test_line_cell_magics(self):
707 def test_line_cell_magics(self):
711 from IPython.core.magic import register_line_cell_magic
708 from IPython.core.magic import register_line_cell_magic
@@ -722,14 +719,14 b' class TestCompleter(unittest.TestCase):'
722 # and this will show a difference if the same name is both a line and cell
719 # and this will show a difference if the same name is both a line and cell
723 # magic.
720 # magic.
724 s, matches = c.complete(None, "_bar_ce")
721 s, matches = c.complete(None, "_bar_ce")
725 nt.assert_in("%_bar_cellm", matches)
722 self.assertIn("%_bar_cellm", matches)
726 nt.assert_in("%%_bar_cellm", matches)
723 self.assertIn("%%_bar_cellm", matches)
727 s, matches = c.complete(None, "%_bar_ce")
724 s, matches = c.complete(None, "%_bar_ce")
728 nt.assert_in("%_bar_cellm", matches)
725 self.assertIn("%_bar_cellm", matches)
729 nt.assert_in("%%_bar_cellm", matches)
726 self.assertIn("%%_bar_cellm", matches)
730 s, matches = c.complete(None, "%%_bar_ce")
727 s, matches = c.complete(None, "%%_bar_ce")
731 nt.assert_not_in("%_bar_cellm", matches)
728 self.assertNotIn("%_bar_cellm", matches)
732 nt.assert_in("%%_bar_cellm", matches)
729 self.assertIn("%%_bar_cellm", matches)
733
730
734 def test_magic_completion_order(self):
731 def test_magic_completion_order(self):
735 ip = get_ipython()
732 ip = get_ipython()
@@ -737,7 +734,7 b' class TestCompleter(unittest.TestCase):'
737
734
738 # Test ordering of line and cell magics.
735 # Test ordering of line and cell magics.
739 text, matches = c.complete("timeit")
736 text, matches = c.complete("timeit")
740 nt.assert_equal(matches, ["%timeit", "%%timeit"])
737 self.assertEqual(matches, ["%timeit", "%%timeit"])
741
738
742 def test_magic_completion_shadowing(self):
739 def test_magic_completion_shadowing(self):
743 ip = get_ipython()
740 ip = get_ipython()
@@ -746,18 +743,18 b' class TestCompleter(unittest.TestCase):'
746
743
747 # Before importing matplotlib, %matplotlib magic should be the only option.
744 # Before importing matplotlib, %matplotlib magic should be the only option.
748 text, matches = c.complete("mat")
745 text, matches = c.complete("mat")
749 nt.assert_equal(matches, ["%matplotlib"])
746 self.assertEqual(matches, ["%matplotlib"])
750
747
751 # The newly introduced name should shadow the magic.
748 # The newly introduced name should shadow the magic.
752 ip.run_cell("matplotlib = 1")
749 ip.run_cell("matplotlib = 1")
753 text, matches = c.complete("mat")
750 text, matches = c.complete("mat")
754 nt.assert_equal(matches, ["matplotlib"])
751 self.assertEqual(matches, ["matplotlib"])
755
752
756 # After removing matplotlib from namespace, the magic should again be
753 # After removing matplotlib from namespace, the magic should again be
757 # the only option.
754 # the only option.
758 del ip.user_ns["matplotlib"]
755 del ip.user_ns["matplotlib"]
759 text, matches = c.complete("mat")
756 text, matches = c.complete("mat")
760 nt.assert_equal(matches, ["%matplotlib"])
757 self.assertEqual(matches, ["%matplotlib"])
761
758
762 def test_magic_completion_shadowing_explicit(self):
759 def test_magic_completion_shadowing_explicit(self):
763 """
760 """
@@ -769,62 +766,62 b' class TestCompleter(unittest.TestCase):'
769
766
770 # Before importing matplotlib, %matplotlib magic should be the only option.
767 # Before importing matplotlib, %matplotlib magic should be the only option.
771 text, matches = c.complete("%mat")
768 text, matches = c.complete("%mat")
772 nt.assert_equal(matches, ["%matplotlib"])
769 self.assertEqual(matches, ["%matplotlib"])
773
770
774 ip.run_cell("matplotlib = 1")
771 ip.run_cell("matplotlib = 1")
775
772
776 # After removing matplotlib from namespace, the magic should still be
773 # After removing matplotlib from namespace, the magic should still be
777 # the only option.
774 # the only option.
778 text, matches = c.complete("%mat")
775 text, matches = c.complete("%mat")
779 nt.assert_equal(matches, ["%matplotlib"])
776 self.assertEqual(matches, ["%matplotlib"])
780
777
781 def test_magic_config(self):
778 def test_magic_config(self):
782 ip = get_ipython()
779 ip = get_ipython()
783 c = ip.Completer
780 c = ip.Completer
784
781
785 s, matches = c.complete(None, "conf")
782 s, matches = c.complete(None, "conf")
786 nt.assert_in("%config", matches)
783 self.assertIn("%config", matches)
787 s, matches = c.complete(None, "conf")
784 s, matches = c.complete(None, "conf")
788 nt.assert_not_in("AliasManager", matches)
785 self.assertNotIn("AliasManager", matches)
789 s, matches = c.complete(None, "config ")
786 s, matches = c.complete(None, "config ")
790 nt.assert_in("AliasManager", matches)
787 self.assertIn("AliasManager", matches)
791 s, matches = c.complete(None, "%config ")
788 s, matches = c.complete(None, "%config ")
792 nt.assert_in("AliasManager", matches)
789 self.assertIn("AliasManager", matches)
793 s, matches = c.complete(None, "config Ali")
790 s, matches = c.complete(None, "config Ali")
794 nt.assert_list_equal(["AliasManager"], matches)
791 self.assertListEqual(["AliasManager"], matches)
795 s, matches = c.complete(None, "%config Ali")
792 s, matches = c.complete(None, "%config Ali")
796 nt.assert_list_equal(["AliasManager"], matches)
793 self.assertListEqual(["AliasManager"], matches)
797 s, matches = c.complete(None, "config AliasManager")
794 s, matches = c.complete(None, "config AliasManager")
798 nt.assert_list_equal(["AliasManager"], matches)
795 self.assertListEqual(["AliasManager"], matches)
799 s, matches = c.complete(None, "%config AliasManager")
796 s, matches = c.complete(None, "%config AliasManager")
800 nt.assert_list_equal(["AliasManager"], matches)
797 self.assertListEqual(["AliasManager"], matches)
801 s, matches = c.complete(None, "config AliasManager.")
798 s, matches = c.complete(None, "config AliasManager.")
802 nt.assert_in("AliasManager.default_aliases", matches)
799 self.assertIn("AliasManager.default_aliases", matches)
803 s, matches = c.complete(None, "%config AliasManager.")
800 s, matches = c.complete(None, "%config AliasManager.")
804 nt.assert_in("AliasManager.default_aliases", matches)
801 self.assertIn("AliasManager.default_aliases", matches)
805 s, matches = c.complete(None, "config AliasManager.de")
802 s, matches = c.complete(None, "config AliasManager.de")
806 nt.assert_list_equal(["AliasManager.default_aliases"], matches)
803 self.assertListEqual(["AliasManager.default_aliases"], matches)
807 s, matches = c.complete(None, "config AliasManager.de")
804 s, matches = c.complete(None, "config AliasManager.de")
808 nt.assert_list_equal(["AliasManager.default_aliases"], matches)
805 self.assertListEqual(["AliasManager.default_aliases"], matches)
809
806
810 def test_magic_color(self):
807 def test_magic_color(self):
811 ip = get_ipython()
808 ip = get_ipython()
812 c = ip.Completer
809 c = ip.Completer
813
810
814 s, matches = c.complete(None, "colo")
811 s, matches = c.complete(None, "colo")
815 nt.assert_in("%colors", matches)
812 self.assertIn("%colors", matches)
816 s, matches = c.complete(None, "colo")
813 s, matches = c.complete(None, "colo")
817 nt.assert_not_in("NoColor", matches)
814 self.assertNotIn("NoColor", matches)
818 s, matches = c.complete(None, "%colors") # No trailing space
815 s, matches = c.complete(None, "%colors") # No trailing space
819 nt.assert_not_in("NoColor", matches)
816 self.assertNotIn("NoColor", matches)
820 s, matches = c.complete(None, "colors ")
817 s, matches = c.complete(None, "colors ")
821 nt.assert_in("NoColor", matches)
818 self.assertIn("NoColor", matches)
822 s, matches = c.complete(None, "%colors ")
819 s, matches = c.complete(None, "%colors ")
823 nt.assert_in("NoColor", matches)
820 self.assertIn("NoColor", matches)
824 s, matches = c.complete(None, "colors NoCo")
821 s, matches = c.complete(None, "colors NoCo")
825 nt.assert_list_equal(["NoColor"], matches)
822 self.assertListEqual(["NoColor"], matches)
826 s, matches = c.complete(None, "%colors NoCo")
823 s, matches = c.complete(None, "%colors NoCo")
827 nt.assert_list_equal(["NoColor"], matches)
824 self.assertListEqual(["NoColor"], matches)
828
825
829 def test_match_dict_keys(self):
826 def test_match_dict_keys(self):
830 """
827 """
@@ -884,34 +881,34 b' class TestCompleter(unittest.TestCase):'
884
881
885 # check completion at different stages
882 # check completion at different stages
886 _, matches = complete(line_buffer="d[")
883 _, matches = complete(line_buffer="d[")
887 nt.assert_in("'abc'", matches)
884 self.assertIn("'abc'", matches)
888 nt.assert_not_in("'abc']", matches)
885 self.assertNotIn("'abc']", matches)
889
886
890 _, matches = complete(line_buffer="d['")
887 _, matches = complete(line_buffer="d['")
891 nt.assert_in("abc", matches)
888 self.assertIn("abc", matches)
892 nt.assert_not_in("abc']", matches)
889 self.assertNotIn("abc']", matches)
893
890
894 _, matches = complete(line_buffer="d['a")
891 _, matches = complete(line_buffer="d['a")
895 nt.assert_in("abc", matches)
892 self.assertIn("abc", matches)
896 nt.assert_not_in("abc']", matches)
893 self.assertNotIn("abc']", matches)
897
894
898 # check use of different quoting
895 # check use of different quoting
899 _, matches = complete(line_buffer='d["')
896 _, matches = complete(line_buffer='d["')
900 nt.assert_in("abc", matches)
897 self.assertIn("abc", matches)
901 nt.assert_not_in('abc"]', matches)
898 self.assertNotIn('abc"]', matches)
902
899
903 _, matches = complete(line_buffer='d["a')
900 _, matches = complete(line_buffer='d["a')
904 nt.assert_in("abc", matches)
901 self.assertIn("abc", matches)
905 nt.assert_not_in('abc"]', matches)
902 self.assertNotIn('abc"]', matches)
906
903
907 # check sensitivity to following context
904 # check sensitivity to following context
908 _, matches = complete(line_buffer="d[]", cursor_pos=2)
905 _, matches = complete(line_buffer="d[]", cursor_pos=2)
909 nt.assert_in("'abc'", matches)
906 self.assertIn("'abc'", matches)
910
907
911 _, matches = complete(line_buffer="d['']", cursor_pos=3)
908 _, matches = complete(line_buffer="d['']", cursor_pos=3)
912 nt.assert_in("abc", matches)
909 self.assertIn("abc", matches)
913 nt.assert_not_in("abc'", matches)
910 self.assertNotIn("abc'", matches)
914 nt.assert_not_in("abc']", matches)
911 self.assertNotIn("abc']", matches)
915
912
916 # check multiple solutions are correctly returned and that noise is not
913 # check multiple solutions are correctly returned and that noise is not
917 ip.user_ns["d"] = {
914 ip.user_ns["d"] = {
@@ -925,111 +922,110 b' class TestCompleter(unittest.TestCase):'
925 }
922 }
926
923
927 _, matches = complete(line_buffer="d['a")
924 _, matches = complete(line_buffer="d['a")
928 nt.assert_in("abc", matches)
925 self.assertIn("abc", matches)
929 nt.assert_in("abd", matches)
926 self.assertIn("abd", matches)
930 nt.assert_not_in("bad", matches)
927 self.assertNotIn("bad", matches)
931 nt.assert_not_in("abe", matches)
928 self.assertNotIn("abe", matches)
932 nt.assert_not_in("abf", matches)
929 self.assertNotIn("abf", matches)
933 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
930 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
934
931
935 # check escaping and whitespace
932 # check escaping and whitespace
936 ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None}
933 ip.user_ns["d"] = {"a\nb": None, "a'b": None, 'a"b': None, "a word": None}
937 _, matches = complete(line_buffer="d['a")
934 _, matches = complete(line_buffer="d['a")
938 nt.assert_in("a\\nb", matches)
935 self.assertIn("a\\nb", matches)
939 nt.assert_in("a\\'b", matches)
936 self.assertIn("a\\'b", matches)
940 nt.assert_in('a"b', matches)
937 self.assertIn('a"b', matches)
941 nt.assert_in("a word", matches)
938 self.assertIn("a word", matches)
942 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
939 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
943
940
944 # - can complete on non-initial word of the string
941 # - can complete on non-initial word of the string
945 _, matches = complete(line_buffer="d['a w")
942 _, matches = complete(line_buffer="d['a w")
946 nt.assert_in("word", matches)
943 self.assertIn("word", matches)
947
944
948 # - understands quote escaping
945 # - understands quote escaping
949 _, matches = complete(line_buffer="d['a\\'")
946 _, matches = complete(line_buffer="d['a\\'")
950 nt.assert_in("b", matches)
947 self.assertIn("b", matches)
951
948
952 # - default quoting should work like repr
949 # - default quoting should work like repr
953 _, matches = complete(line_buffer="d[")
950 _, matches = complete(line_buffer="d[")
954 nt.assert_in('"a\'b"', matches)
951 self.assertIn('"a\'b"', matches)
955
952
956 # - when opening quote with ", possible to match with unescaped apostrophe
953 # - when opening quote with ", possible to match with unescaped apostrophe
957 _, matches = complete(line_buffer="d[\"a'")
954 _, matches = complete(line_buffer="d[\"a'")
958 nt.assert_in("b", matches)
955 self.assertIn("b", matches)
959
956
960 # need to not split at delims that readline won't split at
957 # need to not split at delims that readline won't split at
961 if "-" not in ip.Completer.splitter.delims:
958 if "-" not in ip.Completer.splitter.delims:
962 ip.user_ns["d"] = {"before-after": None}
959 ip.user_ns["d"] = {"before-after": None}
963 _, matches = complete(line_buffer="d['before-af")
960 _, matches = complete(line_buffer="d['before-af")
964 nt.assert_in("before-after", matches)
961 self.assertIn("before-after", matches)
965
962
966 # check completion on tuple-of-string keys at different stage - on first key
963 # check completion on tuple-of-string keys at different stage - on first key
967 ip.user_ns["d"] = {('foo', 'bar'): None}
964 ip.user_ns["d"] = {('foo', 'bar'): None}
968 _, matches = complete(line_buffer="d[")
965 _, matches = complete(line_buffer="d[")
969 nt.assert_in("'foo'", matches)
966 self.assertIn("'foo'", matches)
970 nt.assert_not_in("'foo']", matches)
967 self.assertNotIn("'foo']", matches)
971 nt.assert_not_in("'bar'", matches)
968 self.assertNotIn("'bar'", matches)
972 nt.assert_not_in("foo", matches)
969 self.assertNotIn("foo", matches)
973 nt.assert_not_in("bar", matches)
970 self.assertNotIn("bar", matches)
974
971
975 # - match the prefix
972 # - match the prefix
976 _, matches = complete(line_buffer="d['f")
973 _, matches = complete(line_buffer="d['f")
977 nt.assert_in("foo", matches)
974 self.assertIn("foo", matches)
978 nt.assert_not_in("foo']", matches)
975 self.assertNotIn("foo']", matches)
979 nt.assert_not_in("foo\"]", matches)
976 self.assertNotIn('foo"]', matches)
980 _, matches = complete(line_buffer="d['foo")
977 _, matches = complete(line_buffer="d['foo")
981 nt.assert_in("foo", matches)
978 self.assertIn("foo", matches)
982
979
983 # - can complete on second key
980 # - can complete on second key
984 _, matches = complete(line_buffer="d['foo', ")
981 _, matches = complete(line_buffer="d['foo', ")
985 nt.assert_in("'bar'", matches)
982 self.assertIn("'bar'", matches)
986 _, matches = complete(line_buffer="d['foo', 'b")
983 _, matches = complete(line_buffer="d['foo', 'b")
987 nt.assert_in("bar", matches)
984 self.assertIn("bar", matches)
988 nt.assert_not_in("foo", matches)
985 self.assertNotIn("foo", matches)
989
986
990 # - does not propose missing keys
987 # - does not propose missing keys
991 _, matches = complete(line_buffer="d['foo', 'f")
988 _, matches = complete(line_buffer="d['foo', 'f")
992 nt.assert_not_in("bar", matches)
989 self.assertNotIn("bar", matches)
993 nt.assert_not_in("foo", matches)
990 self.assertNotIn("foo", matches)
994
991
995 # check sensitivity to following context
992 # check sensitivity to following context
996 _, matches = complete(line_buffer="d['foo',]", cursor_pos=8)
993 _, matches = complete(line_buffer="d['foo',]", cursor_pos=8)
997 nt.assert_in("'bar'", matches)
994 self.assertIn("'bar'", matches)
998 nt.assert_not_in("bar", matches)
995 self.assertNotIn("bar", matches)
999 nt.assert_not_in("'foo'", matches)
996 self.assertNotIn("'foo'", matches)
1000 nt.assert_not_in("foo", matches)
997 self.assertNotIn("foo", matches)
1001
998
1002 _, matches = complete(line_buffer="d['']", cursor_pos=3)
999 _, matches = complete(line_buffer="d['']", cursor_pos=3)
1003 nt.assert_in("foo", matches)
1000 self.assertIn("foo", matches)
1004 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
1001 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
1005
1002
1006 _, matches = complete(line_buffer='d[""]', cursor_pos=3)
1003 _, matches = complete(line_buffer='d[""]', cursor_pos=3)
1007 nt.assert_in("foo", matches)
1004 self.assertIn("foo", matches)
1008 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
1005 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
1009
1006
1010 _, matches = complete(line_buffer='d["foo","]', cursor_pos=9)
1007 _, matches = complete(line_buffer='d["foo","]', cursor_pos=9)
1011 nt.assert_in("bar", matches)
1008 self.assertIn("bar", matches)
1012 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
1009 assert not any(m.endswith(("]", '"', "'")) for m in matches), matches
1013
1010
1014 _, matches = complete(line_buffer='d["foo",]', cursor_pos=8)
1011 _, matches = complete(line_buffer='d["foo",]', cursor_pos=8)
1015 nt.assert_in("'bar'", matches)
1012 self.assertIn("'bar'", matches)
1016 nt.assert_not_in("bar", matches)
1013 self.assertNotIn("bar", matches)
1017
1014
1018 # Can complete with longer tuple keys
1015 # Can complete with longer tuple keys
1019 ip.user_ns["d"] = {('foo', 'bar', 'foobar'): None}
1016 ip.user_ns["d"] = {('foo', 'bar', 'foobar'): None}
1020
1017
1021 # - can complete second key
1018 # - can complete second key
1022 _, matches = complete(line_buffer="d['foo', 'b")
1019 _, matches = complete(line_buffer="d['foo', 'b")
1023 nt.assert_in('bar', matches)
1020 self.assertIn("bar", matches)
1024 nt.assert_not_in('foo', matches)
1021 self.assertNotIn("foo", matches)
1025 nt.assert_not_in('foobar', matches)
1022 self.assertNotIn("foobar", matches)
1026
1023
1027 # - can complete third key
1024 # - can complete third key
1028 _, matches = complete(line_buffer="d['foo', 'bar', 'fo")
1025 _, matches = complete(line_buffer="d['foo', 'bar', 'fo")
1029 nt.assert_in('foobar', matches)
1026 self.assertIn("foobar", matches)
1030 nt.assert_not_in('foo', matches)
1027 self.assertNotIn("foo", matches)
1031 nt.assert_not_in('bar', matches)
1028 self.assertNotIn("bar", matches)
1032
1033
1029
1034 def test_dict_key_completion_contexts(self):
1030 def test_dict_key_completion_contexts(self):
1035 """Test expression contexts in which dict key completion occurs"""
1031 """Test expression contexts in which dict key completion occurs"""
@@ -1046,16 +1042,16 b' class TestCompleter(unittest.TestCase):'
1046
1042
1047 def assert_no_completion(**kwargs):
1043 def assert_no_completion(**kwargs):
1048 _, matches = complete(**kwargs)
1044 _, matches = complete(**kwargs)
1049 nt.assert_not_in("abc", matches)
1045 self.assertNotIn("abc", matches)
1050 nt.assert_not_in("abc'", matches)
1046 self.assertNotIn("abc'", matches)
1051 nt.assert_not_in("abc']", matches)
1047 self.assertNotIn("abc']", matches)
1052 nt.assert_not_in("'abc'", matches)
1048 self.assertNotIn("'abc'", matches)
1053 nt.assert_not_in("'abc']", matches)
1049 self.assertNotIn("'abc']", matches)
1054
1050
1055 def assert_completion(**kwargs):
1051 def assert_completion(**kwargs):
1056 _, matches = complete(**kwargs)
1052 _, matches = complete(**kwargs)
1057 nt.assert_in("'abc'", matches)
1053 self.assertIn("'abc'", matches)
1058 nt.assert_not_in("'abc']", matches)
1054 self.assertNotIn("'abc']", matches)
1059
1055
1060 # no completion after string closed, even if reopened
1056 # no completion after string closed, even if reopened
1061 assert_no_completion(line_buffer="d['a'")
1057 assert_no_completion(line_buffer="d['a'")
@@ -1071,7 +1067,7 b' class TestCompleter(unittest.TestCase):'
1071 # greedy flag
1067 # greedy flag
1072 def assert_completion(**kwargs):
1068 def assert_completion(**kwargs):
1073 _, matches = complete(**kwargs)
1069 _, matches = complete(**kwargs)
1074 nt.assert_in("get()['abc']", matches)
1070 self.assertIn("get()['abc']", matches)
1075
1071
1076 assert_no_completion(line_buffer="get()[")
1072 assert_no_completion(line_buffer="get()[")
1077 with greedy_completion():
1073 with greedy_completion():
@@ -1089,25 +1085,25 b' class TestCompleter(unittest.TestCase):'
1089 ip.user_ns["d"] = {"abc": None, b"abd": None}
1085 ip.user_ns["d"] = {"abc": None, b"abd": None}
1090
1086
1091 _, matches = complete(line_buffer="d[")
1087 _, matches = complete(line_buffer="d[")
1092 nt.assert_in("'abc'", matches)
1088 self.assertIn("'abc'", matches)
1093 nt.assert_in("b'abd'", matches)
1089 self.assertIn("b'abd'", matches)
1094
1090
1095 if False: # not currently implemented
1091 if False: # not currently implemented
1096 _, matches = complete(line_buffer="d[b")
1092 _, matches = complete(line_buffer="d[b")
1097 nt.assert_in("b'abd'", matches)
1093 self.assertIn("b'abd'", matches)
1098 nt.assert_not_in("b'abc'", matches)
1094 self.assertNotIn("b'abc'", matches)
1099
1095
1100 _, matches = complete(line_buffer="d[b'")
1096 _, matches = complete(line_buffer="d[b'")
1101 nt.assert_in("abd", matches)
1097 self.assertIn("abd", matches)
1102 nt.assert_not_in("abc", matches)
1098 self.assertNotIn("abc", matches)
1103
1099
1104 _, matches = complete(line_buffer="d[B'")
1100 _, matches = complete(line_buffer="d[B'")
1105 nt.assert_in("abd", matches)
1101 self.assertIn("abd", matches)
1106 nt.assert_not_in("abc", matches)
1102 self.assertNotIn("abc", matches)
1107
1103
1108 _, matches = complete(line_buffer="d['")
1104 _, matches = complete(line_buffer="d['")
1109 nt.assert_in("abc", matches)
1105 self.assertIn("abc", matches)
1110 nt.assert_not_in("abd", matches)
1106 self.assertNotIn("abd", matches)
1111
1107
1112 def test_dict_key_completion_unicode_py3(self):
1108 def test_dict_key_completion_unicode_py3(self):
1113 """Test handling of unicode in dict key completion"""
1109 """Test handling of unicode in dict key completion"""
@@ -1120,20 +1116,20 b' class TestCompleter(unittest.TestCase):'
1120 if sys.platform != "win32":
1116 if sys.platform != "win32":
1121 # Known failure on Windows
1117 # Known failure on Windows
1122 _, matches = complete(line_buffer="d['a\\u05d0")
1118 _, matches = complete(line_buffer="d['a\\u05d0")
1123 nt.assert_in("u05d0", matches) # tokenized after \\
1119 self.assertIn("u05d0", matches) # tokenized after \\
1124
1120
1125 # query using character
1121 # query using character
1126 _, matches = complete(line_buffer="d['a\u05d0")
1122 _, matches = complete(line_buffer="d['a\u05d0")
1127 nt.assert_in("a\u05d0", matches)
1123 self.assertIn("a\u05d0", matches)
1128
1124
1129 with greedy_completion():
1125 with greedy_completion():
1130 # query using escape
1126 # query using escape
1131 _, matches = complete(line_buffer="d['a\\u05d0")
1127 _, matches = complete(line_buffer="d['a\\u05d0")
1132 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
1128 self.assertIn("d['a\\u05d0']", matches) # tokenized after \\
1133
1129
1134 # query using character
1130 # query using character
1135 _, matches = complete(line_buffer="d['a\u05d0")
1131 _, matches = complete(line_buffer="d['a\u05d0")
1136 nt.assert_in("d['a\u05d0']", matches)
1132 self.assertIn("d['a\u05d0']", matches)
1137
1133
1138 @dec.skip_without("numpy")
1134 @dec.skip_without("numpy")
1139 def test_struct_array_key_completion(self):
1135 def test_struct_array_key_completion(self):
@@ -1144,8 +1140,8 b' class TestCompleter(unittest.TestCase):'
1144 complete = ip.Completer.complete
1140 complete = ip.Completer.complete
1145 ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")])
1141 ip.user_ns["d"] = numpy.array([], dtype=[("hello", "f"), ("world", "f")])
1146 _, matches = complete(line_buffer="d['")
1142 _, matches = complete(line_buffer="d['")
1147 nt.assert_in("hello", matches)
1143 self.assertIn("hello", matches)
1148 nt.assert_in("world", matches)
1144 self.assertIn("world", matches)
1149 # complete on the numpy struct itself
1145 # complete on the numpy struct itself
1150 dt = numpy.dtype(
1146 dt = numpy.dtype(
1151 [("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)]
1147 [("my_head", [("my_dt", ">u4"), ("my_df", ">u4")]), ("my_data", ">f4", 5)]
@@ -1153,14 +1149,14 b' class TestCompleter(unittest.TestCase):'
1153 x = numpy.zeros(2, dtype=dt)
1149 x = numpy.zeros(2, dtype=dt)
1154 ip.user_ns["d"] = x[1]
1150 ip.user_ns["d"] = x[1]
1155 _, matches = complete(line_buffer="d['")
1151 _, matches = complete(line_buffer="d['")
1156 nt.assert_in("my_head", matches)
1152 self.assertIn("my_head", matches)
1157 nt.assert_in("my_data", matches)
1153 self.assertIn("my_data", matches)
1158 # complete on a nested level
1154 # complete on a nested level
1159 with greedy_completion():
1155 with greedy_completion():
1160 ip.user_ns["d"] = numpy.zeros(2, dtype=dt)
1156 ip.user_ns["d"] = numpy.zeros(2, dtype=dt)
1161 _, matches = complete(line_buffer="d[1]['my_head']['")
1157 _, matches = complete(line_buffer="d[1]['my_head']['")
1162 nt.assert_true(any(["my_dt" in m for m in matches]))
1158 self.assertTrue(any(["my_dt" in m for m in matches]))
1163 nt.assert_true(any(["my_df" in m for m in matches]))
1159 self.assertTrue(any(["my_df" in m for m in matches]))
1164
1160
1165 @dec.skip_without("pandas")
1161 @dec.skip_without("pandas")
1166 def test_dataframe_key_completion(self):
1162 def test_dataframe_key_completion(self):
@@ -1171,8 +1167,8 b' class TestCompleter(unittest.TestCase):'
1171 complete = ip.Completer.complete
1167 complete = ip.Completer.complete
1172 ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]})
1168 ip.user_ns["d"] = pandas.DataFrame({"hello": [1], "world": [2]})
1173 _, matches = complete(line_buffer="d['")
1169 _, matches = complete(line_buffer="d['")
1174 nt.assert_in("hello", matches)
1170 self.assertIn("hello", matches)
1175 nt.assert_in("world", matches)
1171 self.assertIn("world", matches)
1176
1172
1177 def test_dict_key_completion_invalids(self):
1173 def test_dict_key_completion_invalids(self):
1178 """Smoke test cases dict key completion can't handle"""
1174 """Smoke test cases dict key completion can't handle"""
@@ -1197,8 +1193,8 b' class TestCompleter(unittest.TestCase):'
1197 ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"])
1193 ip.user_ns["key_completable"] = KeyCompletable(["qwerty", "qwick"])
1198
1194
1199 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
1195 _, matches = ip.Completer.complete(line_buffer="key_completable['qw")
1200 nt.assert_in("qwerty", matches)
1196 self.assertIn("qwerty", matches)
1201 nt.assert_in("qwick", matches)
1197 self.assertIn("qwick", matches)
1202
1198
1203 def test_class_key_completion(self):
1199 def test_class_key_completion(self):
1204 ip = get_ipython()
1200 ip = get_ipython()
@@ -1207,8 +1203,8 b' class TestCompleter(unittest.TestCase):'
1207 ip.user_ns["named_instance_class"] = NamedInstanceClass
1203 ip.user_ns["named_instance_class"] = NamedInstanceClass
1208
1204
1209 _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw")
1205 _, matches = ip.Completer.complete(line_buffer="named_instance_class['qw")
1210 nt.assert_in("qwerty", matches)
1206 self.assertIn("qwerty", matches)
1211 nt.assert_in("qwick", matches)
1207 self.assertIn("qwick", matches)
1212
1208
1213 def test_tryimport(self):
1209 def test_tryimport(self):
1214 """
1210 """
@@ -1221,27 +1217,27 b' class TestCompleter(unittest.TestCase):'
1221 def test_aimport_module_completer(self):
1217 def test_aimport_module_completer(self):
1222 ip = get_ipython()
1218 ip = get_ipython()
1223 _, matches = ip.complete("i", "%aimport i")
1219 _, matches = ip.complete("i", "%aimport i")
1224 nt.assert_in("io", matches)
1220 self.assertIn("io", matches)
1225 nt.assert_not_in("int", matches)
1221 self.assertNotIn("int", matches)
1226
1222
1227 def test_nested_import_module_completer(self):
1223 def test_nested_import_module_completer(self):
1228 ip = get_ipython()
1224 ip = get_ipython()
1229 _, matches = ip.complete(None, "import IPython.co", 17)
1225 _, matches = ip.complete(None, "import IPython.co", 17)
1230 nt.assert_in("IPython.core", matches)
1226 self.assertIn("IPython.core", matches)
1231 nt.assert_not_in("import IPython.core", matches)
1227 self.assertNotIn("import IPython.core", matches)
1232 nt.assert_not_in("IPython.display", matches)
1228 self.assertNotIn("IPython.display", matches)
1233
1229
1234 def test_import_module_completer(self):
1230 def test_import_module_completer(self):
1235 ip = get_ipython()
1231 ip = get_ipython()
1236 _, matches = ip.complete("i", "import i")
1232 _, matches = ip.complete("i", "import i")
1237 nt.assert_in("io", matches)
1233 self.assertIn("io", matches)
1238 nt.assert_not_in("int", matches)
1234 self.assertNotIn("int", matches)
1239
1235
1240 def test_from_module_completer(self):
1236 def test_from_module_completer(self):
1241 ip = get_ipython()
1237 ip = get_ipython()
1242 _, matches = ip.complete("B", "from io import B", 16)
1238 _, matches = ip.complete("B", "from io import B", 16)
1243 nt.assert_in("BytesIO", matches)
1239 self.assertIn("BytesIO", matches)
1244 nt.assert_not_in("BaseException", matches)
1240 self.assertNotIn("BaseException", matches)
1245
1241
1246 def test_snake_case_completion(self):
1242 def test_snake_case_completion(self):
1247 ip = get_ipython()
1243 ip = get_ipython()
@@ -1249,8 +1245,8 b' class TestCompleter(unittest.TestCase):'
1249 ip.user_ns["some_three"] = 3
1245 ip.user_ns["some_three"] = 3
1250 ip.user_ns["some_four"] = 4
1246 ip.user_ns["some_four"] = 4
1251 _, matches = ip.complete("s_", "print(s_f")
1247 _, matches = ip.complete("s_", "print(s_f")
1252 nt.assert_in("some_three", matches)
1248 self.assertIn("some_three", matches)
1253 nt.assert_in("some_four", matches)
1249 self.assertIn("some_four", matches)
1254
1250
1255 def test_mix_terms(self):
1251 def test_mix_terms(self):
1256 ip = get_ipython()
1252 ip = get_ipython()
@@ -1274,5 +1270,5 b' class TestCompleter(unittest.TestCase):'
1274 )
1270 )
1275 )
1271 )
1276 _, matches = ip.complete(None, "test.meth(")
1272 _, matches = ip.complete(None, "test.meth(")
1277 nt.assert_in("meth_arg1=", matches)
1273 self.assertIn("meth_arg1=", matches)
1278 nt.assert_not_in("meth2_arg1=", matches)
1274 self.assertNotIn("meth2_arg1=", matches)
@@ -14,8 +14,6 b' import tempfile'
14 import unittest
14 import unittest
15 from os.path import join
15 from os.path import join
16
16
17 import nose.tools as nt
18
19 from IPython.core.completerlib import magic_run_completer, module_completion, try_import
17 from IPython.core.completerlib import magic_run_completer, module_completion, try_import
20 from IPython.utils.tempdir import TemporaryDirectory
18 from IPython.utils.tempdir import TemporaryDirectory
21 from IPython.testing.decorators import onlyif_unicode_paths
19 from IPython.testing.decorators import onlyif_unicode_paths
@@ -140,7 +138,7 b' def test_import_invalid_module():'
140
138
141 s = set( module_completion('import foo') )
139 s = set( module_completion('import foo') )
142 intersection = s.intersection(invalid_module_names)
140 intersection = s.intersection(invalid_module_names)
143 nt.assert_equal(intersection, set())
141 assert intersection == set()
144
142
145 assert valid_module_names.issubset(s), valid_module_names.intersection(s)
143 assert valid_module_names.issubset(s), valid_module_names.intersection(s)
146
144
@@ -153,15 +151,15 b' def test_bad_module_all():'
153 testsdir = os.path.dirname(__file__)
151 testsdir = os.path.dirname(__file__)
154 sys.path.insert(0, testsdir)
152 sys.path.insert(0, testsdir)
155 try:
153 try:
156 results = module_completion('from bad_all import ')
154 results = module_completion("from bad_all import ")
157 nt.assert_in('puppies', results)
155 assert "puppies" in results
158 for r in results:
156 for r in results:
159 nt.assert_is_instance(r, str)
157 assert isinstance(r, str)
160
158
161 # bad_all doesn't contain submodules, but this completion
159 # bad_all doesn't contain submodules, but this completion
162 # should finish without raising an exception:
160 # should finish without raising an exception:
163 results = module_completion("import bad_all.")
161 results = module_completion("import bad_all.")
164 nt.assert_equal(results, [])
162 assert results == []
165 finally:
163 finally:
166 sys.path.remove(testsdir)
164 sys.path.remove(testsdir)
167
165
@@ -189,6 +187,6 b' def test_valid_exported_submodules():'
189 """
187 """
190 results = module_completion("import os.pa")
188 results = module_completion("import os.pa")
191 # ensure we get a valid submodule:
189 # ensure we get a valid submodule:
192 nt.assert_in("os.path", results)
190 assert "os.path" in results
193 # ensure we don't get objects that aren't submodules:
191 # ensure we don't get objects that aren't submodules:
194 nt.assert_not_in("os.pathconf", results)
192 assert "os.pathconf" not in results
@@ -18,8 +18,6 b' from tempfile import NamedTemporaryFile'
18 from textwrap import dedent
18 from textwrap import dedent
19 from unittest.mock import patch
19 from unittest.mock import patch
20
20
21 import nose.tools as nt
22
23 from IPython.core import debugger
21 from IPython.core import debugger
24 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
22 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
25 from IPython.testing.decorators import skip_win32
23 from IPython.testing.decorators import skip_win32
@@ -66,13 +64,13 b' def test_longer_repr():'
66 a = '1234567890'* 7
64 a = '1234567890'* 7
67 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
65 ar = "'1234567890123456789012345678901234567890123456789012345678901234567890'"
68 a_trunc = "'123456789012...8901234567890'"
66 a_trunc = "'123456789012...8901234567890'"
69 nt.assert_equal(trepr(a), a_trunc)
67 assert trepr(a) == a_trunc
70 # The creation of our tracer modifies the repr module's repr function
68 # The creation of our tracer modifies the repr module's repr function
71 # in-place, since that global is used directly by the stdlib's pdb module.
69 # in-place, since that global is used directly by the stdlib's pdb module.
72 with warnings.catch_warnings():
70 with warnings.catch_warnings():
73 warnings.simplefilter('ignore', DeprecationWarning)
71 warnings.simplefilter('ignore', DeprecationWarning)
74 debugger.Tracer()
72 debugger.Tracer()
75 nt.assert_equal(trepr(a), ar)
73 assert trepr(a) == ar
76
74
77 def test_ipdb_magics():
75 def test_ipdb_magics():
78 '''Test calling some IPython magics from ipdb.
76 '''Test calling some IPython magics from ipdb.
@@ -7,7 +7,7 b' import warnings'
7
7
8 from unittest import mock
8 from unittest import mock
9
9
10 import nose.tools as nt
10 import pytest
11
11
12 from IPython import display
12 from IPython import display
13 from IPython.core.getipython import get_ipython
13 from IPython.core.getipython import get_ipython
@@ -22,15 +22,15 b' def test_image_size():'
22 """Simple test for display.Image(args, width=x,height=y)"""
22 """Simple test for display.Image(args, width=x,height=y)"""
23 thisurl = 'http://www.google.fr/images/srpr/logo3w.png'
23 thisurl = 'http://www.google.fr/images/srpr/logo3w.png'
24 img = display.Image(url=thisurl, width=200, height=200)
24 img = display.Image(url=thisurl, width=200, height=200)
25 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
25 assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_()
26 img = display.Image(url=thisurl, metadata={'width':200, 'height':200})
26 img = display.Image(url=thisurl, metadata={'width':200, 'height':200})
27 nt.assert_equal(u'<img src="%s" width="200" height="200"/>' % (thisurl), img._repr_html_())
27 assert '<img src="%s" width="200" height="200"/>' % (thisurl) == img._repr_html_()
28 img = display.Image(url=thisurl, width=200)
28 img = display.Image(url=thisurl, width=200)
29 nt.assert_equal(u'<img src="%s" width="200"/>' % (thisurl), img._repr_html_())
29 assert '<img src="%s" width="200"/>' % (thisurl) == img._repr_html_()
30 img = display.Image(url=thisurl)
30 img = display.Image(url=thisurl)
31 nt.assert_equal(u'<img src="%s"/>' % (thisurl), img._repr_html_())
31 assert '<img src="%s"/>' % (thisurl) == img._repr_html_()
32 img = display.Image(url=thisurl, unconfined=True)
32 img = display.Image(url=thisurl, unconfined=True)
33 nt.assert_equal(u'<img src="%s" class="unconfined"/>' % (thisurl), img._repr_html_())
33 assert '<img src="%s" class="unconfined"/>' % (thisurl) == img._repr_html_()
34
34
35
35
36 def test_image_mimes():
36 def test_image_mimes():
@@ -39,7 +39,7 b' def test_image_mimes():'
39 mime = display.Image._MIMETYPES[format]
39 mime = display.Image._MIMETYPES[format]
40 img = display.Image(b'garbage', format=format)
40 img = display.Image(b'garbage', format=format)
41 data, metadata = fmt(img)
41 data, metadata = fmt(img)
42 nt.assert_equal(sorted(data), sorted([mime, 'text/plain']))
42 assert sorted(data) == sorted([mime, "text/plain"])
43
43
44
44
45 def test_geojson():
45 def test_geojson():
@@ -60,17 +60,20 b' def test_geojson():'
60 "attribution": "Celestia/praesepe",
60 "attribution": "Celestia/praesepe",
61 "minZoom": 0,
61 "minZoom": 0,
62 "maxZoom": 18,
62 "maxZoom": 18,
63 })
63 },
64 nt.assert_equal(u'<IPython.core.display.GeoJSON object>', str(gj))
64 )
65 assert "<IPython.core.display.GeoJSON object>" == str(gj)
66
65
67
66 def test_retina_png():
68 def test_retina_png():
67 here = os.path.dirname(__file__)
69 here = os.path.dirname(__file__)
68 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
70 img = display.Image(os.path.join(here, "2x2.png"), retina=True)
69 nt.assert_equal(img.height, 1)
71 assert img.height == 1
70 nt.assert_equal(img.width, 1)
72 assert img.width == 1
71 data, md = img._repr_png_()
73 data, md = img._repr_png_()
72 nt.assert_equal(md['width'], 1)
74 assert md["width"] == 1
73 nt.assert_equal(md['height'], 1)
75 assert md["height"] == 1
76
74
77
75 def test_embed_svg_url():
78 def test_embed_svg_url():
76 import gzip
79 import gzip
@@ -102,18 +105,20 b' def test_embed_svg_url():'
102
105
103 with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen):
106 with mock.patch('urllib.request.urlopen', side_effect=mocked_urlopen):
104 svg = display.SVG(url=url)
107 svg = display.SVG(url=url)
105 nt.assert_true(svg._repr_svg_().startswith('<svg'))
108 assert svg._repr_svg_().startswith("<svg") is True
106 svg = display.SVG(url=url + 'z')
109 svg = display.SVG(url=url + "z")
107 nt.assert_true(svg._repr_svg_().startswith('<svg'))
110 assert svg._repr_svg_().startswith("<svg") is True
111
108
112
109 def test_retina_jpeg():
113 def test_retina_jpeg():
110 here = os.path.dirname(__file__)
114 here = os.path.dirname(__file__)
111 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
115 img = display.Image(os.path.join(here, "2x2.jpg"), retina=True)
112 nt.assert_equal(img.height, 1)
116 assert img.height == 1
113 nt.assert_equal(img.width, 1)
117 assert img.width == 1
114 data, md = img._repr_jpeg_()
118 data, md = img._repr_jpeg_()
115 nt.assert_equal(md['width'], 1)
119 assert md["width"] == 1
116 nt.assert_equal(md['height'], 1)
120 assert md["height"] == 1
121
117
122
118 def test_base64image():
123 def test_base64image():
119 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
124 display.Image("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABAQMAAAAl21bKAAAAA1BMVEUAAACnej3aAAAAAWJLR0QAiAUdSAAAAAlwSFlzAAALEwAACxMBAJqcGAAAAAd0SU1FB94BCRQnOqNu0b4AAAAKSURBVAjXY2AAAAACAAHiIbwzAAAAAElFTkSuQmCC")
@@ -121,18 +126,30 b' def test_base64image():'
121 def test_image_filename_defaults():
126 def test_image_filename_defaults():
122 '''test format constraint, and validity of jpeg and png'''
127 '''test format constraint, and validity of jpeg and png'''
123 tpath = ipath.get_ipython_package_dir()
128 tpath = ipath.get_ipython_package_dir()
124 nt.assert_raises(ValueError, display.Image, filename=os.path.join(tpath, 'testing/tests/badformat.zip'),
129 pytest.raises(
125 embed=True)
130 ValueError,
126 nt.assert_raises(ValueError, display.Image)
131 display.Image,
127 nt.assert_raises(ValueError, display.Image, data='this is not an image', format='badformat', embed=True)
132 filename=os.path.join(tpath, "testing/tests/badformat.zip"),
128 # check both paths to allow packages to test at build and install time
133 embed=True,
134 )
135 pytest.raises(ValueError, display.Image)
136 pytest.raises(
137 ValueError,
138 display.Image,
139 data="this is not an image",
140 format="badformat",
141 embed=True,
142 )
143 # check boths paths to allow packages to test at build and install time
129 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
144 imgfile = os.path.join(tpath, 'core/tests/2x2.png')
130 img = display.Image(filename=imgfile)
145 img = display.Image(filename=imgfile)
131 nt.assert_equal('png', img.format)
146 assert "png" == img.format
132 nt.assert_is_not_none(img._repr_png_())
147 assert img._repr_png_() is not None
133 img = display.Image(filename=os.path.join(tpath, 'testing/tests/logo.jpg'), embed=False)
148 img = display.Image(
134 nt.assert_equal('jpeg', img.format)
149 filename=os.path.join(tpath, "testing/tests/logo.jpg"), embed=False
135 nt.assert_is_none(img._repr_jpeg_())
150 )
151 assert "jpeg" == img.format
152 assert img._repr_jpeg_() is None
136
153
137 def _get_inline_config():
154 def _get_inline_config():
138 from matplotlib_inline.config import InlineBackend
155 from matplotlib_inline.config import InlineBackend
@@ -171,9 +188,9 b' def test_set_matplotlib_formats():'
171 display.set_matplotlib_formats(*formats)
188 display.set_matplotlib_formats(*formats)
172 for mime, f in formatters.items():
189 for mime, f in formatters.items():
173 if mime in active_mimes:
190 if mime in active_mimes:
174 nt.assert_in(Figure, f)
191 assert Figure in f
175 else:
192 else:
176 nt.assert_not_in(Figure, f)
193 assert Figure not in f
177
194
178
195
179 @dec.skip_without("ipykernel")
196 @dec.skip_without("ipykernel")
@@ -192,7 +209,7 b' def test_set_matplotlib_formats_kwargs():'
192 expected["base64"] = True
209 expected["base64"] = True
193 expected["fmt"] = "png"
210 expected["fmt"] = "png"
194 expected.update(cfg.print_figure_kwargs)
211 expected.update(cfg.print_figure_kwargs)
195 nt.assert_equal(formatter_kwargs, expected)
212 assert formatter_kwargs == expected
196
213
197 def test_display_available():
214 def test_display_available():
198 """
215 """
@@ -214,26 +231,27 b' def test_display_available():'
214
231
215 def test_textdisplayobj_pretty_repr():
232 def test_textdisplayobj_pretty_repr():
216 p = display.Pretty("This is a simple test")
233 p = display.Pretty("This is a simple test")
217 nt.assert_equal(repr(p), '<IPython.core.display.Pretty object>')
234 assert repr(p) == "<IPython.core.display.Pretty object>"
218 nt.assert_equal(p.data, 'This is a simple test')
235 assert p.data == "This is a simple test"
219
236
220 p._show_mem_addr = True
237 p._show_mem_addr = True
221 nt.assert_equal(repr(p), object.__repr__(p))
238 assert repr(p) == object.__repr__(p)
239
222
240
223 def test_displayobject_repr():
241 def test_displayobject_repr():
224 h = display.HTML('<br />')
242 h = display.HTML("<br />")
225 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
243 assert repr(h) == "<IPython.core.display.HTML object>"
226 h._show_mem_addr = True
244 h._show_mem_addr = True
227 nt.assert_equal(repr(h), object.__repr__(h))
245 assert repr(h) == object.__repr__(h)
228 h._show_mem_addr = False
246 h._show_mem_addr = False
229 nt.assert_equal(repr(h), '<IPython.core.display.HTML object>')
247 assert repr(h) == "<IPython.core.display.HTML object>"
230
248
231 j = display.Javascript('')
249 j = display.Javascript("")
232 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
250 assert repr(j) == "<IPython.core.display.Javascript object>"
233 j._show_mem_addr = True
251 j._show_mem_addr = True
234 nt.assert_equal(repr(j), object.__repr__(j))
252 assert repr(j) == object.__repr__(j)
235 j._show_mem_addr = False
253 j._show_mem_addr = False
236 nt.assert_equal(repr(j), '<IPython.core.display.Javascript object>')
254 assert repr(j) == "<IPython.core.display.Javascript object>"
237
255
238 @mock.patch('warnings.warn')
256 @mock.patch('warnings.warn')
239 def test_encourage_iframe_over_html(m_warn):
257 def test_encourage_iframe_over_html(m_warn):
@@ -255,18 +273,22 b' def test_encourage_iframe_over_html(m_warn):'
255
273
256 def test_progress():
274 def test_progress():
257 p = display.ProgressBar(10)
275 p = display.ProgressBar(10)
258 nt.assert_in('0/10',repr(p))
276 assert "0/10" in repr(p)
259 p.html_width = '100%'
277 p.html_width = "100%"
260 p.progress = 5
278 p.progress = 5
261 nt.assert_equal(p._repr_html_(), "<progress style='width:100%' max='10' value='5'></progress>")
279 assert (
280 p._repr_html_() == "<progress style='width:100%' max='10' value='5'></progress>"
281 )
282
262
283
263 def test_progress_iter():
284 def test_progress_iter():
264 with capture_output(display=False) as captured:
285 with capture_output(display=False) as captured:
265 for i in display.ProgressBar(5):
286 for i in display.ProgressBar(5):
266 out = captured.stdout
287 out = captured.stdout
267 nt.assert_in('{0}/5'.format(i), out)
288 assert "{0}/5".format(i) in out
268 out = captured.stdout
289 out = captured.stdout
269 nt.assert_in('5/5', out)
290 assert "5/5" in out
291
270
292
271 def test_json():
293 def test_json():
272 d = {'a': 5}
294 d = {'a': 5}
@@ -284,13 +306,13 b' def test_json():'
284 display.JSON(d, expanded=True, root='custom'),
306 display.JSON(d, expanded=True, root='custom'),
285 ]
307 ]
286 for j, md in zip(json_objs, metadata):
308 for j, md in zip(json_objs, metadata):
287 nt.assert_equal(j._repr_json_(), (d, md))
309 assert j._repr_json_() == (d, md)
288
310
289 with warnings.catch_warnings(record=True) as w:
311 with warnings.catch_warnings(record=True) as w:
290 warnings.simplefilter("always")
312 warnings.simplefilter("always")
291 j = display.JSON(json.dumps(d))
313 j = display.JSON(json.dumps(d))
292 nt.assert_equal(len(w), 1)
314 assert len(w) == 1
293 nt.assert_equal(j._repr_json_(), (d, metadata[0]))
315 assert j._repr_json_() == (d, metadata[0])
294
316
295 json_objs = [
317 json_objs = [
296 display.JSON(lis),
318 display.JSON(lis),
@@ -299,23 +321,24 b' def test_json():'
299 display.JSON(lis, expanded=True, root='custom'),
321 display.JSON(lis, expanded=True, root='custom'),
300 ]
322 ]
301 for j, md in zip(json_objs, metadata):
323 for j, md in zip(json_objs, metadata):
302 nt.assert_equal(j._repr_json_(), (lis, md))
324 assert j._repr_json_() == (lis, md)
303
325
304 with warnings.catch_warnings(record=True) as w:
326 with warnings.catch_warnings(record=True) as w:
305 warnings.simplefilter("always")
327 warnings.simplefilter("always")
306 j = display.JSON(json.dumps(lis))
328 j = display.JSON(json.dumps(lis))
307 nt.assert_equal(len(w), 1)
329 assert len(w) == 1
308 nt.assert_equal(j._repr_json_(), (lis, metadata[0]))
330 assert j._repr_json_() == (lis, metadata[0])
331
309
332
310 def test_video_embedding():
333 def test_video_embedding():
311 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
334 """use a tempfile, with dummy-data, to ensure that video embedding doesn't crash"""
312 v = display.Video("http://ignored")
335 v = display.Video("http://ignored")
313 assert not v.embed
336 assert not v.embed
314 html = v._repr_html_()
337 html = v._repr_html_()
315 nt.assert_not_in('src="data:', html)
338 assert 'src="data:' not in html
316 nt.assert_in('src="http://ignored"', html)
339 assert 'src="http://ignored"' in html
317
340
318 with nt.assert_raises(ValueError):
341 with pytest.raises(ValueError):
319 v = display.Video(b'abc')
342 v = display.Video(b'abc')
320
343
321 with NamedFileInTemporaryDirectory('test.mp4') as f:
344 with NamedFileInTemporaryDirectory('test.mp4') as f:
@@ -325,52 +348,53 b' def test_video_embedding():'
325 v = display.Video(f.name)
348 v = display.Video(f.name)
326 assert not v.embed
349 assert not v.embed
327 html = v._repr_html_()
350 html = v._repr_html_()
328 nt.assert_not_in('src="data:', html)
351 assert 'src="data:' not in html
329
352
330 v = display.Video(f.name, embed=True)
353 v = display.Video(f.name, embed=True)
331 html = v._repr_html_()
354 html = v._repr_html_()
332 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
355 assert 'src="data:video/mp4;base64,YWJj"' in html
333
356
334 v = display.Video(f.name, embed=True, mimetype='video/other')
357 v = display.Video(f.name, embed=True, mimetype='video/other')
335 html = v._repr_html_()
358 html = v._repr_html_()
336 nt.assert_in('src="data:video/other;base64,YWJj"',html)
359 assert 'src="data:video/other;base64,YWJj"' in html
337
360
338 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
361 v = display.Video(b'abc', embed=True, mimetype='video/mp4')
339 html = v._repr_html_()
362 html = v._repr_html_()
340 nt.assert_in('src="data:video/mp4;base64,YWJj"',html)
363 assert 'src="data:video/mp4;base64,YWJj"' in html
341
364
342 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
365 v = display.Video(u'YWJj', embed=True, mimetype='video/xyz')
343 html = v._repr_html_()
366 html = v._repr_html_()
344 nt.assert_in('src="data:video/xyz;base64,YWJj"',html)
367 assert 'src="data:video/xyz;base64,YWJj"' in html
345
368
346 def test_html_metadata():
369 def test_html_metadata():
347 s = "<h1>Test</h1>"
370 s = "<h1>Test</h1>"
348 h = display.HTML(s, metadata={"isolated": True})
371 h = display.HTML(s, metadata={"isolated": True})
349 nt.assert_equal(h._repr_html_(), (s, {"isolated": True}))
372 assert h._repr_html_() == (s, {"isolated": True})
373
350
374
351 def test_display_id():
375 def test_display_id():
352 ip = get_ipython()
376 ip = get_ipython()
353 with mock.patch.object(ip.display_pub, 'publish') as pub:
377 with mock.patch.object(ip.display_pub, 'publish') as pub:
354 handle = display.display('x')
378 handle = display.display('x')
355 nt.assert_is(handle, None)
379 assert handle is None
356 handle = display.display('y', display_id='secret')
380 handle = display.display('y', display_id='secret')
357 nt.assert_is_instance(handle, display.DisplayHandle)
381 assert isinstance(handle, display.DisplayHandle)
358 handle2 = display.display('z', display_id=True)
382 handle2 = display.display('z', display_id=True)
359 nt.assert_is_instance(handle2, display.DisplayHandle)
383 assert isinstance(handle2, display.DisplayHandle)
360 nt.assert_not_equal(handle.display_id, handle2.display_id)
384 assert handle.display_id != handle2.display_id
361
385
362 nt.assert_equal(pub.call_count, 3)
386 assert pub.call_count == 3
363 args, kwargs = pub.call_args_list[0]
387 args, kwargs = pub.call_args_list[0]
364 nt.assert_equal(args, ())
388 assert args == ()
365 nt.assert_equal(kwargs, {
389 assert kwargs == {
366 'data': {
390 'data': {
367 'text/plain': repr('x')
391 'text/plain': repr('x')
368 },
392 },
369 'metadata': {},
393 'metadata': {},
370 })
394 }
371 args, kwargs = pub.call_args_list[1]
395 args, kwargs = pub.call_args_list[1]
372 nt.assert_equal(args, ())
396 assert args == ()
373 nt.assert_equal(kwargs, {
397 assert kwargs == {
374 'data': {
398 'data': {
375 'text/plain': repr('y')
399 'text/plain': repr('y')
376 },
400 },
@@ -378,10 +402,10 b' def test_display_id():'
378 'transient': {
402 'transient': {
379 'display_id': handle.display_id,
403 'display_id': handle.display_id,
380 },
404 },
381 })
405 }
382 args, kwargs = pub.call_args_list[2]
406 args, kwargs = pub.call_args_list[2]
383 nt.assert_equal(args, ())
407 assert args == ()
384 nt.assert_equal(kwargs, {
408 assert kwargs == {
385 'data': {
409 'data': {
386 'text/plain': repr('z')
410 'text/plain': repr('z')
387 },
411 },
@@ -389,19 +413,19 b' def test_display_id():'
389 'transient': {
413 'transient': {
390 'display_id': handle2.display_id,
414 'display_id': handle2.display_id,
391 },
415 },
392 })
416 }
393
417
394
418
395 def test_update_display():
419 def test_update_display():
396 ip = get_ipython()
420 ip = get_ipython()
397 with mock.patch.object(ip.display_pub, 'publish') as pub:
421 with mock.patch.object(ip.display_pub, 'publish') as pub:
398 with nt.assert_raises(TypeError):
422 with pytest.raises(TypeError):
399 display.update_display('x')
423 display.update_display('x')
400 display.update_display('x', display_id='1')
424 display.update_display('x', display_id='1')
401 display.update_display('y', display_id='2')
425 display.update_display('y', display_id='2')
402 args, kwargs = pub.call_args_list[0]
426 args, kwargs = pub.call_args_list[0]
403 nt.assert_equal(args, ())
427 assert args == ()
404 nt.assert_equal(kwargs, {
428 assert kwargs == {
405 'data': {
429 'data': {
406 'text/plain': repr('x')
430 'text/plain': repr('x')
407 },
431 },
@@ -410,10 +434,10 b' def test_update_display():'
410 'display_id': '1',
434 'display_id': '1',
411 },
435 },
412 'update': True,
436 'update': True,
413 })
437 }
414 args, kwargs = pub.call_args_list[1]
438 args, kwargs = pub.call_args_list[1]
415 nt.assert_equal(args, ())
439 assert args == ()
416 nt.assert_equal(kwargs, {
440 assert kwargs == {
417 'data': {
441 'data': {
418 'text/plain': repr('y')
442 'text/plain': repr('y')
419 },
443 },
@@ -422,22 +446,22 b' def test_update_display():'
422 'display_id': '2',
446 'display_id': '2',
423 },
447 },
424 'update': True,
448 'update': True,
425 })
449 }
426
450
427
451
428 def test_display_handle():
452 def test_display_handle():
429 ip = get_ipython()
453 ip = get_ipython()
430 handle = display.DisplayHandle()
454 handle = display.DisplayHandle()
431 nt.assert_is_instance(handle.display_id, str)
455 assert isinstance(handle.display_id, str)
432 handle = display.DisplayHandle('my-id')
456 handle = display.DisplayHandle("my-id")
433 nt.assert_equal(handle.display_id, 'my-id')
457 assert handle.display_id == "my-id"
434 with mock.patch.object(ip.display_pub, 'publish') as pub:
458 with mock.patch.object(ip.display_pub, "publish") as pub:
435 handle.display('x')
459 handle.display("x")
436 handle.update('y')
460 handle.update("y")
437
461
438 args, kwargs = pub.call_args_list[0]
462 args, kwargs = pub.call_args_list[0]
439 nt.assert_equal(args, ())
463 assert args == ()
440 nt.assert_equal(kwargs, {
464 assert kwargs == {
441 'data': {
465 'data': {
442 'text/plain': repr('x')
466 'text/plain': repr('x')
443 },
467 },
@@ -445,10 +469,10 b' def test_display_handle():'
445 'transient': {
469 'transient': {
446 'display_id': handle.display_id,
470 'display_id': handle.display_id,
447 }
471 }
448 })
472 }
449 args, kwargs = pub.call_args_list[1]
473 args, kwargs = pub.call_args_list[1]
450 nt.assert_equal(args, ())
474 assert args == ()
451 nt.assert_equal(kwargs, {
475 assert kwargs == {
452 'data': {
476 'data': {
453 'text/plain': repr('y')
477 'text/plain': repr('y')
454 },
478 },
@@ -457,34 +481,31 b' def test_display_handle():'
457 'display_id': handle.display_id,
481 'display_id': handle.display_id,
458 },
482 },
459 'update': True,
483 'update': True,
460 })
484 }
461
485
462
486
463 def test_image_alt_tag():
487 def test_image_alt_tag():
464 """Simple test for display.Image(args, alt=x,)"""
488 """Simple test for display.Image(args, alt=x,)"""
465 thisurl = "http://example.com/image.png"
489 thisurl = "http://example.com/image.png"
466 img = display.Image(url=thisurl, alt="an image")
490 img = display.Image(url=thisurl, alt="an image")
467 nt.assert_equal(u'<img src="%s" alt="an image"/>' % (thisurl), img._repr_html_())
491 assert '<img src="%s" alt="an image"/>' % (thisurl) == img._repr_html_()
468 img = display.Image(url=thisurl, unconfined=True, alt="an image")
492 img = display.Image(url=thisurl, unconfined=True, alt="an image")
469 nt.assert_equal(
493 assert (
470 u'<img src="%s" class="unconfined" alt="an image"/>' % (thisurl),
494 '<img src="%s" class="unconfined" alt="an image"/>' % (thisurl)
471 img._repr_html_(),
495 == img._repr_html_()
472 )
496 )
473 img = display.Image(url=thisurl, alt='>"& <')
497 img = display.Image(url=thisurl, alt='>"& <')
474 nt.assert_equal(
498 assert '<img src="%s" alt="&gt;&quot;&amp; &lt;"/>' % (thisurl) == img._repr_html_()
475 u'<img src="%s" alt="&gt;&quot;&amp; &lt;"/>' % (thisurl), img._repr_html_()
476 )
477
499
478 img = display.Image(url=thisurl, metadata={"alt": "an image"})
500 img = display.Image(url=thisurl, metadata={"alt": "an image"})
479 nt.assert_equal(img.alt, "an image")
501 assert img.alt == "an image"
480
481 here = os.path.dirname(__file__)
502 here = os.path.dirname(__file__)
482 img = display.Image(os.path.join(here, "2x2.png"), alt="an image")
503 img = display.Image(os.path.join(here, "2x2.png"), alt="an image")
483 nt.assert_equal(img.alt, "an image")
504 assert img.alt == "an image"
484 _, md = img._repr_png_()
505 _, md = img._repr_png_()
485 nt.assert_equal(md["alt"], "an image")
506 assert md["alt"] == "an image"
486
507
487
508
488 @nt.raises(FileNotFoundError)
489 def test_image_bad_filename_raises_proper_exception():
509 def test_image_bad_filename_raises_proper_exception():
510 with pytest.raises(FileNotFoundError):
490 display.Image("/this/file/does/not/exist/")._repr_png_()
511 display.Image("/this/file/does/not/exist/")._repr_png_()
@@ -1,6 +1,5 b''
1 import unittest
1 import unittest
2 from unittest.mock import Mock
2 from unittest.mock import Mock
3 import nose.tools as nt
4
3
5 from IPython.core import events
4 from IPython.core import events
6 import IPython.testing.tools as tt
5 import IPython.testing.tools as tt
@@ -40,9 +39,9 b' class CallbackTests(unittest.TestCase):'
40 def cb2():
39 def cb2():
41 ...
40 ...
42
41
43 self.em.register('ping_received', cb1)
42 self.em.register("ping_received", cb1)
44 nt.assert_raises(ValueError, self.em.unregister, 'ping_received', cb2)
43 self.assertRaises(ValueError, self.em.unregister, "ping_received", cb2)
45 self.em.unregister('ping_received', cb1)
44 self.em.unregister("ping_received", cb1)
46
45
47 def test_cb_error(self):
46 def test_cb_error(self):
48 cb = Mock(side_effect=ValueError)
47 cb = Mock(side_effect=ValueError)
@@ -1,7 +1,5 b''
1 import os.path
1 import os.path
2
2
3 import nose.tools as nt
4
5 import IPython.testing.tools as tt
3 import IPython.testing.tools as tt
6 from IPython.utils.syspathcontext import prepended_to_syspath
4 from IPython.utils.syspathcontext import prepended_to_syspath
7 from IPython.utils.tempdir import TemporaryDirectory
5 from IPython.utils.tempdir import TemporaryDirectory
@@ -93,4 +91,4 b' def test_extension_builtins():'
93
91
94 def test_non_extension():
92 def test_non_extension():
95 em = get_ipython().extension_manager
93 em = get_ipython().extension_manager
96 nt.assert_equal(em.load_extension('sys'), "no load function")
94 assert em.load_extension("sys") == "no load function"
@@ -7,7 +7,7 b' try:'
7 import numpy
7 import numpy
8 except:
8 except:
9 numpy = None
9 numpy = None
10 import nose.tools as nt
10 import pytest
11
11
12 from IPython import get_ipython
12 from IPython import get_ipython
13 from traitlets.config import Config
13 from traitlets.config import Config
@@ -96,23 +96,24 b' def test_bad_precision():'
96 f = PlainTextFormatter()
96 f = PlainTextFormatter()
97 def set_fp(p):
97 def set_fp(p):
98 f.float_precision=p
98 f.float_precision = p
99 nt.assert_raises(ValueError, set_fp, '%')
99
100 nt.assert_raises(ValueError, set_fp, '%.3f%i')
100 pytest.raises(ValueError, set_fp, "%")
101 nt.assert_raises(ValueError, set_fp, 'foo')
101 pytest.raises(ValueError, set_fp, "%.3f%i")
102 nt.assert_raises(ValueError, set_fp, -1)
102 pytest.raises(ValueError, set_fp, "foo")
103 pytest.raises(ValueError, set_fp, -1)
103
104
104 def test_for_type():
105 def test_for_type():
105 f = PlainTextFormatter()
106 f = PlainTextFormatter()
106
107
107 # initial return, None
108 # initial return, None
108 nt.assert_is(f.for_type(C, foo_printer), None)
109 assert f.for_type(C, foo_printer) is None
109 # no func queries
110 # no func queries
110 nt.assert_is(f.for_type(C), foo_printer)
111 assert f.for_type(C) is foo_printer
111 # shouldn't change anything
112 # shouldn't change anything
112 nt.assert_is(f.for_type(C), foo_printer)
113 assert f.for_type(C) is foo_printer
113 # None should do the same
114 # None should do the same
114 nt.assert_is(f.for_type(C, None), foo_printer)
115 assert f.for_type(C, None) is foo_printer
115 nt.assert_is(f.for_type(C, None), foo_printer)
116 assert f.for_type(C, None) is foo_printer
116
117
117 def test_for_type_string():
118 def test_for_type_string():
118 f = PlainTextFormatter()
119 f = PlainTextFormatter()
@@ -120,13 +121,13 b' def test_for_type_string():'
120 type_str = '%s.%s' % (C.__module__, 'C')
121 type_str = '%s.%s' % (C.__module__, 'C')
121
122
122 # initial return, None
123 # initial return, None
123 nt.assert_is(f.for_type(type_str, foo_printer), None)
124 assert f.for_type(type_str, foo_printer) is None
124 # no func queries
125 # no func queries
125 nt.assert_is(f.for_type(type_str), foo_printer)
126 assert f.for_type(type_str) is foo_printer
126 nt.assert_in(_mod_name_key(C), f.deferred_printers)
127 assert _mod_name_key(C) in f.deferred_printers
127 nt.assert_is(f.for_type(C), foo_printer)
128 assert f.for_type(C) is foo_printer
128 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
129 assert _mod_name_key(C) not in f.deferred_printers
129 nt.assert_in(C, f.type_printers)
130 assert C in f.type_printers
130
131
131 def test_for_type_by_name():
132 def test_for_type_by_name():
132 f = PlainTextFormatter()
133 f = PlainTextFormatter()
@@ -134,21 +135,22 b' def test_for_type_by_name():'
134 mod = C.__module__
135 mod = C.__module__
135
136
136 # initial return, None
137 # initial return, None
137 nt.assert_is(f.for_type_by_name(mod, 'C', foo_printer), None)
138 assert f.for_type_by_name(mod, "C", foo_printer) is None
138 # no func queries
139 # no func queries
139 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
140 assert f.for_type_by_name(mod, "C") is foo_printer
140 # shouldn't change anything
141 # shouldn't change anything
141 nt.assert_is(f.for_type_by_name(mod, 'C'), foo_printer)
142 assert f.for_type_by_name(mod, "C") is foo_printer
142 # None should do the same
143 # None should do the same
143 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
144 assert f.for_type_by_name(mod, "C", None) is foo_printer
144 nt.assert_is(f.for_type_by_name(mod, 'C', None), foo_printer)
145 assert f.for_type_by_name(mod, "C", None) is foo_printer
146
145
147
146 def test_lookup():
148 def test_lookup():
147 f = PlainTextFormatter()
149 f = PlainTextFormatter()
148
150
149 f.for_type(C, foo_printer)
151 f.for_type(C, foo_printer)
150 nt.assert_is(f.lookup(C()), foo_printer)
152 assert f.lookup(C()) is foo_printer
151 with nt.assert_raises(KeyError):
153 with pytest.raises(KeyError):
152 f.lookup(A())
154 f.lookup(A())
153
155
154 def test_lookup_string():
156 def test_lookup_string():
@@ -156,16 +158,16 b' def test_lookup_string():'
156 type_str = '%s.%s' % (C.__module__, 'C')
158 type_str = '%s.%s' % (C.__module__, 'C')
157
159
158 f.for_type(type_str, foo_printer)
160 f.for_type(type_str, foo_printer)
159 nt.assert_is(f.lookup(C()), foo_printer)
161 assert f.lookup(C()) is foo_printer
160 # should move from deferred to imported dict
162 # should move from deferred to imported dict
161 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
163 assert _mod_name_key(C) not in f.deferred_printers
162 nt.assert_in(C, f.type_printers)
164 assert C in f.type_printers
163
165
164 def test_lookup_by_type():
166 def test_lookup_by_type():
165 f = PlainTextFormatter()
167 f = PlainTextFormatter()
166 f.for_type(C, foo_printer)
168 f.for_type(C, foo_printer)
167 nt.assert_is(f.lookup_by_type(C), foo_printer)
169 assert f.lookup_by_type(C) is foo_printer
168 with nt.assert_raises(KeyError):
170 with pytest.raises(KeyError):
169 f.lookup_by_type(A)
171 f.lookup_by_type(A)
170
172
171 def test_lookup_by_type_string():
173 def test_lookup_by_type_string():
@@ -174,69 +176,69 b' def test_lookup_by_type_string():'
174 f.for_type(type_str, foo_printer)
176 f.for_type(type_str, foo_printer)
175
177
176 # verify insertion
178 # verify insertion
177 nt.assert_in(_mod_name_key(C), f.deferred_printers)
179 assert _mod_name_key(C) in f.deferred_printers
178 nt.assert_not_in(C, f.type_printers)
180 assert C not in f.type_printers
179
181
180 nt.assert_is(f.lookup_by_type(type_str), foo_printer)
182 assert f.lookup_by_type(type_str) is foo_printer
181 # lookup by string doesn't cause import
183 # lookup by string doesn't cause import
182 nt.assert_in(_mod_name_key(C), f.deferred_printers)
184 assert _mod_name_key(C) in f.deferred_printers
183 nt.assert_not_in(C, f.type_printers)
185 assert C not in f.type_printers
184
186
185 nt.assert_is(f.lookup_by_type(C), foo_printer)
187 assert f.lookup_by_type(C) is foo_printer
186 # should move from deferred to imported dict
188 # should move from deferred to imported dict
187 nt.assert_not_in(_mod_name_key(C), f.deferred_printers)
189 assert _mod_name_key(C) not in f.deferred_printers
188 nt.assert_in(C, f.type_printers)
190 assert C in f.type_printers
189
191
190 def test_in_formatter():
192 def test_in_formatter():
191 f = PlainTextFormatter()
193 f = PlainTextFormatter()
192 f.for_type(C, foo_printer)
194 f.for_type(C, foo_printer)
193 type_str = '%s.%s' % (C.__module__, 'C')
195 type_str = '%s.%s' % (C.__module__, 'C')
194 nt.assert_in(C, f)
196 assert C in f
195 nt.assert_in(type_str, f)
197 assert type_str in f
196
198
197 def test_string_in_formatter():
199 def test_string_in_formatter():
198 f = PlainTextFormatter()
200 f = PlainTextFormatter()
199 type_str = '%s.%s' % (C.__module__, 'C')
201 type_str = '%s.%s' % (C.__module__, 'C')
200 f.for_type(type_str, foo_printer)
202 f.for_type(type_str, foo_printer)
201 nt.assert_in(type_str, f)
203 assert type_str in f
202 nt.assert_in(C, f)
204 assert C in f
203
205
204 def test_pop():
206 def test_pop():
205 f = PlainTextFormatter()
207 f = PlainTextFormatter()
206 f.for_type(C, foo_printer)
208 f.for_type(C, foo_printer)
207 nt.assert_is(f.lookup_by_type(C), foo_printer)
209 assert f.lookup_by_type(C) is foo_printer
208 nt.assert_is(f.pop(C, None), foo_printer)
210 assert f.pop(C, None) is foo_printer
209 f.for_type(C, foo_printer)
211 f.for_type(C, foo_printer)
210 nt.assert_is(f.pop(C), foo_printer)
212 assert f.pop(C) is foo_printer
211 with nt.assert_raises(KeyError):
213 with pytest.raises(KeyError):
212 f.lookup_by_type(C)
214 f.lookup_by_type(C)
213 with nt.assert_raises(KeyError):
215 with pytest.raises(KeyError):
214 f.pop(C)
216 f.pop(C)
215 with nt.assert_raises(KeyError):
217 with pytest.raises(KeyError):
216 f.pop(A)
218 f.pop(A)
217 nt.assert_is(f.pop(A, None), None)
219 assert f.pop(A, None) is None
218
220
219 def test_pop_string():
221 def test_pop_string():
220 f = PlainTextFormatter()
222 f = PlainTextFormatter()
221 type_str = '%s.%s' % (C.__module__, 'C')
223 type_str = '%s.%s' % (C.__module__, 'C')
222
224
223 with nt.assert_raises(KeyError):
225 with pytest.raises(KeyError):
224 f.pop(type_str)
226 f.pop(type_str)
225
227
226 f.for_type(type_str, foo_printer)
228 f.for_type(type_str, foo_printer)
227 f.pop(type_str)
229 f.pop(type_str)
228 with nt.assert_raises(KeyError):
230 with pytest.raises(KeyError):
229 f.lookup_by_type(C)
231 f.lookup_by_type(C)
230 with nt.assert_raises(KeyError):
232 with pytest.raises(KeyError):
231 f.pop(type_str)
233 f.pop(type_str)
232
234
233 f.for_type(C, foo_printer)
235 f.for_type(C, foo_printer)
234 nt.assert_is(f.pop(type_str, None), foo_printer)
236 assert f.pop(type_str, None) is foo_printer
235 with nt.assert_raises(KeyError):
237 with pytest.raises(KeyError):
236 f.lookup_by_type(C)
238 f.lookup_by_type(C)
237 with nt.assert_raises(KeyError):
239 with pytest.raises(KeyError):
238 f.pop(type_str)
240 f.pop(type_str)
239 nt.assert_is(f.pop(type_str, None), None)
241 assert f.pop(type_str, None) is None
240
242
241
243
242 def test_error_method():
244 def test_error_method():
@@ -247,10 +249,10 b' def test_error_method():'
247 bad = BadHTML()
249 bad = BadHTML()
248 with capture_output() as captured:
250 with capture_output() as captured:
249 result = f(bad)
251 result = f(bad)
250 nt.assert_is(result, None)
252 assert result is None
251 nt.assert_in("Traceback", captured.stdout)
253 assert "Traceback" in captured.stdout
252 nt.assert_in("Bad HTML", captured.stdout)
254 assert "Bad HTML" in captured.stdout
253 nt.assert_in("_repr_html_", captured.stdout)
255 assert "_repr_html_" in captured.stdout
254
256
255 def test_nowarn_notimplemented():
257 def test_nowarn_notimplemented():
256 f = HTMLFormatter()
258 f = HTMLFormatter()
@@ -260,7 +262,7 b' def test_nowarn_notimplemented():'
260 h = HTMLNotImplemented()
262 h = HTMLNotImplemented()
261 with capture_output() as captured:
263 with capture_output() as captured:
262 result = f(h)
264 result = f(h)
263 nt.assert_is(result, None)
265 assert result is None
264 assert "" == captured.stderr
266 assert "" == captured.stderr
265 assert "" == captured.stdout
267 assert "" == captured.stdout
266
268
@@ -270,10 +272,10 b' def test_warn_error_for_type():'
270 f.for_type(int, lambda i: name_error)
272 f.for_type(int, lambda i: name_error)
271 with capture_output() as captured:
273 with capture_output() as captured:
272 result = f(5)
274 result = f(5)
273 nt.assert_is(result, None)
275 assert result is None
274 nt.assert_in("Traceback", captured.stdout)
276 assert "Traceback" in captured.stdout
275 nt.assert_in("NameError", captured.stdout)
277 assert "NameError" in captured.stdout
276 nt.assert_in("name_error", captured.stdout)
278 assert "name_error" in captured.stdout
277
279
278 def test_error_pretty_method():
280 def test_error_pretty_method():
279 f = PlainTextFormatter()
281 f = PlainTextFormatter()
@@ -283,11 +285,11 b' def test_error_pretty_method():'
283 bad = BadPretty()
285 bad = BadPretty()
284 with capture_output() as captured:
286 with capture_output() as captured:
285 result = f(bad)
287 result = f(bad)
286 nt.assert_is(result, None)
288 assert result is None
287 nt.assert_in("Traceback", captured.stdout)
289 assert "Traceback" in captured.stdout
288 nt.assert_in("_repr_pretty_", captured.stdout)
290 assert "_repr_pretty_" in captured.stdout
289 nt.assert_in("given", captured.stdout)
291 assert "given" in captured.stdout
290 nt.assert_in("argument", captured.stdout)
292 assert "argument" in captured.stdout
291
293
292
294
293 def test_bad_repr_traceback():
295 def test_bad_repr_traceback():
@@ -296,10 +298,10 b' def test_bad_repr_traceback():'
296 with capture_output() as captured:
298 with capture_output() as captured:
297 result = f(bad)
299 result = f(bad)
298 # catches error, returns None
300 # catches error, returns None
299 nt.assert_is(result, None)
301 assert result is None
300 nt.assert_in("Traceback", captured.stdout)
302 assert "Traceback" in captured.stdout
301 nt.assert_in("__repr__", captured.stdout)
303 assert "__repr__" in captured.stdout
302 nt.assert_in("ValueError", captured.stdout)
304 assert "ValueError" in captured.stdout
303
305
304
306
305 class MakePDF(object):
307 class MakePDF(object):
@@ -319,8 +321,8 b' def test_print_method_bound():'
319 return "hello"
321 return "hello"
320 with capture_output() as captured:
322 with capture_output() as captured:
321 result = f(MyHTML)
323 result = f(MyHTML)
322 nt.assert_is(result, None)
324 assert result is None
323 nt.assert_not_in("FormatterWarning", captured.stderr)
325 assert "FormatterWarning" not in captured.stderr
324
326
325 with capture_output() as captured:
327 with capture_output() as captured:
326 result = f(MyHTML())
328 result = f(MyHTML())
@@ -341,8 +343,8 b' def test_print_method_weird():'
341 with capture_output() as captured:
343 with capture_output() as captured:
342 result = f(text_hat)
344 result = f(text_hat)
343
345
344 nt.assert_is(result, None)
346 assert result is None
345 nt.assert_not_in("FormatterWarning", captured.stderr)
347 assert "FormatterWarning" not in captured.stderr
346
348
347 class CallableMagicHat(object):
349 class CallableMagicHat(object):
348 def __getattr__(self, key):
350 def __getattr__(self, key):
@@ -362,8 +364,8 b' def test_print_method_weird():'
362 with capture_output() as captured:
364 with capture_output() as captured:
363 result = f(bad)
365 result = f(bad)
364
366
365 nt.assert_is(result, None)
367 assert result is None
366 nt.assert_not_in("FormatterWarning", captured.stderr)
368 assert "FormatterWarning" not in captured.stderr
367
369
368
370
369 def test_format_config():
371 def test_format_config():
@@ -372,12 +374,12 b' def test_format_config():'
372 cfg = Config()
374 cfg = Config()
373 with capture_output() as captured:
375 with capture_output() as captured:
374 result = f(cfg)
376 result = f(cfg)
375 nt.assert_is(result, None)
377 assert result is None
376 assert captured.stderr == ""
378 assert captured.stderr == ""
377
379
378 with capture_output() as captured:
380 with capture_output() as captured:
379 result = f(Config)
381 result = f(Config)
380 nt.assert_is(result, None)
382 assert result is None
381 assert captured.stderr == ""
383 assert captured.stderr == ""
382
384
383
385
@@ -4,9 +4,6 b''
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # third party
8 import nose.tools as nt
9
10 # our own packages
7 # our own packages
11 from IPython.core import autocall
8 from IPython.core import autocall
12 from IPython.testing import tools as tt
9 from IPython.testing import tools as tt
@@ -91,4 +88,4 b' def test_handlers():'
91 ])
88 ])
92 ip.magic('autocall 1')
89 ip.magic('autocall 1')
93
90
94 nt.assert_equal(failures, [])
91 assert failures == []
@@ -13,9 +13,6 b' import tempfile'
13 from datetime import datetime
13 from datetime import datetime
14 import sqlite3
14 import sqlite3
15
15
16 # third party
17 import nose.tools as nt
18
19 # our own packages
16 # our own packages
20 from traitlets.config.loader import Config
17 from traitlets.config.loader import Config
21 from IPython.utils.tempdir import TemporaryDirectory
18 from IPython.utils.tempdir import TemporaryDirectory
@@ -23,7 +20,7 b' from IPython.core.history import HistoryManager, extract_hist_ranges'
23 from IPython.testing.decorators import skipif
20 from IPython.testing.decorators import skipif
24
21
25 def test_proper_default_encoding():
22 def test_proper_default_encoding():
26 nt.assert_equal(sys.getdefaultencoding(), "utf-8")
23 assert sys.getdefaultencoding() == "utf-8"
27
24
28 @skipif(sqlite3.sqlite_version_info > (3,24,0))
25 @skipif(sqlite3.sqlite_version_info > (3,24,0))
29 def test_history():
26 def test_history():
@@ -34,7 +31,7 b' def test_history():'
34 hist_file = tmp_path / "history.sqlite"
31 hist_file = tmp_path / "history.sqlite"
35 try:
32 try:
36 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
33 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
37 hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='€Æ¾÷ß'"]
34 hist = ["a=1", "def f():\n test = 1\n return test", "b='€Æ¾÷ß'"]
38 for i, h in enumerate(hist, start=1):
35 for i, h in enumerate(hist, start=1):
39 ip.history_manager.store_inputs(i, h)
36 ip.history_manager.store_inputs(i, h)
40
37
@@ -43,13 +40,15 b' def test_history():'
43 ip.history_manager.output_hist_reprs[3] = "spam"
40 ip.history_manager.output_hist_reprs[3] = "spam"
44 ip.history_manager.store_output(3)
41 ip.history_manager.store_output(3)
45
42
46 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
43 assert ip.history_manager.input_hist_raw == [""] + hist
47
44
48 # Detailed tests for _get_range_session
45 # Detailed tests for _get_range_session
49 grs = ip.history_manager._get_range_session
46 grs = ip.history_manager._get_range_session
50 nt.assert_equal(list(grs(start=2,stop=-1)), list(zip([0], [2], hist[1:-1])))
47 assert list(grs(start=2, stop=-1)) == list(zip([0], [2], hist[1:-1]))
51 nt.assert_equal(list(grs(start=-2)), list(zip([0,0], [2,3], hist[-2:])))
48 assert list(grs(start=-2)) == list(zip([0, 0], [2, 3], hist[-2:]))
52 nt.assert_equal(list(grs(output=True)), list(zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam']))))
49 assert list(grs(output=True)) == list(
50 zip([0, 0, 0], [1, 2, 3], zip(hist, [None, None, "spam"]))
51 )
53
52
54 # Check whether specifying a range beyond the end of the current
53 # Check whether specifying a range beyond the end of the current
55 # session results in an error (gh-804)
54 # session results in an error (gh-804)
@@ -63,17 +62,14 b' def test_history():'
63
62
64 # New session
63 # New session
65 ip.history_manager.reset()
64 ip.history_manager.reset()
66 newcmds = [u"z=5",
65 newcmds = ["z=5", "class X(object):\n pass", "k='p'", "z=5"]
67 u"class X(object):\n pass",
68 u"k='p'",
69 u"z=5"]
70 for i, cmd in enumerate(newcmds, start=1):
66 for i, cmd in enumerate(newcmds, start=1):
71 ip.history_manager.store_inputs(i, cmd)
67 ip.history_manager.store_inputs(i, cmd)
72 gothist = ip.history_manager.get_range(start=1, stop=4)
68 gothist = ip.history_manager.get_range(start=1, stop=4)
73 nt.assert_equal(list(gothist), list(zip([0,0,0],[1,2,3], newcmds)))
69 assert list(gothist) == list(zip([0, 0, 0], [1, 2, 3], newcmds))
74 # Previous session:
70 # Previous session:
75 gothist = ip.history_manager.get_range(-1, 1, 4)
71 gothist = ip.history_manager.get_range(-1, 1, 4)
76 nt.assert_equal(list(gothist), list(zip([1,1,1],[1,2,3], hist)))
72 assert list(gothist) == list(zip([1, 1, 1], [1, 2, 3], hist))
77
73
78 newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)]
74 newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)]
79
75
@@ -82,62 +78,61 b' def test_history():'
82 include_latest=True)
78 include_latest=True)
83 expected = [(1, 3, (hist[-1], "spam"))] \
79 expected = [(1, 3, (hist[-1], "spam"))] \
84 + [(s, n, (c, None)) for (s, n, c) in newhist]
80 + [(s, n, (c, None)) for (s, n, c) in newhist]
85 nt.assert_equal(list(gothist), expected)
81 assert list(gothist) == expected
86
82
87 gothist = ip.history_manager.get_tail(2)
83 gothist = ip.history_manager.get_tail(2)
88 expected = newhist[-3:-1]
84 expected = newhist[-3:-1]
89 nt.assert_equal(list(gothist), expected)
85 assert list(gothist) == expected
90
86
91 # Check get_hist_search
87 # Check get_hist_search
92
88
93 gothist = ip.history_manager.search("*test*")
89 gothist = ip.history_manager.search("*test*")
94 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
90 assert list(gothist) == [(1, 2, hist[1])]
95
91
96 gothist = ip.history_manager.search("*=*")
92 gothist = ip.history_manager.search("*=*")
97 nt.assert_equal(list(gothist),
93 assert list(gothist) == [
98 [(1, 1, hist[0]),
94 (1, 1, hist[0]),
99 (1, 2, hist[1]),
95 (1, 2, hist[1]),
100 (1, 3, hist[2]),
96 (1, 3, hist[2]),
101 newhist[0],
97 newhist[0],
102 newhist[2],
98 newhist[2],
103 newhist[3]])
99 newhist[3],
100 ]
104
101
105 gothist = ip.history_manager.search("*=*", n=4)
102 gothist = ip.history_manager.search("*=*", n=4)
106 nt.assert_equal(list(gothist),
103 assert list(gothist) == [
107 [(1, 3, hist[2]),
104 (1, 3, hist[2]),
108 newhist[0],
105 newhist[0],
109 newhist[2],
106 newhist[2],
110 newhist[3]])
107 newhist[3],
108 ]
111
109
112 gothist = ip.history_manager.search("*=*", unique=True)
110 gothist = ip.history_manager.search("*=*", unique=True)
113 nt.assert_equal(list(gothist),
111 assert list(gothist) == [
114 [(1, 1, hist[0]),
112 (1, 1, hist[0]),
115 (1, 2, hist[1]),
113 (1, 2, hist[1]),
116 (1, 3, hist[2]),
114 (1, 3, hist[2]),
117 newhist[2],
115 newhist[2],
118 newhist[3]])
116 newhist[3],
117 ]
119
118
120 gothist = ip.history_manager.search("*=*", unique=True, n=3)
119 gothist = ip.history_manager.search("*=*", unique=True, n=3)
121 nt.assert_equal(list(gothist),
120 assert list(gothist) == [(1, 3, hist[2]), newhist[2], newhist[3]]
122 [(1, 3, hist[2]),
123 newhist[2],
124 newhist[3]])
125
121
126 gothist = ip.history_manager.search("b*", output=True)
122 gothist = ip.history_manager.search("b*", output=True)
127 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
123 assert list(gothist) == [(1, 3, (hist[2], "spam"))]
128
124
129 # Cross testing: check that magic %save can get previous session.
125 # Cross testing: check that magic %save can get previous session.
130 testfilename = (tmp_path / "test.py").resolve()
126 testfilename = (tmp_path / "test.py").resolve()
131 ip.magic("save " + str(testfilename) + " ~1/1-3")
127 ip.magic("save " + str(testfilename) + " ~1/1-3")
132 with io.open(testfilename, encoding='utf-8') as testfile:
128 with io.open(testfilename, encoding="utf-8") as testfile:
133 nt.assert_equal(testfile.read(),
129 assert testfile.read() == "# coding: utf-8\n" + "\n".join(hist) + "\n"
134 u"# coding: utf-8\n" + u"\n".join(hist)+u"\n")
135
130
136 # Duplicate line numbers - check that it doesn't crash, and
131 # Duplicate line numbers - check that it doesn't crash, and
137 # gets a new session
132 # gets a new session
138 ip.history_manager.store_inputs(1, "rogue")
133 ip.history_manager.store_inputs(1, "rogue")
139 ip.history_manager.writeout_cache()
134 ip.history_manager.writeout_cache()
140 nt.assert_equal(ip.history_manager.session_number, 3)
135 assert ip.history_manager.session_number == 3
141 finally:
136 finally:
142 # Ensure saving thread is shut down before we try to clean up the files
137 # Ensure saving thread is shut down before we try to clean up the files
143 ip.history_manager.save_thread.stop()
138 ip.history_manager.save_thread.stop()
@@ -158,14 +153,14 b' def test_extract_hist_ranges():'
158 (-7, 1, 6),
153 (-7, 1, 6),
159 (-10, 1, None)]
154 (-10, 1, None)]
160 actual = list(extract_hist_ranges(instr))
155 actual = list(extract_hist_ranges(instr))
161 nt.assert_equal(actual, expected)
156 assert actual == expected
162
157
163
158
164 def test_extract_hist_ranges_empty_str():
159 def test_extract_hist_ranges_empty_str():
165 instr = ""
160 instr = ""
166 expected = [(0, 1, None)] # 0 == current session, None == to end
161 expected = [(0, 1, None)] # 0 == current session, None == to end
167 actual = list(extract_hist_ranges(instr))
162 actual = list(extract_hist_ranges(instr))
168 nt.assert_equal(actual, expected)
163 assert actual == expected
169
164
170
165
171 def test_magic_rerun():
166 def test_magic_rerun():
@@ -173,14 +168,14 b' def test_magic_rerun():'
173 ip = get_ipython()
168 ip = get_ipython()
174 ip.run_cell("a = 10", store_history=True)
169 ip.run_cell("a = 10", store_history=True)
175 ip.run_cell("a += 1", store_history=True)
170 ip.run_cell("a += 1", store_history=True)
176 nt.assert_equal(ip.user_ns["a"], 11)
171 assert ip.user_ns["a"] == 11
177 ip.run_cell("%rerun", store_history=True)
172 ip.run_cell("%rerun", store_history=True)
178 nt.assert_equal(ip.user_ns["a"], 12)
173 assert ip.user_ns["a"] == 12
179
174
180 def test_timestamp_type():
175 def test_timestamp_type():
181 ip = get_ipython()
176 ip = get_ipython()
182 info = ip.history_manager.get_session_info()
177 info = ip.history_manager.get_session_info()
183 nt.assert_true(isinstance(info[1], datetime))
178 assert isinstance(info[1], datetime)
184
179
185 def test_hist_file_config():
180 def test_hist_file_config():
186 cfg = Config()
181 cfg = Config()
@@ -188,7 +183,7 b' def test_hist_file_config():'
188 cfg.HistoryManager.hist_file = Path(tfile.name)
183 cfg.HistoryManager.hist_file = Path(tfile.name)
189 try:
184 try:
190 hm = HistoryManager(shell=get_ipython(), config=cfg)
185 hm = HistoryManager(shell=get_ipython(), config=cfg)
191 nt.assert_equal(hm.hist_file, cfg.HistoryManager.hist_file)
186 assert hm.hist_file == cfg.HistoryManager.hist_file
192 finally:
187 finally:
193 try:
188 try:
194 Path(tfile.name).unlink()
189 Path(tfile.name).unlink()
@@ -210,14 +205,14 b' def test_histmanager_disabled():'
210 cfg.HistoryManager.hist_file = hist_file
205 cfg.HistoryManager.hist_file = hist_file
211 try:
206 try:
212 ip.history_manager = HistoryManager(shell=ip, config=cfg)
207 ip.history_manager = HistoryManager(shell=ip, config=cfg)
213 hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='€Æ¾÷ß'"]
208 hist = ["a=1", "def f():\n test = 1\n return test", "b='€Æ¾÷ß'"]
214 for i, h in enumerate(hist, start=1):
209 for i, h in enumerate(hist, start=1):
215 ip.history_manager.store_inputs(i, h)
210 ip.history_manager.store_inputs(i, h)
216 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
211 assert ip.history_manager.input_hist_raw == [""] + hist
217 ip.history_manager.reset()
212 ip.history_manager.reset()
218 ip.history_manager.end_session()
213 ip.history_manager.end_session()
219 finally:
214 finally:
220 ip.history_manager = hist_manager_ori
215 ip.history_manager = hist_manager_ori
221
216
222 # hist_file should not be created
217 # hist_file should not be created
223 nt.assert_false(hist_file.exists())
218 assert hist_file.exists() is False
@@ -6,7 +6,6 b''
6 # Imports
6 # Imports
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8
8
9 import nose.tools as nt
10 from IPython.core.error import TryNext
9 from IPython.core.error import TryNext
11 from IPython.core.hooks import CommandChainDispatcher
10 from IPython.core.hooks import CommandChainDispatcher
12
11
@@ -38,27 +37,26 b' class Fail(object):'
38
37
39 def test_command_chain_dispatcher_ff():
38 def test_command_chain_dispatcher_ff():
40 """Test two failing hooks"""
39 """Test two failing hooks"""
41 fail1 = Fail(u'fail1')
40 fail1 = Fail("fail1")
42 fail2 = Fail(u'fail2')
41 fail2 = Fail("fail2")
43 dp = CommandChainDispatcher([(0, fail1),
42 dp = CommandChainDispatcher([(0, fail1), (10, fail2)])
44 (10, fail2)])
45
43
46 try:
44 try:
47 dp()
45 dp()
48 except TryNext as e:
46 except TryNext as e:
49 nt.assert_equal(str(e), u'fail2')
47 assert str(e) == "fail2"
50 else:
48 else:
51 assert False, "Expected exception was not raised."
49 assert False, "Expected exception was not raised."
52
50
53 nt.assert_true(fail1.called)
51 assert fail1.called is True
54 nt.assert_true(fail2.called)
52 assert fail2.called is True
55
53
56 def test_command_chain_dispatcher_fofo():
54 def test_command_chain_dispatcher_fofo():
57 """Test a mixture of failing and succeeding hooks."""
55 """Test a mixture of failing and succeeding hooks."""
58 fail1 = Fail(u'fail1')
56 fail1 = Fail("fail1")
59 fail2 = Fail(u'fail2')
57 fail2 = Fail("fail2")
60 okay1 = Okay(u'okay1')
58 okay1 = Okay("okay1")
61 okay2 = Okay(u'okay2')
59 okay2 = Okay("okay2")
62
60
63 dp = CommandChainDispatcher([(0, fail1),
61 dp = CommandChainDispatcher([(0, fail1),
64 # (5, okay1), # add this later
62 # (5, okay1), # add this later
@@ -66,12 +64,12 b' def test_command_chain_dispatcher_fofo():'
66 (15, okay2)])
64 (15, okay2)])
67 dp.add(okay1, 5)
65 dp.add(okay1, 5)
68
66
69 nt.assert_equal(dp(), u'okay1')
67 assert dp() == "okay1"
70
68
71 nt.assert_true(fail1.called)
69 assert fail1.called is True
72 nt.assert_true(okay1.called)
70 assert okay1.called is True
73 nt.assert_false(fail2.called)
71 assert fail2.called is False
74 nt.assert_false(okay2.called)
72 assert okay2.called is False
75
73
76 def test_command_chain_dispatcher_eq_priority():
74 def test_command_chain_dispatcher_eq_priority():
77 okay1 = Okay(u'okay1')
75 okay1 = Okay(u'okay1')
@@ -8,8 +8,6 b''
8 import unittest
8 import unittest
9 import sys
9 import sys
10
10
11 import nose.tools as nt
12
13 from IPython.core import inputsplitter as isp
11 from IPython.core import inputsplitter as isp
14 from IPython.core.inputtransformer import InputTransformer
12 from IPython.core.inputtransformer import InputTransformer
15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
13 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
@@ -98,10 +96,10 b' def test_remove_comments():'
98
96
99 def test_get_input_encoding():
97 def test_get_input_encoding():
100 encoding = isp.get_input_encoding()
98 encoding = isp.get_input_encoding()
101 nt.assert_true(isinstance(encoding, str))
99 assert isinstance(encoding, str)
102 # simple-minded check that at least encoding a simple string works with the
100 # simple-minded check that at least encoding a simple string works with the
103 # encoding we got.
101 # encoding we got.
104 nt.assert_equal(u'test'.encode(encoding), b'test')
102 assert "test".encode(encoding) == b"test"
105
103
106
104
107 class NoInputEncodingTestCase(unittest.TestCase):
105 class NoInputEncodingTestCase(unittest.TestCase):
@@ -527,38 +525,38 b" if __name__ == '__main__':"
527 # Tests for cell magics support
525 # Tests for cell magics support
528
526
529 def test_last_blank():
527 def test_last_blank():
530 nt.assert_false(isp.last_blank(''))
528 assert isp.last_blank("") is False
531 nt.assert_false(isp.last_blank('abc'))
529 assert isp.last_blank("abc") is False
532 nt.assert_false(isp.last_blank('abc\n'))
530 assert isp.last_blank("abc\n") is False
533 nt.assert_false(isp.last_blank('abc\na'))
531 assert isp.last_blank("abc\na") is False
534
532
535 nt.assert_true(isp.last_blank('\n'))
533 assert isp.last_blank("\n") is True
536 nt.assert_true(isp.last_blank('\n '))
534 assert isp.last_blank("\n ") is True
537 nt.assert_true(isp.last_blank('abc\n '))
535 assert isp.last_blank("abc\n ") is True
538 nt.assert_true(isp.last_blank('abc\n\n'))
536 assert isp.last_blank("abc\n\n") is True
539 nt.assert_true(isp.last_blank('abc\nd\n\n'))
537 assert isp.last_blank("abc\nd\n\n") is True
540 nt.assert_true(isp.last_blank('abc\nd\ne\n\n'))
538 assert isp.last_blank("abc\nd\ne\n\n") is True
541 nt.assert_true(isp.last_blank('abc \n \n \n\n'))
539 assert isp.last_blank("abc \n \n \n\n") is True
542
540
543
541
544 def test_last_two_blanks():
542 def test_last_two_blanks():
545 nt.assert_false(isp.last_two_blanks(''))
543 assert isp.last_two_blanks("") is False
546 nt.assert_false(isp.last_two_blanks('abc'))
544 assert isp.last_two_blanks("abc") is False
547 nt.assert_false(isp.last_two_blanks('abc\n'))
545 assert isp.last_two_blanks("abc\n") is False
548 nt.assert_false(isp.last_two_blanks('abc\n\na'))
546 assert isp.last_two_blanks("abc\n\na") is False
549 nt.assert_false(isp.last_two_blanks('abc\n \n'))
547 assert isp.last_two_blanks("abc\n \n") is False
550 nt.assert_false(isp.last_two_blanks('abc\n\n'))
548 assert isp.last_two_blanks("abc\n\n") is False
551
549
552 nt.assert_true(isp.last_two_blanks('\n\n'))
550 assert isp.last_two_blanks("\n\n") is True
553 nt.assert_true(isp.last_two_blanks('\n\n '))
551 assert isp.last_two_blanks("\n\n ") is True
554 nt.assert_true(isp.last_two_blanks('\n \n'))
552 assert isp.last_two_blanks("\n \n") is True
555 nt.assert_true(isp.last_two_blanks('abc\n\n '))
553 assert isp.last_two_blanks("abc\n\n ") is True
556 nt.assert_true(isp.last_two_blanks('abc\n\n\n'))
554 assert isp.last_two_blanks("abc\n\n\n") is True
557 nt.assert_true(isp.last_two_blanks('abc\n\n \n'))
555 assert isp.last_two_blanks("abc\n\n \n") is True
558 nt.assert_true(isp.last_two_blanks('abc\n\n \n '))
556 assert isp.last_two_blanks("abc\n\n \n ") is True
559 nt.assert_true(isp.last_two_blanks('abc\n\n \n \n'))
557 assert isp.last_two_blanks("abc\n\n \n \n") is True
560 nt.assert_true(isp.last_two_blanks('abc\nd\n\n\n'))
558 assert isp.last_two_blanks("abc\nd\n\n\n") is True
561 nt.assert_true(isp.last_two_blanks('abc\nd\ne\nf\n\n\n'))
559 assert isp.last_two_blanks("abc\nd\ne\nf\n\n\n") is True
562
560
563
561
564 class CellMagicsCommon(object):
562 class CellMagicsCommon(object):
@@ -567,11 +565,11 b' class CellMagicsCommon(object):'
567 src = "%%cellm line\nbody\n"
565 src = "%%cellm line\nbody\n"
568 out = self.sp.transform_cell(src)
566 out = self.sp.transform_cell(src)
569 ref = "get_ipython().run_cell_magic('cellm', 'line', 'body')\n"
567 ref = "get_ipython().run_cell_magic('cellm', 'line', 'body')\n"
570 nt.assert_equal(out, ref)
568 assert out == ref
571
569
572 def test_cellmagic_help(self):
570 def test_cellmagic_help(self):
573 self.sp.push('%%cellm?')
571 self.sp.push('%%cellm?')
574 nt.assert_false(self.sp.push_accepts_more())
572 assert self.sp.push_accepts_more() is False
575
573
576 def tearDown(self):
574 def tearDown(self):
577 self.sp.reset()
575 self.sp.reset()
@@ -582,13 +580,13 b' class CellModeCellMagics(CellMagicsCommon, unittest.TestCase):'
582
580
583 def test_incremental(self):
581 def test_incremental(self):
584 sp = self.sp
582 sp = self.sp
585 sp.push('%%cellm firstline\n')
583 sp.push("%%cellm firstline\n")
586 nt.assert_true(sp.push_accepts_more()) #1
584 assert sp.push_accepts_more() is True # 1
587 sp.push('line2\n')
585 sp.push("line2\n")
588 nt.assert_true(sp.push_accepts_more()) #2
586 assert sp.push_accepts_more() is True # 2
589 sp.push('\n')
587 sp.push("\n")
590 # This should accept a blank line and carry on until the cell is reset
588 # This should accept a blank line and carry on until the cell is reset
591 nt.assert_true(sp.push_accepts_more()) #3
589 assert sp.push_accepts_more() is True # 3
592
590
593 def test_no_strip_coding(self):
591 def test_no_strip_coding(self):
594 src = '\n'.join([
592 src = '\n'.join([
@@ -597,7 +595,7 b' class CellModeCellMagics(CellMagicsCommon, unittest.TestCase):'
597 'print(u"üñîçø∂é")',
595 'print(u"üñîçø∂é")',
598 ])
596 ])
599 out = self.sp.transform_cell(src)
597 out = self.sp.transform_cell(src)
600 nt.assert_in('# coding: utf-8', out)
598 assert "# coding: utf-8" in out
601
599
602
600
603 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
601 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
@@ -605,11 +603,12 b' class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):'
605
603
606 def test_incremental(self):
604 def test_incremental(self):
607 sp = self.sp
605 sp = self.sp
608 sp.push('%%cellm line2\n')
606 sp.push("%%cellm line2\n")
609 nt.assert_true(sp.push_accepts_more()) #1
607 assert sp.push_accepts_more() is True # 1
610 sp.push('\n')
608 sp.push("\n")
611 # In this case, a blank line should end the cell magic
609 # In this case, a blank line should end the cell magic
612 nt.assert_false(sp.push_accepts_more()) #2
610 assert sp.push_accepts_more() is False # 2
611
613
612
614 indentation_samples = [
613 indentation_samples = [
615 ('a = 1', 0),
614 ('a = 1', 0),
@@ -1,5 +1,4 b''
1 import tokenize
1 import tokenize
2 import nose.tools as nt
3
2
4 from IPython.testing import tools as tt
3 from IPython.testing import tools as tt
5
4
@@ -25,7 +24,7 b' def transform_checker(tests, transformer, **kwargs):'
25 out = transformer.reset()
24 out = transformer.reset()
26 else:
25 else:
27 out = transformer.push(inp)
26 out = transformer.push(inp)
28 nt.assert_equal(out, tr)
27 assert out == tr
29 finally:
28 finally:
30 transformer.reset()
29 transformer.reset()
31
30
@@ -4,7 +4,6 b' Line-based transformers are the simpler ones; token-based transformers are'
4 more complex. See test_inputtransformer2_line for tests for line-based
4 more complex. See test_inputtransformer2_line for tests for line-based
5 transformations.
5 transformations.
6 """
6 """
7 import nose.tools as nt
8 import string
7 import string
9
8
10 from IPython.core import inputtransformer2 as ipt2
9 from IPython.core import inputtransformer2 as ipt2
@@ -147,9 +146,10 b' def check_make_token_by_line_never_ends_empty():'
147 """
146 """
148 from string import printable
147 from string import printable
149 for c in printable:
148 for c in printable:
150 nt.assert_not_equal(make_tokens_by_line(c)[-1], [])
149 assert make_tokens_by_line(c)[-1] != []
151 for k in printable:
150 for k in printable:
152 nt.assert_not_equal(make_tokens_by_line(c+k)[-1], [])
151 assert make_tokens_by_line(c + k)[-1] != []
152
153
153
154 def check_find(transformer, case, match=True):
154 def check_find(transformer, case, match=True):
155 sample, expected_start, _ = case
155 sample, expected_start, _ = case
@@ -157,21 +157,21 b' def check_find(transformer, case, match=True):'
157 res = transformer.find(tbl)
157 res = transformer.find(tbl)
158 if match:
158 if match:
159 # start_line is stored 0-indexed, expected values are 1-indexed
159 # start_line is stored 0-indexed, expected values are 1-indexed
160 nt.assert_equal((res.start_line+1, res.start_col), expected_start)
160 assert (res.start_line + 1, res.start_col) == expected_start
161 return res
161 return res
162 else:
162 else:
163 nt.assert_is(res, None)
163 assert res is None
164
164
165 def check_transform(transformer_cls, case):
165 def check_transform(transformer_cls, case):
166 lines, start, expected = case
166 lines, start, expected = case
167 transformer = transformer_cls(start)
167 transformer = transformer_cls(start)
168 nt.assert_equal(transformer.transform(lines), expected)
168 assert transformer.transform(lines) == expected
169
169
170 def test_continued_line():
170 def test_continued_line():
171 lines = MULTILINE_MAGIC_ASSIGN[0]
171 lines = MULTILINE_MAGIC_ASSIGN[0]
172 nt.assert_equal(ipt2.find_end_of_continued_line(lines, 1), 2)
172 assert ipt2.find_end_of_continued_line(lines, 1) == 2
173
173
174 nt.assert_equal(ipt2.assemble_continued_line(lines, (1, 5), 2), "foo bar")
174 assert ipt2.assemble_continued_line(lines, (1, 5), 2) == "foo bar"
175
175
176 def test_find_assign_magic():
176 def test_find_assign_magic():
177 check_find(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN)
177 check_find(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN)
@@ -217,12 +217,12 b' def test_find_help():'
217 check_find(ipt2.HelpEnd, case)
217 check_find(ipt2.HelpEnd, case)
218
218
219 tf = check_find(ipt2.HelpEnd, HELP_CONTINUED_LINE)
219 tf = check_find(ipt2.HelpEnd, HELP_CONTINUED_LINE)
220 nt.assert_equal(tf.q_line, 1)
220 assert tf.q_line == 1
221 nt.assert_equal(tf.q_col, 3)
221 assert tf.q_col == 3
222
222
223 tf = check_find(ipt2.HelpEnd, HELP_MULTILINE)
223 tf = check_find(ipt2.HelpEnd, HELP_MULTILINE)
224 nt.assert_equal(tf.q_line, 1)
224 assert tf.q_line == 1
225 nt.assert_equal(tf.q_col, 8)
225 assert tf.q_col == 8
226
226
227 # ? in a comment does not trigger help
227 # ? in a comment does not trigger help
228 check_find(ipt2.HelpEnd, (["foo # bar?\n"], None, None), match=False)
228 check_find(ipt2.HelpEnd, (["foo # bar?\n"], None, None), match=False)
@@ -231,16 +231,16 b' def test_find_help():'
231
231
232 def test_transform_help():
232 def test_transform_help():
233 tf = ipt2.HelpEnd((1, 0), (1, 9))
233 tf = ipt2.HelpEnd((1, 0), (1, 9))
234 nt.assert_equal(tf.transform(HELP_IN_EXPR[0]), HELP_IN_EXPR[2])
234 assert tf.transform(HELP_IN_EXPR[0]) == HELP_IN_EXPR[2]
235
235
236 tf = ipt2.HelpEnd((1, 0), (2, 3))
236 tf = ipt2.HelpEnd((1, 0), (2, 3))
237 nt.assert_equal(tf.transform(HELP_CONTINUED_LINE[0]), HELP_CONTINUED_LINE[2])
237 assert tf.transform(HELP_CONTINUED_LINE[0]) == HELP_CONTINUED_LINE[2]
238
238
239 tf = ipt2.HelpEnd((1, 0), (2, 8))
239 tf = ipt2.HelpEnd((1, 0), (2, 8))
240 nt.assert_equal(tf.transform(HELP_MULTILINE[0]), HELP_MULTILINE[2])
240 assert tf.transform(HELP_MULTILINE[0]) == HELP_MULTILINE[2]
241
241
242 tf = ipt2.HelpEnd((1, 0), (1, 0))
242 tf = ipt2.HelpEnd((1, 0), (1, 0))
243 nt.assert_equal(tf.transform(HELP_UNICODE[0]), HELP_UNICODE[2])
243 assert tf.transform(HELP_UNICODE[0]) == HELP_UNICODE[2]
244
244
245 def test_find_assign_op_dedent():
245 def test_find_assign_op_dedent():
246 """
246 """
@@ -250,31 +250,34 b' def test_find_assign_op_dedent():'
250 def __init__(self, s):
250 def __init__(self, s):
251 self.string = s
251 self.string = s
252
252
253 nt.assert_equal(_find_assign_op([Tk(s) for s in ('','a','=','b')]), 2)
253 assert _find_assign_op([Tk(s) for s in ("", "a", "=", "b")]) == 2
254 nt.assert_equal(_find_assign_op([Tk(s) for s in ('','(', 'a','=','b', ')', '=' ,'5')]), 6)
254 assert (
255 _find_assign_op([Tk(s) for s in ("", "(", "a", "=", "b", ")", "=", "5")]) == 6
256 )
257
255
258
256 def test_check_complete():
259 def test_check_complete():
257 cc = ipt2.TransformerManager().check_complete
260 cc = ipt2.TransformerManager().check_complete
258 nt.assert_equal(cc("a = 1"), ("complete", None))
261 assert cc("a = 1") == ("complete", None)
259 nt.assert_equal(cc("for a in range(5):"), ("incomplete", 4))
262 assert cc("for a in range(5):") == ("incomplete", 4)
260 nt.assert_equal(cc("for a in range(5):\n if a > 0:"), ("incomplete", 8))
263 assert cc("for a in range(5):\n if a > 0:") == ("incomplete", 8)
261 nt.assert_equal(cc("raise = 2"), ("invalid", None))
264 assert cc("raise = 2") == ("invalid", None)
262 nt.assert_equal(cc("a = [1,\n2,"), ("incomplete", 0))
265 assert cc("a = [1,\n2,") == ("incomplete", 0)
263 nt.assert_equal(cc("(\n))"), ("incomplete", 0))
266 assert cc("(\n))") == ("incomplete", 0)
264 nt.assert_equal(cc("\\\r\n"), ("incomplete", 0))
267 assert cc("\\\r\n") == ("incomplete", 0)
265 nt.assert_equal(cc("a = '''\n hi"), ("incomplete", 3))
268 assert cc("a = '''\n hi") == ("incomplete", 3)
266 nt.assert_equal(cc("def a():\n x=1\n global x"), ("invalid", None))
269 assert cc("def a():\n x=1\n global x") == ("invalid", None)
267 nt.assert_equal(cc("a \\ "), ("invalid", None)) # Nothing allowed after backslash
270 assert cc("a \\ ") == ("invalid", None) # Nothing allowed after backslash
268 nt.assert_equal(cc("1\\\n+2"), ("complete", None))
271 assert cc("1\\\n+2") == ("complete", None)
269 nt.assert_equal(cc("exit"), ("complete", None))
272 assert cc("exit") == ("complete", None)
270
273
271 example = dedent("""
274 example = dedent("""
272 if True:
275 if True:
273 a=1""" )
276 a=1""" )
274
277
275 nt.assert_equal(cc(example), ('incomplete', 4))
278 assert cc(example) == ("incomplete", 4)
276 nt.assert_equal(cc(example+'\n'), ('complete', None))
279 assert cc(example + "\n") == ("complete", None)
277 nt.assert_equal(cc(example+'\n '), ('complete', None))
280 assert cc(example + "\n ") == ("complete", None)
278
281
279 # no need to loop on all the letters/numbers.
282 # no need to loop on all the letters/numbers.
280 short = '12abAB'+string.printable[62:]
283 short = '12abAB'+string.printable[62:]
@@ -284,7 +287,8 b' def test_check_complete():'
284 for k in short:
287 for k in short:
285 cc(c+k)
288 cc(c+k)
286
289
287 nt.assert_equal(cc("def f():\n x=0\n \\\n "), ('incomplete', 2))
290 assert cc("def f():\n x=0\n \\\n ") == ("incomplete", 2)
291
288
292
289 def test_check_complete_II():
293 def test_check_complete_II():
290 """
294 """
@@ -294,7 +298,7 b' def test_check_complete_II():'
294
298
295 """
299 """
296 cc = ipt2.TransformerManager().check_complete
300 cc = ipt2.TransformerManager().check_complete
297 nt.assert_equal(cc('''def foo():\n """'''), ('incomplete', 4))
301 assert cc('''def foo():\n """''') == ("incomplete", 4)
298
302
299
303
300 def test_check_complete_invalidates_sunken_brackets():
304 def test_check_complete_invalidates_sunken_brackets():
@@ -303,16 +307,16 b' def test_check_complete_invalidates_sunken_brackets():'
303 interpreted as invalid
307 interpreted as invalid
304 """
308 """
305 cc = ipt2.TransformerManager().check_complete
309 cc = ipt2.TransformerManager().check_complete
306 nt.assert_equal(cc(")"), ("invalid", None))
310 assert cc(")") == ("invalid", None)
307 nt.assert_equal(cc("]"), ("invalid", None))
311 assert cc("]") == ("invalid", None)
308 nt.assert_equal(cc("}"), ("invalid", None))
312 assert cc("}") == ("invalid", None)
309 nt.assert_equal(cc(")("), ("invalid", None))
313 assert cc(")(") == ("invalid", None)
310 nt.assert_equal(cc("]["), ("invalid", None))
314 assert cc("][") == ("invalid", None)
311 nt.assert_equal(cc("}{"), ("invalid", None))
315 assert cc("}{") == ("invalid", None)
312 nt.assert_equal(cc("]()("), ("invalid", None))
316 assert cc("]()(") == ("invalid", None)
313 nt.assert_equal(cc("())("), ("invalid", None))
317 assert cc("())(") == ("invalid", None)
314 nt.assert_equal(cc(")[]("), ("invalid", None))
318 assert cc(")[](") == ("invalid", None)
315 nt.assert_equal(cc("()]("), ("invalid", None))
319 assert cc("()](") == ("invalid", None)
316
320
317
321
318 def test_null_cleanup_transformer():
322 def test_null_cleanup_transformer():
@@ -21,8 +21,6 b' from unittest import mock'
21
21
22 from os.path import join
22 from os.path import join
23
23
24 import nose.tools as nt
25
26 from IPython.core.error import InputRejected
24 from IPython.core.error import InputRejected
27 from IPython.core.inputtransformer import InputTransformer
25 from IPython.core.inputtransformer import InputTransformer
28 from IPython.core import interactiveshell
26 from IPython.core import interactiveshell
@@ -220,32 +218,38 b' class InteractiveShellTestCase(unittest.TestCase):'
220 def test_var_expand_local(self):
218 def test_var_expand_local(self):
221 """Test local variable expansion in !system and %magic calls"""
219 """Test local variable expansion in !system and %magic calls"""
222 # !system
220 # !system
223 ip.run_cell('def test():\n'
221 ip.run_cell(
222 "def test():\n"
224 ' lvar = "ttt"\n'
223 ' lvar = "ttt"\n'
225 ' ret = !echo {lvar}\n'
224 " ret = !echo {lvar}\n"
226 ' return ret[0]\n')
225 " return ret[0]\n"
227 res = ip.user_ns['test']()
226 )
228 nt.assert_in('ttt', res)
227 res = ip.user_ns["test"]()
228 self.assertIn("ttt", res)
229
229
230 # %magic
230 # %magic
231 ip.run_cell('def makemacro():\n'
231 ip.run_cell(
232 "def makemacro():\n"
232 ' macroname = "macro_var_expand_locals"\n'
233 ' macroname = "macro_var_expand_locals"\n'
233 ' %macro {macroname} codestr\n')
234 " %macro {macroname} codestr\n"
234 ip.user_ns['codestr'] = "str(12)"
235 )
235 ip.run_cell('makemacro()')
236 ip.user_ns["codestr"] = "str(12)"
236 nt.assert_in('macro_var_expand_locals', ip.user_ns)
237 ip.run_cell("makemacro()")
238 self.assertIn("macro_var_expand_locals", ip.user_ns)
237
239
238 def test_var_expand_self(self):
240 def test_var_expand_self(self):
239 """Test variable expansion with the name 'self', which was failing.
241 """Test variable expansion with the name 'self', which was failing.
240
242
241 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
243 See https://github.com/ipython/ipython/issues/1878#issuecomment-7698218
242 """
244 """
243 ip.run_cell('class cTest:\n'
245 ip.run_cell(
246 "class cTest:\n"
244 ' classvar="see me"\n'
247 ' classvar="see me"\n'
245 ' def test(self):\n'
248 " def test(self):\n"
246 ' res = !echo Variable: {self.classvar}\n'
249 " res = !echo Variable: {self.classvar}\n"
247 ' return res[0]\n')
250 " return res[0]\n"
248 nt.assert_in('see me', ip.user_ns['cTest']().test())
251 )
252 self.assertIn("see me", ip.user_ns["cTest"]().test())
249
253
250 def test_bad_var_expand(self):
254 def test_bad_var_expand(self):
251 """var_expand on invalid formats shouldn't raise"""
255 """var_expand on invalid formats shouldn't raise"""
@@ -346,7 +350,7 b' class InteractiveShellTestCase(unittest.TestCase):'
346 info = dict(found=True, isalias=False, ismagic=True,
350 info = dict(found=True, isalias=False, ismagic=True,
347 namespace = 'IPython internal', obj= lmagic.__wrapped__,
351 namespace = 'IPython internal', obj= lmagic.__wrapped__,
348 parent = None)
352 parent = None)
349 nt.assert_equal(lfind, info)
353 self.assertEqual(lfind, info)
350
354
351 def test_ofind_cell_magic(self):
355 def test_ofind_cell_magic(self):
352 from IPython.core.magic import register_cell_magic
356 from IPython.core.magic import register_cell_magic
@@ -360,7 +364,7 b' class InteractiveShellTestCase(unittest.TestCase):'
360 info = dict(found=True, isalias=False, ismagic=True,
364 info = dict(found=True, isalias=False, ismagic=True,
361 namespace = 'IPython internal', obj= cmagic.__wrapped__,
365 namespace = 'IPython internal', obj= cmagic.__wrapped__,
362 parent = None)
366 parent = None)
363 nt.assert_equal(find, info)
367 self.assertEqual(find, info)
364
368
365 def test_ofind_property_with_error(self):
369 def test_ofind_property_with_error(self):
366 class A(object):
370 class A(object):
@@ -372,7 +376,7 b' class InteractiveShellTestCase(unittest.TestCase):'
372 found = ip._ofind('a.foo', [('locals', locals())])
376 found = ip._ofind('a.foo', [('locals', locals())])
373 info = dict(found=True, isalias=False, ismagic=False,
377 info = dict(found=True, isalias=False, ismagic=False,
374 namespace='locals', obj=A.foo, parent=a)
378 namespace='locals', obj=A.foo, parent=a)
375 nt.assert_equal(found, info)
379 self.assertEqual(found, info)
376
380
377 def test_ofind_multiple_attribute_lookups(self):
381 def test_ofind_multiple_attribute_lookups(self):
378 class A(object):
382 class A(object):
@@ -387,7 +391,7 b' class InteractiveShellTestCase(unittest.TestCase):'
387 found = ip._ofind('a.a.a.foo', [('locals', locals())])
391 found = ip._ofind('a.a.a.foo', [('locals', locals())])
388 info = dict(found=True, isalias=False, ismagic=False,
392 info = dict(found=True, isalias=False, ismagic=False,
389 namespace='locals', obj=A.foo, parent=a.a.a)
393 namespace='locals', obj=A.foo, parent=a.a.a)
390 nt.assert_equal(found, info)
394 self.assertEqual(found, info)
391
395
392 def test_ofind_slotted_attributes(self):
396 def test_ofind_slotted_attributes(self):
393 class A(object):
397 class A(object):
@@ -399,12 +403,12 b' class InteractiveShellTestCase(unittest.TestCase):'
399 found = ip._ofind('a.foo', [('locals', locals())])
403 found = ip._ofind('a.foo', [('locals', locals())])
400 info = dict(found=True, isalias=False, ismagic=False,
404 info = dict(found=True, isalias=False, ismagic=False,
401 namespace='locals', obj=a.foo, parent=a)
405 namespace='locals', obj=a.foo, parent=a)
402 nt.assert_equal(found, info)
406 self.assertEqual(found, info)
403
407
404 found = ip._ofind('a.bar', [('locals', locals())])
408 found = ip._ofind('a.bar', [('locals', locals())])
405 info = dict(found=False, isalias=False, ismagic=False,
409 info = dict(found=False, isalias=False, ismagic=False,
406 namespace=None, obj=None, parent=a)
410 namespace=None, obj=None, parent=a)
407 nt.assert_equal(found, info)
411 self.assertEqual(found, info)
408
412
409 def test_ofind_prefers_property_to_instance_level_attribute(self):
413 def test_ofind_prefers_property_to_instance_level_attribute(self):
410 class A(object):
414 class A(object):
@@ -412,10 +416,10 b' class InteractiveShellTestCase(unittest.TestCase):'
412 def foo(self):
416 def foo(self):
413 return 'bar'
417 return 'bar'
414 a = A()
418 a = A()
415 a.__dict__['foo'] = 'baz'
419 a.__dict__["foo"] = "baz"
416 nt.assert_equal(a.foo, 'bar')
420 self.assertEqual(a.foo, "bar")
417 found = ip._ofind('a.foo', [('locals', locals())])
421 found = ip._ofind("a.foo", [("locals", locals())])
418 nt.assert_is(found['obj'], A.foo)
422 self.assertIs(found["obj"], A.foo)
419
423
420 def test_custom_syntaxerror_exception(self):
424 def test_custom_syntaxerror_exception(self):
421 called = []
425 called = []
@@ -819,7 +823,7 b' class TestAstTransformError(unittest.TestCase):'
819 ip.run_cell("1 + 2")
823 ip.run_cell("1 + 2")
820
824
821 # This should have been removed.
825 # This should have been removed.
822 nt.assert_not_in(err_transformer, ip.ast_transformers)
826 self.assertNotIn(err_transformer, ip.ast_transformers)
823
827
824
828
825 class StringRejector(ast.NodeTransformer):
829 class StringRejector(ast.NodeTransformer):
@@ -889,20 +893,20 b' def test_user_variables():'
889 keys = {'dummy', 'doesnotexist'}
893 keys = {'dummy', 'doesnotexist'}
890 r = ip.user_expressions({ key:key for key in keys})
894 r = ip.user_expressions({ key:key for key in keys})
891
895
892 nt.assert_equal(keys, set(r.keys()))
896 assert keys == set(r.keys())
893 dummy = r['dummy']
897 dummy = r["dummy"]
894 nt.assert_equal({'status', 'data', 'metadata'}, set(dummy.keys()))
898 assert {"status", "data", "metadata"} == set(dummy.keys())
895 nt.assert_equal(dummy['status'], 'ok')
899 assert dummy["status"] == "ok"
896 data = dummy['data']
900 data = dummy["data"]
897 metadata = dummy['metadata']
901 metadata = dummy["metadata"]
898 nt.assert_equal(data.get('text/html'), d._repr_html_())
902 assert data.get("text/html") == d._repr_html_()
899 js, jsmd = d._repr_javascript_()
903 js, jsmd = d._repr_javascript_()
900 nt.assert_equal(data.get('application/javascript'), js)
904 assert data.get("application/javascript") == js
901 nt.assert_equal(metadata.get('application/javascript'), jsmd)
905 assert metadata.get("application/javascript") == jsmd
902
906
903 dne = r['doesnotexist']
907 dne = r["doesnotexist"]
904 nt.assert_equal(dne['status'], 'error')
908 assert dne["status"] == "error"
905 nt.assert_equal(dne['ename'], 'NameError')
909 assert dne["ename"] == "NameError"
906
910
907 # back to text only
911 # back to text only
908 ip.display_formatter.active_types = ['text/plain']
912 ip.display_formatter.active_types = ['text/plain']
@@ -917,17 +921,17 b' def test_user_expression():'
917 r = ip.user_expressions(query)
921 r = ip.user_expressions(query)
918 import pprint
922 import pprint
919 pprint.pprint(r)
923 pprint.pprint(r)
920 nt.assert_equal(set(r.keys()), set(query.keys()))
924 assert set(r.keys()) == set(query.keys())
921 a = r['a']
925 a = r["a"]
922 nt.assert_equal({'status', 'data', 'metadata'}, set(a.keys()))
926 assert {"status", "data", "metadata"} == set(a.keys())
923 nt.assert_equal(a['status'], 'ok')
927 assert a["status"] == "ok"
924 data = a['data']
928 data = a["data"]
925 metadata = a['metadata']
929 metadata = a["metadata"]
926 nt.assert_equal(data.get('text/plain'), '3')
930 assert data.get("text/plain") == "3"
927
931
928 b = r['b']
932 b = r["b"]
929 nt.assert_equal(b['status'], 'error')
933 assert b["status"] == "error"
930 nt.assert_equal(b['ename'], 'ZeroDivisionError')
934 assert b["ename"] == "ZeroDivisionError"
931
935
932 # back to text only
936 # back to text only
933 ip.display_formatter.active_types = ['text/plain']
937 ip.display_formatter.active_types = ['text/plain']
@@ -1030,8 +1034,8 b' def test_custom_exc_count():'
1030 ip.run_cell("def foo()", store_history=True)
1034 ip.run_cell("def foo()", store_history=True)
1031 # restore default excepthook
1035 # restore default excepthook
1032 ip.set_custom_exc((), None)
1036 ip.set_custom_exc((), None)
1033 nt.assert_equal(hook.call_count, 1)
1037 assert hook.call_count == 1
1034 nt.assert_equal(ip.execution_count, before + 1)
1038 assert ip.execution_count == before + 1
1035
1039
1036
1040
1037 def test_run_cell_async():
1041 def test_run_cell_async():
@@ -17,8 +17,6 b' from pathlib import Path'
17 from textwrap import dedent
17 from textwrap import dedent
18 from unittest import TestCase, mock
18 from unittest import TestCase, mock
19
19
20 import nose.tools as nt
21
22 import pytest
20 import pytest
23
21
24 from IPython import get_ipython
22 from IPython import get_ipython
@@ -47,7 +45,8 b' class DummyMagics(magic.Magics): pass'
47
45
48 def test_extract_code_ranges():
46 def test_extract_code_ranges():
49 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
47 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
50 expected = [(0, 1),
48 expected = [
49 (0, 1),
51 (2, 3),
50 (2, 3),
52 (4, 6),
51 (4, 6),
53 (6, 9),
52 (6, 9),
@@ -56,9 +55,10 b' def test_extract_code_ranges():'
56 (None, 9),
55 (None, 9),
57 (9, None),
56 (9, None),
58 (None, 13),
57 (None, 13),
59 (None, None)]
58 (None, None),
59 ]
60 actual = list(code.extract_code_ranges(instr))
60 actual = list(code.extract_code_ranges(instr))
61 nt.assert_equal(actual, expected)
61 assert actual == expected
62
62
63 def test_extract_symbols():
63 def test_extract_symbols():
64 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
64 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
@@ -70,7 +70,7 b' def test_extract_symbols():'
70 (["class A: pass\n"], ['a']),
70 (["class A: pass\n"], ['a']),
71 ([], ['z'])]
71 ([], ['z'])]
72 for symbols, exp in zip(symbols_args, expected):
72 for symbols, exp in zip(symbols_args, expected):
73 nt.assert_equal(code.extract_symbols(source, symbols), exp)
73 assert code.extract_symbols(source, symbols) == exp
74
74
75
75
76 def test_extract_symbols_raises_exception_with_non_python_code():
76 def test_extract_symbols_raises_exception_with_non_python_code():
@@ -78,13 +78,13 b' def test_extract_symbols_raises_exception_with_non_python_code():'
78 "def hello\n"
78 "def hello\n"
79 "puts 'Hello world'\n"
79 "puts 'Hello world'\n"
80 "end")
80 "end")
81 with nt.assert_raises(SyntaxError):
81 with pytest.raises(SyntaxError):
82 code.extract_symbols(source, "hello")
82 code.extract_symbols(source, "hello")
83
83
84
84
85 def test_magic_not_found():
85 def test_magic_not_found():
86 # magic not found raises UsageError
86 # magic not found raises UsageError
87 with nt.assert_raises(UsageError):
87 with pytest.raises(UsageError):
88 _ip.magic('doesntexist')
88 _ip.magic('doesntexist')
89
89
90 # ensure result isn't success when a magic isn't found
90 # ensure result isn't success when a magic isn't found
@@ -94,7 +94,7 b' def test_magic_not_found():'
94
94
95 def test_cell_magic_not_found():
95 def test_cell_magic_not_found():
96 # magic not found raises UsageError
96 # magic not found raises UsageError
97 with nt.assert_raises(UsageError):
97 with pytest.raises(UsageError):
98 _ip.run_cell_magic('doesntexist', 'line', 'cell')
98 _ip.run_cell_magic('doesntexist', 'line', 'cell')
99
99
100 # ensure result isn't success when a magic isn't found
100 # ensure result isn't success when a magic isn't found
@@ -127,7 +127,7 b' def test_config_available_configs():'
127
127
128 stdout = captured.stdout
128 stdout = captured.stdout
129 config_classes = stdout.strip().split('\n')[1:]
129 config_classes = stdout.strip().split('\n')[1:]
130 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
130 assert config_classes == sorted(set(config_classes))
131
131
132 def test_config_print_class():
132 def test_config_print_class():
133 """ test that config with a classname prints the class's options. """
133 """ test that config with a classname prints the class's options. """
@@ -148,15 +148,14 b' def test_rehashx():'
148 _ip.magic('rehashx')
148 _ip.magic('rehashx')
149 # Practically ALL ipython development systems will have more than 10 aliases
149 # Practically ALL ipython development systems will have more than 10 aliases
150
150
151 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
151 assert len(_ip.alias_manager.aliases) > 10
152 for name, cmd in _ip.alias_manager.aliases:
152 for name, cmd in _ip.alias_manager.aliases:
153 # we must strip dots from alias names
153 # we must strip dots from alias names
154 nt.assert_not_in('.', name)
154 assert "." not in name
155
155
156 # rehashx must fill up syscmdlist
156 # rehashx must fill up syscmdlist
157 scoms = _ip.db['syscmdlist']
157 scoms = _ip.db['syscmdlist']
158 nt.assert_true(len(scoms) > 10)
158 assert len(scoms) > 10
159
160
159
161
160
162 def test_magic_parse_options():
161 def test_magic_parse_options():
@@ -170,16 +169,17 b' def test_magic_parse_options():'
170 expected = 'c:x'
169 expected = 'c:x'
171 else:
170 else:
172 expected = path
171 expected = path
173 nt.assert_equal(opts['f'], expected)
172 assert opts["f"] == expected
173
174
174
175 def test_magic_parse_long_options():
175 def test_magic_parse_long_options():
176 """Magic.parse_options can handle --foo=bar long options"""
176 """Magic.parse_options can handle --foo=bar long options"""
177 ip = get_ipython()
177 ip = get_ipython()
178 m = DummyMagics(ip)
178 m = DummyMagics(ip)
179 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
179 opts, _ = m.parse_options("--foo --bar=bubble", "a", "foo", "bar=")
180 nt.assert_in('foo', opts)
180 assert "foo" in opts
181 nt.assert_in('bar', opts)
181 assert "bar" in opts
182 nt.assert_equal(opts['bar'], "bubble")
182 assert opts["bar"] == "bubble"
183
183
184
184
185 def doctest_hist_f():
185 def doctest_hist_f():
@@ -263,7 +263,7 b' def doctest_hist_op():'
263
263
264 def test_hist_pof():
264 def test_hist_pof():
265 ip = get_ipython()
265 ip = get_ipython()
266 ip.run_cell(u"1+2", store_history=True)
266 ip.run_cell("1+2", store_history=True)
267 #raise Exception(ip.history_manager.session_number)
267 #raise Exception(ip.history_manager.session_number)
268 #raise Exception(list(ip.history_manager._get_range_session()))
268 #raise Exception(list(ip.history_manager._get_range_session()))
269 with TemporaryDirectory() as td:
269 with TemporaryDirectory() as td:
@@ -279,10 +279,10 b' def test_macro():'
279 for i, cmd in enumerate(cmds, start=1):
279 for i, cmd in enumerate(cmds, start=1):
280 ip.history_manager.store_inputs(i, cmd)
280 ip.history_manager.store_inputs(i, cmd)
281 ip.magic("macro test 1-3")
281 ip.magic("macro test 1-3")
282 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
282 assert ip.user_ns["test"].value == "\n".join(cmds) + "\n"
283
283
284 # List macros
284 # List macros
285 nt.assert_in("test", ip.magic("macro"))
285 assert "test" in ip.magic("macro")
286
286
287
287
288 def test_macro_run():
288 def test_macro_run():
@@ -292,7 +292,7 b' def test_macro_run():'
292 cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"]
292 cmds = ["a=10", "a+=1", "print(a)", "%macro test 2-3"]
293 for cmd in cmds:
293 for cmd in cmds:
294 ip.run_cell(cmd, store_history=True)
294 ip.run_cell(cmd, store_history=True)
295 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint(a)\n")
295 assert ip.user_ns["test"].value == "a+=1\nprint(a)\n"
296 with tt.AssertPrints("12"):
296 with tt.AssertPrints("12"):
297 ip.run_cell("test")
297 ip.run_cell("test")
298 with tt.AssertPrints("13"):
298 with tt.AssertPrints("13"):
@@ -306,54 +306,59 b' def test_magic_magic():'
306 ip.magic("magic")
306 ip.magic("magic")
307
307
308 stdout = captured.stdout
308 stdout = captured.stdout
309 nt.assert_in('%magic', stdout)
309 assert "%magic" in stdout
310 nt.assert_in('IPython', stdout)
310 assert "IPython" in stdout
311 nt.assert_in('Available', stdout)
311 assert "Available" in stdout
312
312
313
313
314 @dec.skipif_not_numpy
314 @dec.skipif_not_numpy
315 def test_numpy_reset_array_undec():
315 def test_numpy_reset_array_undec():
316 "Test '%reset array' functionality"
316 "Test '%reset array' functionality"
317 _ip.ex('import numpy as np')
317 _ip.ex("import numpy as np")
318 _ip.ex('a = np.empty(2)')
318 _ip.ex("a = np.empty(2)")
319 nt.assert_in('a', _ip.user_ns)
319 assert "a" in _ip.user_ns
320 _ip.magic('reset -f array')
320 _ip.magic("reset -f array")
321 nt.assert_not_in('a', _ip.user_ns)
321 assert "a" not in _ip.user_ns
322
322
323
323 def test_reset_out():
324 def test_reset_out():
324 "Test '%reset out' magic"
325 "Test '%reset out' magic"
325 _ip.run_cell("parrot = 'dead'", store_history=True)
326 _ip.run_cell("parrot = 'dead'", store_history=True)
326 # test '%reset -f out', make an Out prompt
327 # test '%reset -f out', make an Out prompt
327 _ip.run_cell("parrot", store_history=True)
328 _ip.run_cell("parrot", store_history=True)
328 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
329 assert "dead" in [_ip.user_ns[x] for x in ("_", "__", "___")]
329 _ip.magic('reset -f out')
330 _ip.magic("reset -f out")
330 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
331 assert "dead" not in [_ip.user_ns[x] for x in ("_", "__", "___")]
331 nt.assert_equal(len(_ip.user_ns['Out']), 0)
332 assert len(_ip.user_ns["Out"]) == 0
333
332
334
333 def test_reset_in():
335 def test_reset_in():
334 "Test '%reset in' magic"
336 "Test '%reset in' magic"
335 # test '%reset -f in'
337 # test '%reset -f in'
336 _ip.run_cell("parrot", store_history=True)
338 _ip.run_cell("parrot", store_history=True)
337 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
339 assert "parrot" in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
338 _ip.magic('%reset -f in')
340 _ip.magic("%reset -f in")
339 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
341 assert "parrot" not in [_ip.user_ns[x] for x in ("_i", "_ii", "_iii")]
340 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
342 assert len(set(_ip.user_ns["In"])) == 1
343
341
344
342 def test_reset_dhist():
345 def test_reset_dhist():
343 "Test '%reset dhist' magic"
346 "Test '%reset dhist' magic"
344 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
347 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
345 _ip.magic('cd ' + os.path.dirname(nt.__file__))
348 _ip.magic("cd " + os.path.dirname(pytest.__file__))
346 _ip.magic('cd -')
349 _ip.magic("cd -")
347 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
350 assert len(_ip.user_ns["_dh"]) > 0
348 _ip.magic('reset -f dhist')
351 _ip.magic("reset -f dhist")
349 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
352 assert len(_ip.user_ns["_dh"]) == 0
350 _ip.run_cell("_dh = [d for d in tmp]") #restore
353 _ip.run_cell("_dh = [d for d in tmp]") # restore
351
354
355
352 def test_reset_in_length():
356 def test_reset_in_length():
353 "Test that '%reset in' preserves In[] length"
357 "Test that '%reset in' preserves In[] length"
354 _ip.run_cell("print 'foo'")
358 _ip.run_cell("print 'foo'")
355 _ip.run_cell("reset -f in")
359 _ip.run_cell("reset -f in")
356 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
360 assert len(_ip.user_ns["In"]) == _ip.displayhook.prompt_count + 1
361
357
362
358 class TestResetErrors(TestCase):
363 class TestResetErrors(TestCase):
359
364
@@ -395,7 +400,7 b' def test_tb_syntaxerror():'
395 sys.stdout = save_stdout
400 sys.stdout = save_stdout
396 # trim output, and only check the last line
401 # trim output, and only check the last line
397 last_line = out.rstrip().splitlines()[-1].strip()
402 last_line = out.rstrip().splitlines()[-1].strip()
398 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
403 assert last_line == "SyntaxError: invalid syntax"
399
404
400
405
401 def test_time():
406 def test_time():
@@ -448,18 +453,21 b' def test_multiline_time():'
448 a = "ho"
453 a = "ho"
449 b = "hey"
454 b = "hey"
450 a+b
455 a+b
451 """))
456 """
452 nt.assert_equal(ip.user_ns_hidden['_'], 'hohey')
457 )
458 )
459 assert ip.user_ns_hidden["_"] == "hohey"
460
453
461
454 def test_time_local_ns():
462 def test_time_local_ns():
455 """
463 """
456 Test that local_ns is actually global_ns when running a cell magic
464 Test that local_ns is actually global_ns when running a cell magic
457 """
465 """
458 ip = get_ipython()
466 ip = get_ipython()
459 ip.run_cell("%%time\n"
467 ip.run_cell("%%time\n" "myvar = 1")
460 "myvar = 1")
468 assert ip.user_ns["myvar"] == 1
461 nt.assert_equal(ip.user_ns['myvar'], 1)
469 del ip.user_ns["myvar"]
462 del ip.user_ns['myvar']
470
463
471
464 def test_doctest_mode():
472 def test_doctest_mode():
465 "Toggle doctest_mode twice, it should be a no-op and run without error"
473 "Toggle doctest_mode twice, it should be a no-op and run without error"
@@ -472,8 +480,8 b' def test_parse_options():'
472 # These are only the most minimal of tests, more should be added later. At
480 # These are only the most minimal of tests, more should be added later. At
473 # the very least we check that basic text/unicode calls work OK.
481 # the very least we check that basic text/unicode calls work OK.
474 m = DummyMagics(_ip)
482 m = DummyMagics(_ip)
475 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
483 assert m.parse_options("foo", "")[1] == "foo"
476 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
484 assert m.parse_options("foo", "")[1] == "foo"
477
485
478
486
479 def test_parse_options_preserve_non_option_string():
487 def test_parse_options_preserve_non_option_string():
@@ -482,8 +490,8 b' def test_parse_options_preserve_non_option_string():'
482 opts, stmt = m.parse_options(
490 opts, stmt = m.parse_options(
483 " -n1 -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True
491 " -n1 -r 13 _ = 314 + foo", "n:r:", preserve_non_opts=True
484 )
492 )
485 nt.assert_equal(opts, {"n": "1", "r": "13"})
493 assert opts == {"n": "1", "r": "13"}
486 nt.assert_equal(stmt, "_ = 314 + foo")
494 assert stmt == "_ = 314 + foo"
487
495
488
496
489 def test_run_magic_preserve_code_block():
497 def test_run_magic_preserve_code_block():
@@ -501,13 +509,13 b' def test_dirops():'
501 ipdir = os.path.realpath(_ip.ipython_dir)
509 ipdir = os.path.realpath(_ip.ipython_dir)
502 try:
510 try:
503 _ip.magic('cd "%s"' % ipdir)
511 _ip.magic('cd "%s"' % ipdir)
504 nt.assert_equal(curpath(), ipdir)
512 assert curpath() == ipdir
505 _ip.magic('cd -')
513 _ip.magic('cd -')
506 nt.assert_equal(curpath(), startdir)
514 assert curpath() == startdir
507 _ip.magic('pushd "%s"' % ipdir)
515 _ip.magic('pushd "%s"' % ipdir)
508 nt.assert_equal(curpath(), ipdir)
516 assert curpath() == ipdir
509 _ip.magic('popd')
517 _ip.magic('popd')
510 nt.assert_equal(curpath(), startdir)
518 assert curpath() == startdir
511 finally:
519 finally:
512 os.chdir(startdir)
520 os.chdir(startdir)
513
521
@@ -534,7 +542,7 b' def test_xmode():'
534 xmode = _ip.InteractiveTB.mode
542 xmode = _ip.InteractiveTB.mode
535 for i in range(4):
543 for i in range(4):
536 _ip.magic("xmode")
544 _ip.magic("xmode")
537 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
545 assert _ip.InteractiveTB.mode == xmode
538
546
539 def test_reset_hard():
547 def test_reset_hard():
540 monitor = []
548 monitor = []
@@ -547,9 +555,9 b' def test_reset_hard():'
547 _ip.user_ns["a"] = A()
555 _ip.user_ns["a"] = A()
548 _ip.run_cell("a")
556 _ip.run_cell("a")
549
557
550 nt.assert_equal(monitor, [])
558 assert monitor == []
551 _ip.magic("reset -f")
559 _ip.magic("reset -f")
552 nt.assert_equal(monitor, [1])
560 assert monitor == [1]
553
561
554 class TestXdel(tt.TempFileMixin):
562 class TestXdel(tt.TempFileMixin):
555 def test_xdel(self):
563 def test_xdel(self):
@@ -566,12 +574,12 b' class TestXdel(tt.TempFileMixin):'
566 _ip.run_cell("a")
574 _ip.run_cell("a")
567
575
568 monitor = _ip.user_ns["A"].monitor
576 monitor = _ip.user_ns["A"].monitor
569 nt.assert_equal(monitor, [])
577 assert monitor == []
570
578
571 _ip.magic("xdel a")
579 _ip.magic("xdel a")
572
580
573 # Check that a's __del__ method has been called.
581 # Check that a's __del__ method has been called.
574 nt.assert_equal(monitor, [1])
582 assert monitor == [1]
575
583
576 def doctest_who():
584 def doctest_who():
577 """doctest for %who
585 """doctest for %who
@@ -661,11 +669,12 b' def test_timeit_special_syntax():'
661 ip.user_ns['lmagic_out'] = line
669 ip.user_ns['lmagic_out'] = line
662
670
663 # line mode test
671 # line mode test
664 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
672 _ip.run_line_magic("timeit", "-n1 -r1 %lmagic my line")
665 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
673 assert _ip.user_ns["lmagic_out"] == "my line"
666 # cell mode test
674 # cell mode test
667 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
675 _ip.run_cell_magic("timeit", "-n1 -r1", "%lmagic my line2")
668 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
676 assert _ip.user_ns["lmagic_out"] == "my line2"
677
669
678
670 def test_timeit_return():
679 def test_timeit_return():
671 """
680 """
@@ -688,7 +697,7 b' def test_timeit_return_quiet():'
688 assert (res is not None)
697 assert (res is not None)
689
698
690 def test_timeit_invalid_return():
699 def test_timeit_invalid_return():
691 with nt.assert_raises_regex(SyntaxError, "outside function"):
700 with pytest.raises(SyntaxError):
692 _ip.run_line_magic('timeit', 'return')
701 _ip.run_line_magic('timeit', 'return')
693
702
694 @dec.skipif(execution.profile is None)
703 @dec.skipif(execution.profile is None)
@@ -700,17 +709,19 b' def test_prun_special_syntax():'
700 ip.user_ns['lmagic_out'] = line
709 ip.user_ns['lmagic_out'] = line
701
710
702 # line mode test
711 # line mode test
703 _ip.run_line_magic('prun', '-q %lmagic my line')
712 _ip.run_line_magic("prun", "-q %lmagic my line")
704 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
713 assert _ip.user_ns["lmagic_out"] == "my line"
705 # cell mode test
714 # cell mode test
706 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
715 _ip.run_cell_magic("prun", "-q", "%lmagic my line2")
707 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
716 assert _ip.user_ns["lmagic_out"] == "my line2"
717
708
718
709 @dec.skipif(execution.profile is None)
719 @dec.skipif(execution.profile is None)
710 def test_prun_quotes():
720 def test_prun_quotes():
711 "Test that prun does not clobber string escapes (GH #1302)"
721 "Test that prun does not clobber string escapes (GH #1302)"
712 _ip.magic(r"prun -q x = '\t'")
722 _ip.magic(r"prun -q x = '\t'")
713 nt.assert_equal(_ip.user_ns['x'], '\t')
723 assert _ip.user_ns["x"] == "\t"
724
714
725
715 def test_extension():
726 def test_extension():
716 # Debugging information for failures of this test
727 # Debugging information for failures of this test
@@ -719,14 +730,14 b' def test_extension():'
719 print(' ', p)
730 print(' ', p)
720 print('CWD', os.getcwd())
731 print('CWD', os.getcwd())
721
732
722 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
733 pytest.raises(ImportError, _ip.magic, "load_ext daft_extension")
723 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
734 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
724 sys.path.insert(0, daft_path)
735 sys.path.insert(0, daft_path)
725 try:
736 try:
726 _ip.user_ns.pop('arq', None)
737 _ip.user_ns.pop('arq', None)
727 invalidate_caches() # Clear import caches
738 invalidate_caches() # Clear import caches
728 _ip.magic("load_ext daft_extension")
739 _ip.magic("load_ext daft_extension")
729 nt.assert_equal(_ip.user_ns['arq'], 185)
740 assert _ip.user_ns["arq"] == 185
730 _ip.magic("unload_ext daft_extension")
741 _ip.magic("unload_ext daft_extension")
731 assert 'arq' not in _ip.user_ns
742 assert 'arq' not in _ip.user_ns
732 finally:
743 finally:
@@ -736,7 +747,7 b' def test_extension():'
736 def test_notebook_export_json():
747 def test_notebook_export_json():
737 _ip = get_ipython()
748 _ip = get_ipython()
738 _ip.history_manager.reset() # Clear any existing history.
749 _ip.history_manager.reset() # Clear any existing history.
739 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
750 cmds = ["a=1", "def b():\n return a**2", "print('noël, été', b())"]
740 for i, cmd in enumerate(cmds, start=1):
751 for i, cmd in enumerate(cmds, start=1):
741 _ip.history_manager.store_inputs(i, cmd)
752 _ip.history_manager.store_inputs(i, cmd)
742 with TemporaryDirectory() as td:
753 with TemporaryDirectory() as td:
@@ -797,11 +808,11 b' class CellMagicTestCase(TestCase):'
797
808
798 def check_ident(self, magic):
809 def check_ident(self, magic):
799 # Manually called, we get the result
810 # Manually called, we get the result
800 out = _ip.run_cell_magic(magic, 'a', 'b')
811 out = _ip.run_cell_magic(magic, "a", "b")
801 nt.assert_equal(out, ('a','b'))
812 assert out == ("a", "b")
802 # Via run_cell, it goes into the user's namespace via displayhook
813 # Via run_cell, it goes into the user's namespace via displayhook
803 _ip.run_cell('%%' + magic +' c\nd\n')
814 _ip.run_cell("%%" + magic + " c\nd\n")
804 nt.assert_equal(_ip.user_ns['_'], ('c','d\n'))
815 assert _ip.user_ns["_"] == ("c", "d\n")
805
816
806 def test_cell_magic_func_deco(self):
817 def test_cell_magic_func_deco(self):
807 "Cell magic using simple decorator"
818 "Cell magic using simple decorator"
@@ -844,7 +855,7 b' class CellMagicTestCase(TestCase):'
844 self.check_ident('cellm4')
855 self.check_ident('cellm4')
845 # Check that nothing is registered as 'cellm33'
856 # Check that nothing is registered as 'cellm33'
846 c33 = _ip.find_cell_magic('cellm33')
857 c33 = _ip.find_cell_magic('cellm33')
847 nt.assert_equal(c33, None)
858 assert c33 == None
848
859
849 def test_file():
860 def test_file():
850 """Basic %%writefile"""
861 """Basic %%writefile"""
@@ -856,8 +867,9 b' def test_file():'
856 'line2',
867 'line2',
857 ]))
868 ]))
858 s = Path(fname).read_text()
869 s = Path(fname).read_text()
859 nt.assert_in('line1\n', s)
870 assert "line1\n" in s
860 nt.assert_in('line2', s)
871 assert "line2" in s
872
861
873
862 @dec.skip_win32
874 @dec.skip_win32
863 def test_file_single_quote():
875 def test_file_single_quote():
@@ -870,8 +882,9 b' def test_file_single_quote():'
870 'line2',
882 'line2',
871 ]))
883 ]))
872 s = Path(fname).read_text()
884 s = Path(fname).read_text()
873 nt.assert_in('line1\n', s)
885 assert "line1\n" in s
874 nt.assert_in('line2', s)
886 assert "line2" in s
887
875
888
876 @dec.skip_win32
889 @dec.skip_win32
877 def test_file_double_quote():
890 def test_file_double_quote():
@@ -884,8 +897,9 b' def test_file_double_quote():'
884 'line2',
897 'line2',
885 ]))
898 ]))
886 s = Path(fname).read_text()
899 s = Path(fname).read_text()
887 nt.assert_in('line1\n', s)
900 assert "line1\n" in s
888 nt.assert_in('line2', s)
901 assert "line2" in s
902
889
903
890 def test_file_var_expand():
904 def test_file_var_expand():
891 """%%writefile $filename"""
905 """%%writefile $filename"""
@@ -898,8 +912,9 b' def test_file_var_expand():'
898 'line2',
912 'line2',
899 ]))
913 ]))
900 s = Path(fname).read_text()
914 s = Path(fname).read_text()
901 nt.assert_in('line1\n', s)
915 assert "line1\n" in s
902 nt.assert_in('line2', s)
916 assert "line2" in s
917
903
918
904 def test_file_unicode():
919 def test_file_unicode():
905 """%%writefile with unicode cell"""
920 """%%writefile with unicode cell"""
@@ -912,8 +927,9 b' def test_file_unicode():'
912 ]))
927 ]))
913 with io.open(fname, encoding='utf-8') as f:
928 with io.open(fname, encoding='utf-8') as f:
914 s = f.read()
929 s = f.read()
915 nt.assert_in(u'liné1\n', s)
930 assert "liné1\n" in s
916 nt.assert_in(u'liné2', s)
931 assert "liné2" in s
932
917
933
918 def test_file_amend():
934 def test_file_amend():
919 """%%writefile -a amends files"""
935 """%%writefile -a amends files"""
@@ -929,8 +945,9 b' def test_file_amend():'
929 'line4',
945 'line4',
930 ]))
946 ]))
931 s = Path(fname).read_text()
947 s = Path(fname).read_text()
932 nt.assert_in('line1\n', s)
948 assert "line1\n" in s
933 nt.assert_in('line3\n', s)
949 assert "line3\n" in s
950
934
951
935 def test_file_spaces():
952 def test_file_spaces():
936 """%%file with spaces in filename"""
953 """%%file with spaces in filename"""
@@ -942,14 +959,16 b' def test_file_spaces():'
942 'line2',
959 'line2',
943 ]))
960 ]))
944 s = Path(fname).read_text()
961 s = Path(fname).read_text()
945 nt.assert_in('line1\n', s)
962 assert "line1\n" in s
946 nt.assert_in('line2', s)
963 assert "line2" in s
964
947
965
948 def test_script_config():
966 def test_script_config():
949 ip = get_ipython()
967 ip = get_ipython()
950 ip.config.ScriptMagics.script_magics = ['whoda']
968 ip.config.ScriptMagics.script_magics = ['whoda']
951 sm = script.ScriptMagics(shell=ip)
969 sm = script.ScriptMagics(shell=ip)
952 nt.assert_in('whoda', sm.magics['cell'])
970 assert "whoda" in sm.magics["cell"]
971
953
972
954 @dec.skip_iptest_but_not_pytest
973 @dec.skip_iptest_but_not_pytest
955 @dec.skip_win32
974 @dec.skip_win32
@@ -962,7 +981,8 b' def test_script_out():'
962 ip = get_ipython()
981 ip = get_ipython()
963 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
982 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
964 assert asyncio.get_event_loop().is_running() is False
983 assert asyncio.get_event_loop().is_running() is False
965 nt.assert_equal(ip.user_ns['output'], 'hi\n')
984 assert ip.user_ns["output"] == "hi\n"
985
966
986
967 @dec.skip_iptest_but_not_pytest
987 @dec.skip_iptest_but_not_pytest
968 @dec.skip_win32
988 @dec.skip_win32
@@ -974,7 +994,7 b' def test_script_err():'
974 assert asyncio.get_event_loop().is_running() is False
994 assert asyncio.get_event_loop().is_running() is False
975 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
995 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
976 assert asyncio.get_event_loop().is_running() is False
996 assert asyncio.get_event_loop().is_running() is False
977 nt.assert_equal(ip.user_ns['error'], 'hello\n')
997 assert ip.user_ns["error"] == "hello\n"
978
998
979
999
980 @dec.skip_iptest_but_not_pytest
1000 @dec.skip_iptest_but_not_pytest
@@ -988,8 +1008,8 b' def test_script_out_err():'
988 ip.run_cell_magic(
1008 ip.run_cell_magic(
989 "script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2"
1009 "script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2"
990 )
1010 )
991 nt.assert_equal(ip.user_ns["output"], "hi\n")
1011 assert ip.user_ns["output"] == "hi\n"
992 nt.assert_equal(ip.user_ns["error"], "hello\n")
1012 assert ip.user_ns["error"] == "hello\n"
993
1013
994
1014
995 @dec.skip_iptest_but_not_pytest
1015 @dec.skip_iptest_but_not_pytest
@@ -1000,10 +1020,11 b' def test_script_out_err():'
1000 async def test_script_bg_out():
1020 async def test_script_bg_out():
1001 ip = get_ipython()
1021 ip = get_ipython()
1002 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
1022 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
1003 nt.assert_equal((await ip.user_ns["output"].read()), b"hi\n")
1023 assert (await ip.user_ns["output"].read()) == b"hi\n"
1004 ip.user_ns["output"].close()
1024 ip.user_ns["output"].close()
1005 asyncio.get_event_loop().stop()
1025 asyncio.get_event_loop().stop()
1006
1026
1027
1007 @dec.skip_iptest_but_not_pytest
1028 @dec.skip_iptest_but_not_pytest
1008 @dec.skip_win32
1029 @dec.skip_win32
1009 @pytest.mark.skipif(
1030 @pytest.mark.skipif(
@@ -1012,7 +1033,7 b' async def test_script_bg_out():'
1012 async def test_script_bg_err():
1033 async def test_script_bg_err():
1013 ip = get_ipython()
1034 ip = get_ipython()
1014 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
1035 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
1015 nt.assert_equal((await ip.user_ns["error"].read()), b"hello\n")
1036 assert (await ip.user_ns["error"].read()) == b"hello\n"
1016 ip.user_ns["error"].close()
1037 ip.user_ns["error"].close()
1017
1038
1018
1039
@@ -1026,8 +1047,8 b' async def test_script_bg_out_err():'
1026 ip.run_cell_magic(
1047 ip.run_cell_magic(
1027 "script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2"
1048 "script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2"
1028 )
1049 )
1029 nt.assert_equal((await ip.user_ns["output"].read()), b"hi\n")
1050 assert (await ip.user_ns["output"].read()) == b"hi\n"
1030 nt.assert_equal((await ip.user_ns["error"].read()), b"hello\n")
1051 assert (await ip.user_ns["error"].read()) == b"hello\n"
1031 ip.user_ns["output"].close()
1052 ip.user_ns["output"].close()
1032 ip.user_ns["error"].close()
1053 ip.user_ns["error"].close()
1033
1054
@@ -1040,7 +1061,7 b' def test_script_defaults():'
1040 except Exception:
1061 except Exception:
1041 pass
1062 pass
1042 else:
1063 else:
1043 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
1064 assert cmd in ip.magics_manager.magics["cell"]
1044
1065
1045
1066
1046 @magics_class
1067 @magics_class
@@ -1060,19 +1081,20 b' def test_line_cell_info():'
1060 """%%foo and %foo magics are distinguishable to inspect"""
1081 """%%foo and %foo magics are distinguishable to inspect"""
1061 ip = get_ipython()
1082 ip = get_ipython()
1062 ip.magics_manager.register(FooFoo)
1083 ip.magics_manager.register(FooFoo)
1063 oinfo = ip.object_inspect('foo')
1084 oinfo = ip.object_inspect("foo")
1064 nt.assert_true(oinfo['found'])
1085 assert oinfo["found"] is True
1065 nt.assert_true(oinfo['ismagic'])
1086 assert oinfo["ismagic"] is True
1087
1088 oinfo = ip.object_inspect("%%foo")
1089 assert oinfo["found"] is True
1090 assert oinfo["ismagic"] is True
1091 assert oinfo["docstring"] == FooFoo.cell_foo.__doc__
1066
1092
1067 oinfo = ip.object_inspect('%%foo')
1093 oinfo = ip.object_inspect("%foo")
1068 nt.assert_true(oinfo['found'])
1094 assert oinfo["found"] is True
1069 nt.assert_true(oinfo['ismagic'])
1095 assert oinfo["ismagic"] is True
1070 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
1096 assert oinfo["docstring"] == FooFoo.line_foo.__doc__
1071
1097
1072 oinfo = ip.object_inspect('%foo')
1073 nt.assert_true(oinfo['found'])
1074 nt.assert_true(oinfo['ismagic'])
1075 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
1076
1098
1077 def test_multiple_magics():
1099 def test_multiple_magics():
1078 ip = get_ipython()
1100 ip = get_ipython()
@@ -1080,9 +1102,10 b' def test_multiple_magics():'
1080 foo2 = FooFoo(ip)
1102 foo2 = FooFoo(ip)
1081 mm = ip.magics_manager
1103 mm = ip.magics_manager
1082 mm.register(foo1)
1104 mm.register(foo1)
1083 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
1105 assert mm.magics["line"]["foo"].__self__ is foo1
1084 mm.register(foo2)
1106 mm.register(foo2)
1085 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
1107 assert mm.magics["line"]["foo"].__self__ is foo2
1108
1086
1109
1087 def test_alias_magic():
1110 def test_alias_magic():
1088 """Test %alias_magic."""
1111 """Test %alias_magic."""
@@ -1090,48 +1113,49 b' def test_alias_magic():'
1090 mm = ip.magics_manager
1113 mm = ip.magics_manager
1091
1114
1092 # Basic operation: both cell and line magics are created, if possible.
1115 # Basic operation: both cell and line magics are created, if possible.
1093 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
1116 ip.run_line_magic("alias_magic", "timeit_alias timeit")
1094 nt.assert_in('timeit_alias', mm.magics['line'])
1117 assert "timeit_alias" in mm.magics["line"]
1095 nt.assert_in('timeit_alias', mm.magics['cell'])
1118 assert "timeit_alias" in mm.magics["cell"]
1096
1119
1097 # --cell is specified, line magic not created.
1120 # --cell is specified, line magic not created.
1098 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
1121 ip.run_line_magic("alias_magic", "--cell timeit_cell_alias timeit")
1099 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
1122 assert "timeit_cell_alias" not in mm.magics["line"]
1100 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
1123 assert "timeit_cell_alias" in mm.magics["cell"]
1101
1124
1102 # Test that line alias is created successfully.
1125 # Test that line alias is created successfully.
1103 ip.run_line_magic('alias_magic', '--line env_alias env')
1126 ip.run_line_magic("alias_magic", "--line env_alias env")
1104 nt.assert_equal(ip.run_line_magic('env', ''),
1127 assert ip.run_line_magic("env", "") == ip.run_line_magic("env_alias", "")
1105 ip.run_line_magic('env_alias', ''))
1106
1128
1107 # Test that line alias with parameters passed in is created successfully.
1129 # Test that line alias with parameters passed in is created successfully.
1108 ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
1130 ip.run_line_magic(
1109 nt.assert_in('history_alias', mm.magics['line'])
1131 "alias_magic", "--line history_alias history --params " + shlex.quote("3")
1132 )
1133 assert "history_alias" in mm.magics["line"]
1110
1134
1111
1135
1112 def test_save():
1136 def test_save():
1113 """Test %save."""
1137 """Test %save."""
1114 ip = get_ipython()
1138 ip = get_ipython()
1115 ip.history_manager.reset() # Clear any existing history.
1139 ip.history_manager.reset() # Clear any existing history.
1116 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
1140 cmds = ["a=1", "def b():\n return a**2", "print(a, b())"]
1117 for i, cmd in enumerate(cmds, start=1):
1141 for i, cmd in enumerate(cmds, start=1):
1118 ip.history_manager.store_inputs(i, cmd)
1142 ip.history_manager.store_inputs(i, cmd)
1119 with TemporaryDirectory() as tmpdir:
1143 with TemporaryDirectory() as tmpdir:
1120 file = os.path.join(tmpdir, "testsave.py")
1144 file = os.path.join(tmpdir, "testsave.py")
1121 ip.run_line_magic("save", "%s 1-10" % file)
1145 ip.run_line_magic("save", "%s 1-10" % file)
1122 content = Path(file).read_text()
1146 content = Path(file).read_text()
1123 nt.assert_equal(content.count(cmds[0]), 1)
1147 assert content.count(cmds[0]) == 1
1124 nt.assert_in("coding: utf-8", content)
1148 assert "coding: utf-8" in content
1125 ip.run_line_magic("save", "-a %s 1-10" % file)
1149 ip.run_line_magic("save", "-a %s 1-10" % file)
1126 content = Path(file).read_text()
1150 content = Path(file).read_text()
1127 nt.assert_equal(content.count(cmds[0]), 2)
1151 assert content.count(cmds[0]) == 2
1128 nt.assert_in("coding: utf-8", content)
1152 assert "coding: utf-8" in content
1129
1153
1130
1154
1131 def test_save_with_no_args():
1155 def test_save_with_no_args():
1132 ip = get_ipython()
1156 ip = get_ipython()
1133 ip.history_manager.reset() # Clear any existing history.
1157 ip.history_manager.reset() # Clear any existing history.
1134 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())", "%save"]
1158 cmds = ["a=1", "def b():\n return a**2", "print(a, b())", "%save"]
1135 for i, cmd in enumerate(cmds, start=1):
1159 for i, cmd in enumerate(cmds, start=1):
1136 ip.history_manager.store_inputs(i, cmd)
1160 ip.history_manager.store_inputs(i, cmd)
1137
1161
@@ -1148,7 +1172,7 b' def test_save_with_no_args():'
1148 print(a, b())
1172 print(a, b())
1149 """
1173 """
1150 )
1174 )
1151 nt.assert_equal(content, expected_content)
1175 assert content == expected_content
1152
1176
1153
1177
1154 def test_store():
1178 def test_store():
@@ -1157,17 +1181,17 b' def test_store():'
1157 ip.run_line_magic('load_ext', 'storemagic')
1181 ip.run_line_magic('load_ext', 'storemagic')
1158
1182
1159 # make sure the storage is empty
1183 # make sure the storage is empty
1160 ip.run_line_magic('store', '-z')
1184 ip.run_line_magic("store", "-z")
1161 ip.user_ns['var'] = 42
1185 ip.user_ns["var"] = 42
1162 ip.run_line_magic('store', 'var')
1186 ip.run_line_magic("store", "var")
1163 ip.user_ns['var'] = 39
1187 ip.user_ns["var"] = 39
1164 ip.run_line_magic('store', '-r')
1188 ip.run_line_magic("store", "-r")
1165 nt.assert_equal(ip.user_ns['var'], 42)
1189 assert ip.user_ns["var"] == 42
1166
1190
1167 ip.run_line_magic('store', '-d var')
1191 ip.run_line_magic("store", "-d var")
1168 ip.user_ns['var'] = 39
1192 ip.user_ns["var"] = 39
1169 ip.run_line_magic('store' , '-r')
1193 ip.run_line_magic("store", "-r")
1170 nt.assert_equal(ip.user_ns['var'], 39)
1194 assert ip.user_ns["var"] == 39
1171
1195
1172
1196
1173 def _run_edit_test(arg_s, exp_filename=None,
1197 def _run_edit_test(arg_s, exp_filename=None,
@@ -1181,27 +1205,27 b' def _run_edit_test(arg_s, exp_filename=None,'
1181 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
1205 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
1182
1206
1183 if exp_filename is not None:
1207 if exp_filename is not None:
1184 nt.assert_equal(exp_filename, filename)
1208 assert exp_filename == filename
1185 if exp_contents is not None:
1209 if exp_contents is not None:
1186 with io.open(filename, 'r', encoding='utf-8') as f:
1210 with io.open(filename, 'r', encoding='utf-8') as f:
1187 contents = f.read()
1211 contents = f.read()
1188 nt.assert_equal(exp_contents, contents)
1212 assert exp_contents == contents
1189 if exp_lineno != -1:
1213 if exp_lineno != -1:
1190 nt.assert_equal(exp_lineno, lineno)
1214 assert exp_lineno == lineno
1191 if exp_is_temp is not None:
1215 if exp_is_temp is not None:
1192 nt.assert_equal(exp_is_temp, is_temp)
1216 assert exp_is_temp == is_temp
1193
1217
1194
1218
1195 def test_edit_interactive():
1219 def test_edit_interactive():
1196 """%edit on interactively defined objects"""
1220 """%edit on interactively defined objects"""
1197 ip = get_ipython()
1221 ip = get_ipython()
1198 n = ip.execution_count
1222 n = ip.execution_count
1199 ip.run_cell(u"def foo(): return 1", store_history=True)
1223 ip.run_cell("def foo(): return 1", store_history=True)
1200
1224
1201 try:
1225 try:
1202 _run_edit_test("foo")
1226 _run_edit_test("foo")
1203 except code.InteractivelyDefined as e:
1227 except code.InteractivelyDefined as e:
1204 nt.assert_equal(e.index, n)
1228 assert e.index == n
1205 else:
1229 else:
1206 raise AssertionError("Should have raised InteractivelyDefined")
1230 raise AssertionError("Should have raised InteractivelyDefined")
1207
1231
@@ -1210,7 +1234,7 b' def test_edit_cell():'
1210 """%edit [cell id]"""
1234 """%edit [cell id]"""
1211 ip = get_ipython()
1235 ip = get_ipython()
1212
1236
1213 ip.run_cell(u"def foo(): return 1", store_history=True)
1237 ip.run_cell("def foo(): return 1", store_history=True)
1214
1238
1215 # test
1239 # test
1216 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
1240 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
@@ -1234,17 +1258,18 b' def test_ls_magic():'
1234 lsmagic = ip.magic('lsmagic')
1258 lsmagic = ip.magic('lsmagic')
1235 with warnings.catch_warnings(record=True) as w:
1259 with warnings.catch_warnings(record=True) as w:
1236 j = json_formatter(lsmagic)
1260 j = json_formatter(lsmagic)
1237 nt.assert_equal(sorted(j), ['cell', 'line'])
1261 assert sorted(j) == ["cell", "line"]
1238 nt.assert_equal(w, []) # no warnings
1262 assert w == [] # no warnings
1263
1239
1264
1240 def test_strip_initial_indent():
1265 def test_strip_initial_indent():
1241 def sii(s):
1266 def sii(s):
1242 lines = s.splitlines()
1267 lines = s.splitlines()
1243 return '\n'.join(code.strip_initial_indent(lines))
1268 return '\n'.join(code.strip_initial_indent(lines))
1244
1269
1245 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
1270 assert sii(" a = 1\nb = 2") == "a = 1\nb = 2"
1246 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
1271 assert sii(" a\n b\nc") == "a\n b\nc"
1247 nt.assert_equal(sii("a\n b"), "a\n b")
1272 assert sii("a\n b") == "a\n b"
1248
1273
1249 def test_logging_magic_quiet_from_arg():
1274 def test_logging_magic_quiet_from_arg():
1250 _ip.config.LoggingMagics.quiet = False
1275 _ip.config.LoggingMagics.quiet = False
@@ -1336,6 +1361,6 b' def test_run_module_from_import_hook():'
1336 _ip.run_cell("import my_tmp")
1361 _ip.run_cell("import my_tmp")
1337
1362
1338 output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
1363 output = "Loaded my_tmp\nI just ran a script\nLoaded my_tmp\n"
1339 nt.assert_equal(output, captured.stdout)
1364 assert output == captured.stdout
1340
1365
1341 sys.meta_path.pop(0)
1366 sys.meta_path.pop(0)
@@ -11,8 +11,6 b' import sys'
11 from io import StringIO
11 from io import StringIO
12 from unittest import TestCase
12 from unittest import TestCase
13
13
14 import nose.tools as nt
15
16 from IPython.testing import tools as tt
14 from IPython.testing import tools as tt
17
15
18 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
@@ -93,16 +91,16 b' class PasteTestCase(TestCase):'
93 ip.hooks.clipboard_get = self.original_clip
91 ip.hooks.clipboard_get = self.original_clip
94
92
95 def test_paste(self):
93 def test_paste(self):
96 ip.user_ns.pop('x', None)
94 ip.user_ns.pop("x", None)
97 self.paste('x = 1')
95 self.paste("x = 1")
98 nt.assert_equal(ip.user_ns['x'], 1)
96 self.assertEqual(ip.user_ns["x"], 1)
99 ip.user_ns.pop('x')
97 ip.user_ns.pop("x")
100
98
101 def test_paste_pyprompt(self):
99 def test_paste_pyprompt(self):
102 ip.user_ns.pop('x', None)
100 ip.user_ns.pop("x", None)
103 self.paste('>>> x=2')
101 self.paste(">>> x=2")
104 nt.assert_equal(ip.user_ns['x'], 2)
102 self.assertEqual(ip.user_ns["x"], 2)
105 ip.user_ns.pop('x')
103 ip.user_ns.pop("x")
106
104
107 def test_paste_py_multi(self):
105 def test_paste_py_multi(self):
108 self.paste("""
106 self.paste("""
@@ -111,35 +109,38 b' class PasteTestCase(TestCase):'
111 >>> for i in x:
109 >>> for i in x:
112 ... y.append(i**2)
110 ... y.append(i**2)
113 ...
111 ...
114 """)
112 """
115 nt.assert_equal(ip.user_ns['x'], [1,2,3])
113 )
116 nt.assert_equal(ip.user_ns['y'], [1,4,9])
114 self.assertEqual(ip.user_ns["x"], [1, 2, 3])
115 self.assertEqual(ip.user_ns["y"], [1, 4, 9])
117
116
118 def test_paste_py_multi_r(self):
117 def test_paste_py_multi_r(self):
119 "Now, test that self.paste -r works"
118 "Now, test that self.paste -r works"
120 self.test_paste_py_multi()
119 self.test_paste_py_multi()
121 nt.assert_equal(ip.user_ns.pop('x'), [1,2,3])
120 self.assertEqual(ip.user_ns.pop("x"), [1, 2, 3])
122 nt.assert_equal(ip.user_ns.pop('y'), [1,4,9])
121 self.assertEqual(ip.user_ns.pop("y"), [1, 4, 9])
123 nt.assert_false('x' in ip.user_ns)
122 self.assertFalse("x" in ip.user_ns)
124 ip.magic('paste -r')
123 ip.magic("paste -r")
125 nt.assert_equal(ip.user_ns['x'], [1,2,3])
124 self.assertEqual(ip.user_ns["x"], [1, 2, 3])
126 nt.assert_equal(ip.user_ns['y'], [1,4,9])
125 self.assertEqual(ip.user_ns["y"], [1, 4, 9])
127
126
128 def test_paste_email(self):
127 def test_paste_email(self):
129 "Test pasting of email-quoted contents"
128 "Test pasting of email-quoted contents"
130 self.paste("""\
129 self.paste("""\
131 >> def foo(x):
130 >> def foo(x):
132 >> return x + 1
131 >> return x + 1
133 >> xx = foo(1.1)""")
132 >> xx = foo(1.1)"""
134 nt.assert_equal(ip.user_ns['xx'], 2.1)
133 )
134 self.assertEqual(ip.user_ns["xx"], 2.1)
135
135
136 def test_paste_email2(self):
136 def test_paste_email2(self):
137 "Email again; some programs add a space also at each quoting level"
137 "Email again; some programs add a space also at each quoting level"
138 self.paste("""\
138 self.paste("""\
139 > > def foo(x):
139 > > def foo(x):
140 > > return x + 1
140 > > return x + 1
141 > > yy = foo(2.1) """)
141 > > yy = foo(2.1) """
142 nt.assert_equal(ip.user_ns['yy'], 3.1)
142 )
143 self.assertEqual(ip.user_ns["yy"], 3.1)
143
144
144 def test_paste_email_py(self):
145 def test_paste_email_py(self):
145 "Email quoting of interactive input"
146 "Email quoting of interactive input"
@@ -147,8 +148,9 b' class PasteTestCase(TestCase):'
147 >> >>> def f(x):
148 >> >>> def f(x):
148 >> ... return x+1
149 >> ... return x+1
149 >> ...
150 >> ...
150 >> >>> zz = f(2.5) """)
151 >> >>> zz = f(2.5) """
151 nt.assert_equal(ip.user_ns['zz'], 3.5)
152 )
153 self.assertEqual(ip.user_ns["zz"], 3.5)
152
154
153 def test_paste_echo(self):
155 def test_paste_echo(self):
154 "Also test self.paste echoing, by temporarily faking the writer"
156 "Also test self.paste echoing, by temporarily faking the writer"
@@ -163,8 +165,8 b' class PasteTestCase(TestCase):'
163 out = w.getvalue()
165 out = w.getvalue()
164 finally:
166 finally:
165 ip.write = writer
167 ip.write = writer
166 nt.assert_equal(ip.user_ns['a'], 100)
168 self.assertEqual(ip.user_ns["a"], 100)
167 nt.assert_equal(ip.user_ns['b'], 200)
169 self.assertEqual(ip.user_ns["b"], 200)
168 assert out == code+"\n## -- End pasted text --\n"
170 assert out == code + "\n## -- End pasted text --\n"
169
171
170 def test_paste_leading_commas(self):
172 def test_paste_leading_commas(self):
@@ -174,10 +176,9 b' class PasteTestCase(TestCase):'
174 a = """
176 a = """
175 ,1,2,3
177 ,1,2,3
176 """'''
178 """'''
177 ip.user_ns.pop('foo', None)
179 ip.user_ns.pop("foo", None)
178 tm.store_or_execute(s, 'foo')
180 tm.store_or_execute(s, "foo")
179 nt.assert_in('foo', ip.user_ns)
181 self.assertIn("foo", ip.user_ns)
180
181
182
182 def test_paste_trailing_question(self):
183 def test_paste_trailing_question(self):
183 "Test pasting sources with trailing question marks"
184 "Test pasting sources with trailing question marks"
@@ -189,4 +190,4 b' def funcfoo():'
189 '''
190 '''
190 ip.user_ns.pop('funcfoo', None)
191 ip.user_ns.pop('funcfoo', None)
191 self.paste(s)
192 self.paste(s)
192 nt.assert_equal(ip.user_ns['funcfoo'](), 'fooresult')
193 self.assertEqual(ip.user_ns["funcfoo"](), "fooresult")
@@ -9,8 +9,6 b' from inspect import signature, Signature, Parameter'
9 import os
9 import os
10 import re
10 import re
11
11
12 import nose.tools as nt
13
14 from .. import oinspect
12 from .. import oinspect
15
13
16 from decorator import decorator
14 from decorator import decorator
@@ -38,7 +36,7 b' def setup_module():'
38 # defined, if any code is inserted above, the following line will need to be
36 # defined, if any code is inserted above, the following line will need to be
39 # updated. Do NOT insert any whitespace between the next line and the function
37 # updated. Do NOT insert any whitespace between the next line and the function
40 # definition below.
38 # definition below.
41 THIS_LINE_NUMBER = 41 # Put here the actual number of this line
39 THIS_LINE_NUMBER = 39 # Put here the actual number of this line
42
40
43 from unittest import TestCase
41 from unittest import TestCase
44
42
@@ -97,7 +95,7 b' def test_find_file_decorated2():'
97
95
98 def test_find_file_magic():
96 def test_find_file_magic():
99 run = ip.find_line_magic('run')
97 run = ip.find_line_magic('run')
100 nt.assert_not_equal(oinspect.find_file(run), None)
98 assert oinspect.find_file(run) is not None
101
99
102
100
103 # A few generic objects we can then inspect in the tests below
101 # A few generic objects we can then inspect in the tests below
@@ -169,11 +167,11 b' def test_info():'
169 "Check that Inspector.info fills out various fields as expected."
167 "Check that Inspector.info fills out various fields as expected."
170 i = inspector.info(Call, oname="Call")
168 i = inspector.info(Call, oname="Call")
171 assert i["type_name"] == "type"
169 assert i["type_name"] == "type"
172 expted_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
170 expected_class = str(type(type)) # <class 'type'> (Python 3) or <type 'type'>
173 assert i["base_class"] == expted_class
171 assert i["base_class"] == expected_class
174 nt.assert_regex(
172 assert re.search(
175 i["string_form"],
176 "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>",
173 "<class 'IPython.core.tests.test_oinspect.Call'( at 0x[0-9a-f]{1,9})?>",
174 i["string_form"],
177 )
175 )
178 fname = __file__
176 fname = __file__
179 if fname.endswith(".pyc"):
177 if fname.endswith(".pyc"):
@@ -184,12 +182,12 b' def test_info():'
184 assert i["definition"] == None
182 assert i["definition"] == None
185 assert i["docstring"] == Call.__doc__
183 assert i["docstring"] == Call.__doc__
186 assert i["source"] == None
184 assert i["source"] == None
187 nt.assert_true(i["isclass"])
185 assert i["isclass"] is True
188 assert i["init_definition"] == "Call(x, y=1)"
186 assert i["init_definition"] == "Call(x, y=1)"
189 assert i["init_docstring"] == Call.__init__.__doc__
187 assert i["init_docstring"] == Call.__init__.__doc__
190
188
191 i = inspector.info(Call, detail_level=1)
189 i = inspector.info(Call, detail_level=1)
192 nt.assert_not_equal(i["source"], None)
190 assert i["source"] is not None
193 assert i["docstring"] == None
191 assert i["docstring"] == None
194
192
195 c = Call(1)
193 c = Call(1)
@@ -221,7 +219,7 b' def test_info_serialliar():'
221
219
222 # Nested attribute access should be cut off at 100 levels deep to avoid
220 # Nested attribute access should be cut off at 100 levels deep to avoid
223 # infinite loops: https://github.com/ipython/ipython/issues/9122
221 # infinite loops: https://github.com/ipython/ipython/issues/9122
224 nt.assert_less(fib_tracker[0], 9000)
222 assert fib_tracker[0] < 9000
225
223
226 def support_function_one(x, y=2, *a, **kw):
224 def support_function_one(x, y=2, *a, **kw):
227 """A simple function."""
225 """A simple function."""
@@ -230,7 +228,8 b' def test_calldef_none():'
230 # We should ignore __call__ for all of these.
228 # We should ignore __call__ for all of these.
231 for obj in [support_function_one, SimpleClass().method, any, str.upper]:
229 for obj in [support_function_one, SimpleClass().method, any, str.upper]:
232 i = inspector.info(obj)
230 i = inspector.info(obj)
233 nt.assert_is(i['call_def'], None)
231 assert i["call_def"] is None
232
234
233
235 def f_kwarg(pos, *, kwonly):
234 def f_kwarg(pos, *, kwonly):
236 pass
235 pass
@@ -266,7 +265,7 b' def test_getdoc():'
266
265
267 def test_empty_property_has_no_source():
266 def test_empty_property_has_no_source():
268 i = inspector.info(property(), detail_level=1)
267 i = inspector.info(property(), detail_level=1)
269 nt.assert_is(i['source'], None)
268 assert i["source"] is None
270
269
271
270
272 def test_property_sources():
271 def test_property_sources():
@@ -288,14 +287,14 b' def test_property_sources():'
288 adder = property(simple_add)
287 adder = property(simple_add)
289
288
290 i = inspector.info(A.foo, detail_level=1)
289 i = inspector.info(A.foo, detail_level=1)
291 nt.assert_in('def foo(self):', i['source'])
290 assert "def foo(self):" in i["source"]
292 nt.assert_in('lambda self, v:', i['source'])
291 assert "lambda self, v:" in i["source"]
293
292
294 i = inspector.info(A.dname, detail_level=1)
293 i = inspector.info(A.dname, detail_level=1)
295 nt.assert_in('def dirname(p)', i['source'])
294 assert "def dirname(p)" in i["source"]
296
295
297 i = inspector.info(A.adder, detail_level=1)
296 i = inspector.info(A.adder, detail_level=1)
298 nt.assert_in('def simple_add(a, b)', i['source'])
297 assert "def simple_add(a, b)" in i["source"]
299
298
300
299
301 def test_property_docstring_is_in_info_for_detail_level_0():
300 def test_property_docstring_is_in_info_for_detail_level_0():
@@ -396,14 +395,14 b' def test_pinfo_magic():'
396 def test_init_colors():
395 def test_init_colors():
397 # ensure colors are not present in signature info
396 # ensure colors are not present in signature info
398 info = inspector.info(HasSignature)
397 info = inspector.info(HasSignature)
399 init_def = info['init_definition']
398 init_def = info["init_definition"]
400 nt.assert_not_in('[0m', init_def)
399 assert "[0m" not in init_def
401
400
402
401
403 def test_builtin_init():
402 def test_builtin_init():
404 info = inspector.info(list)
403 info = inspector.info(list)
405 init_def = info['init_definition']
404 init_def = info['init_definition']
406 nt.assert_is_not_none(init_def)
405 assert init_def is not None
407
406
408
407
409 def test_render_signature_short():
408 def test_render_signature_short():
@@ -428,7 +427,7 b' def test_render_signature_long():'
428 signature(long_function),
427 signature(long_function),
429 long_function.__name__,
428 long_function.__name__,
430 )
429 )
431 nt.assert_in(sig, [
430 assert sig in [
432 # Python >=3.9
431 # Python >=3.9
433 '''\
432 '''\
434 long_function(
433 long_function(
@@ -452,4 +451,4 b' long_function('
452 let_us_make_sure_this_is_looong:Union[str, NoneType]=None,
451 let_us_make_sure_this_is_looong:Union[str, NoneType]=None,
453 ) -> bool\
452 ) -> bool\
454 ''',
453 ''',
455 ])
454 ]
@@ -6,7 +6,6 b' import tempfile'
6 import warnings
6 import warnings
7 from unittest.mock import patch
7 from unittest.mock import patch
8
8
9 import nose.tools as nt
10 from testpath import modified_env, assert_isdir, assert_isfile
9 from testpath import modified_env, assert_isdir, assert_isfile
11
10
12 from IPython import paths
11 from IPython import paths
@@ -52,7 +51,7 b' def test_get_ipython_dir_1():'
52 modified_env({'IPYTHONDIR': env_ipdir}):
51 modified_env({'IPYTHONDIR': env_ipdir}):
53 ipdir = paths.get_ipython_dir()
52 ipdir = paths.get_ipython_dir()
54
53
55 nt.assert_equal(ipdir, env_ipdir)
54 assert ipdir == env_ipdir
56
55
57 def test_get_ipython_dir_2():
56 def test_get_ipython_dir_2():
58 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
57 """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions."""
@@ -66,7 +65,7 b' def test_get_ipython_dir_2():'
66 }):
65 }):
67 ipdir = paths.get_ipython_dir()
66 ipdir = paths.get_ipython_dir()
68
67
69 nt.assert_equal(ipdir, os.path.join("someplace", ".ipython"))
68 assert ipdir == os.path.join("someplace", ".ipython")
70
69
71 def test_get_ipython_dir_3():
70 def test_get_ipython_dir_3():
72 """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
71 """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist."""
@@ -81,10 +80,10 b' def test_get_ipython_dir_3():'
81 }), warnings.catch_warnings(record=True) as w:
80 }), warnings.catch_warnings(record=True) as w:
82 ipdir = paths.get_ipython_dir()
81 ipdir = paths.get_ipython_dir()
83
82
84 nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython"))
83 assert ipdir == os.path.join(tmphome.name, ".ipython")
85 if sys.platform != 'darwin':
84 if sys.platform != 'darwin':
86 nt.assert_equal(len(w), 1)
85 assert len(w) == 1
87 nt.assert_in('Moving', str(w[0]))
86 assert "Moving" in str(w[0])
88 finally:
87 finally:
89 tmphome.cleanup()
88 tmphome.cleanup()
90
89
@@ -106,10 +105,11 b' def test_get_ipython_dir_4():'
106 }), warnings.catch_warnings(record=True) as w:
105 }), warnings.catch_warnings(record=True) as w:
107 ipdir = paths.get_ipython_dir()
106 ipdir = paths.get_ipython_dir()
108
107
109 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython"))
108 assert ipdir == os.path.join(HOME_TEST_DIR, ".ipython")
110 if sys.platform != 'darwin':
109 if sys.platform != 'darwin':
111 nt.assert_equal(len(w), 1)
110 assert len(w) == 1
112 nt.assert_in('Ignoring', str(w[0]))
111 assert "Ignoring" in str(w[0])
112
113
113
114 def test_get_ipython_dir_5():
114 def test_get_ipython_dir_5():
115 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
115 """test_get_ipython_dir_5, use .ipython if exists and XDG defined, but doesn't exist."""
@@ -128,7 +128,7 b' def test_get_ipython_dir_5():'
128 }):
128 }):
129 ipdir = paths.get_ipython_dir()
129 ipdir = paths.get_ipython_dir()
130
130
131 nt.assert_equal(ipdir, IP_TEST_DIR)
131 assert ipdir == IP_TEST_DIR
132
132
133 def test_get_ipython_dir_6():
133 def test_get_ipython_dir_6():
134 """test_get_ipython_dir_6, use home over XDG if defined and neither exist."""
134 """test_get_ipython_dir_6, use home over XDG if defined and neither exist."""
@@ -146,8 +146,8 b' def test_get_ipython_dir_6():'
146 }), warnings.catch_warnings(record=True) as w:
146 }), warnings.catch_warnings(record=True) as w:
147 ipdir = paths.get_ipython_dir()
147 ipdir = paths.get_ipython_dir()
148
148
149 nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, '.ipython'))
149 assert ipdir == os.path.join(HOME_TEST_DIR, ".ipython")
150 nt.assert_equal(len(w), 0)
150 assert len(w) == 0
151
151
152 def test_get_ipython_dir_7():
152 def test_get_ipython_dir_7():
153 """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
153 """test_get_ipython_dir_7, test home directory expansion on IPYTHONDIR"""
@@ -155,7 +155,8 b' def test_get_ipython_dir_7():'
155 with modified_env({'IPYTHONDIR': os.path.join('~', 'somewhere')}), \
155 with modified_env({'IPYTHONDIR': os.path.join('~', 'somewhere')}), \
156 patch.object(paths, '_writable_dir', return_value=True):
156 patch.object(paths, '_writable_dir', return_value=True):
157 ipdir = paths.get_ipython_dir()
157 ipdir = paths.get_ipython_dir()
158 nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere'))
158 assert ipdir == os.path.join(home_dir, "somewhere")
159
159
160
160 @skip_win32
161 @skip_win32
161 def test_get_ipython_dir_8():
162 def test_get_ipython_dir_8():
@@ -164,14 +165,16 b' def test_get_ipython_dir_8():'
164 # test only when HOME directory actually writable
165 # test only when HOME directory actually writable
165 return
166 return
166
167
167 with patch.object(paths, '_writable_dir', lambda path: bool(path)), \
168 with patch.object(paths, "_writable_dir", lambda path: bool(path)), patch.object(
168 patch.object(paths, 'get_xdg_dir', return_value=None), \
169 paths, "get_xdg_dir", return_value=None
169 modified_env({
170 ), modified_env(
170 'IPYTHON_DIR': None,
171 {
171 'IPYTHONDIR': None,
172 "IPYTHON_DIR": None,
172 'HOME': '/',
173 "IPYTHONDIR": None,
173 }):
174 "HOME": "/",
174 nt.assert_equal(paths.get_ipython_dir(), '/.ipython')
175 }
176 ):
177 assert paths.get_ipython_dir() == "/.ipython"
175
178
176
179
177 def test_get_ipython_cache_dir():
180 def test_get_ipython_cache_dir():
@@ -181,18 +184,16 b' def test_get_ipython_cache_dir():'
181 os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
184 os.makedirs(os.path.join(HOME_TEST_DIR, ".cache"))
182 with modified_env({'XDG_CACHE_HOME': None}):
185 with modified_env({'XDG_CACHE_HOME': None}):
183 ipdir = paths.get_ipython_cache_dir()
186 ipdir = paths.get_ipython_cache_dir()
184 nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"),
187 assert os.path.join(HOME_TEST_DIR, ".cache", "ipython") == ipdir
185 ipdir)
186 assert_isdir(ipdir)
188 assert_isdir(ipdir)
187
189
188 # test env override
190 # test env override
189 with modified_env({"XDG_CACHE_HOME": XDG_CACHE_DIR}):
191 with modified_env({"XDG_CACHE_HOME": XDG_CACHE_DIR}):
190 ipdir = paths.get_ipython_cache_dir()
192 ipdir = paths.get_ipython_cache_dir()
191 assert_isdir(ipdir)
193 assert_isdir(ipdir)
192 nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython"))
194 assert ipdir == os.path.join(XDG_CACHE_DIR, "ipython")
193 else:
195 else:
194 nt.assert_equal(paths.get_ipython_cache_dir(),
196 assert paths.get_ipython_cache_dir() == paths.get_ipython_dir()
195 paths.get_ipython_dir())
196
197
197 def test_get_ipython_package_dir():
198 def test_get_ipython_package_dir():
198 ipdir = paths.get_ipython_package_dir()
199 ipdir = paths.get_ipython_package_dir()
@@ -27,8 +27,6 b' import tempfile'
27 from pathlib import Path
27 from pathlib import Path
28 from unittest import TestCase
28 from unittest import TestCase
29
29
30 import nose.tools as nt
31
32 from IPython.core.profileapp import list_profiles_in, list_bundled_profiles
30 from IPython.core.profileapp import list_profiles_in, list_bundled_profiles
33 from IPython.core.profiledir import ProfileDir
31 from IPython.core.profiledir import ProfileDir
34
32
@@ -139,14 +137,14 b' def test_list_profiles_in():'
139 found_unicode = True
137 found_unicode = True
140 break
138 break
141 if dec.unicode_paths:
139 if dec.unicode_paths:
142 nt.assert_true(found_unicode)
140 assert found_unicode is True
143 nt.assert_equal(set(profiles), {'foo', 'hello'})
141 assert set(profiles) == {"foo", "hello"}
144
142
145
143
146 def test_list_bundled_profiles():
144 def test_list_bundled_profiles():
147 # This variable will need to be updated when a new profile gets bundled
145 # This variable will need to be updated when a new profile gets bundled
148 bundled = sorted(list_bundled_profiles())
146 bundled = sorted(list_bundled_profiles())
149 nt.assert_equal(bundled, [])
147 assert bundled == []
150
148
151
149
152 def test_profile_create_ipython_dir():
150 def test_profile_create_ipython_dir():
@@ -167,4 +165,3 b' def test_profile_create_ipython_dir():'
167 assert Path(profile_dir).exists()
165 assert Path(profile_dir).exists()
168 ipython_config = profile_dir / "ipython_config.py"
166 ipython_config = profile_dir / "ipython_config.py"
169 assert Path(ipython_config).exists()
167 assert Path(ipython_config).exists()
170
@@ -12,12 +12,10 b' import matplotlib'
12 matplotlib.use('Agg')
12 matplotlib.use('Agg')
13 from matplotlib.figure import Figure
13 from matplotlib.figure import Figure
14
14
15 from nose import SkipTest
16 import nose.tools as nt
17
18 from matplotlib import pyplot as plt
15 from matplotlib import pyplot as plt
19 import matplotlib_inline
16 from matplotlib_inline import backend_inline
20 import numpy as np
17 import numpy as np
18 import pytest
21
19
22 from IPython.core.getipython import get_ipython
20 from IPython.core.getipython import get_ipython
23 from IPython.core.interactiveshell import InteractiveShell
21 from IPython.core.interactiveshell import InteractiveShell
@@ -30,7 +28,7 b' from IPython.testing import decorators as dec'
30 def test_figure_to_svg():
28 def test_figure_to_svg():
31 # simple empty-figure test
29 # simple empty-figure test
32 fig = plt.figure()
30 fig = plt.figure()
33 nt.assert_equal(pt.print_figure(fig, 'svg'), None)
31 assert pt.print_figure(fig, "svg") is None
34
32
35 plt.close('all')
33 plt.close('all')
36
34
@@ -39,8 +37,9 b' def test_figure_to_svg():'
39 ax = fig.add_subplot(1,1,1)
37 ax = fig.add_subplot(1,1,1)
40 ax.plot([1,2,3])
38 ax.plot([1,2,3])
41 plt.draw()
39 plt.draw()
42 svg = pt.print_figure(fig, 'svg')[:100].lower()
40 svg = pt.print_figure(fig, "svg")[:100].lower()
43 nt.assert_in(u'doctype svg', svg)
41 assert "doctype svg" in svg
42
44
43
45 def _check_pil_jpeg_bytes():
44 def _check_pil_jpeg_bytes():
46 """Skip if PIL can't write JPEGs to BytesIO objects"""
45 """Skip if PIL can't write JPEGs to BytesIO objects"""
@@ -53,7 +52,7 b' def _check_pil_jpeg_bytes():'
53 img.save(buf, 'jpeg')
52 img.save(buf, 'jpeg')
54 except Exception as e:
53 except Exception as e:
55 ename = e.__class__.__name__
54 ename = e.__class__.__name__
56 raise SkipTest("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e)) from e
55 raise pytest.skip("PIL can't write JPEG to BytesIO: %s: %s" % (ename, e)) from e
57
56
58 @dec.skip_without("PIL.Image")
57 @dec.skip_without("PIL.Image")
59 def test_figure_to_jpeg():
58 def test_figure_to_jpeg():
@@ -69,7 +68,7 b' def test_figure_to_jpeg():'
69 def test_retina_figure():
68 def test_retina_figure():
70 # simple empty-figure test
69 # simple empty-figure test
71 fig = plt.figure()
70 fig = plt.figure()
72 nt.assert_equal(pt.retina_figure(fig), None)
71 assert pt.retina_figure(fig) == None
73 plt.close('all')
72 plt.close('all')
74
73
75 fig = plt.figure()
74 fig = plt.figure()
@@ -78,8 +77,9 b' def test_retina_figure():'
78 plt.draw()
77 plt.draw()
79 png, md = pt.retina_figure(fig)
78 png, md = pt.retina_figure(fig)
80 assert png.startswith(_PNG)
79 assert png.startswith(_PNG)
81 nt.assert_in('width', md)
80 assert "width" in md
82 nt.assert_in('height', md)
81 assert "height" in md
82
83
83
84 _fmt_mime_map = {
84 _fmt_mime_map = {
85 'png': 'image/png',
85 'png': 'image/png',
@@ -95,9 +95,9 b' def test_select_figure_formats_str():'
95 pt.select_figure_formats(ip, fmt)
95 pt.select_figure_formats(ip, fmt)
96 for mime, f in ip.display_formatter.formatters.items():
96 for mime, f in ip.display_formatter.formatters.items():
97 if mime == active_mime:
97 if mime == active_mime:
98 nt.assert_in(Figure, f)
98 assert Figure in f
99 else:
99 else:
100 nt.assert_not_in(Figure, f)
100 assert Figure not in f
101
101
102 def test_select_figure_formats_kwargs():
102 def test_select_figure_formats_kwargs():
103 ip = get_ipython()
103 ip = get_ipython()
@@ -134,24 +134,25 b' def test_select_figure_formats_set():'
134 pt.select_figure_formats(ip, fmts)
134 pt.select_figure_formats(ip, fmts)
135 for mime, f in ip.display_formatter.formatters.items():
135 for mime, f in ip.display_formatter.formatters.items():
136 if mime in active_mimes:
136 if mime in active_mimes:
137 nt.assert_in(Figure, f)
137 assert Figure in f
138 else:
138 else:
139 nt.assert_not_in(Figure, f)
139 assert Figure not in f
140
140
141 def test_select_figure_formats_bad():
141 def test_select_figure_formats_bad():
142 ip = get_ipython()
142 ip = get_ipython()
143 with nt.assert_raises(ValueError):
143 with pytest.raises(ValueError):
144 pt.select_figure_formats(ip, 'foo')
144 pt.select_figure_formats(ip, 'foo')
145 with nt.assert_raises(ValueError):
145 with pytest.raises(ValueError):
146 pt.select_figure_formats(ip, {'png', 'foo'})
146 pt.select_figure_formats(ip, {'png', 'foo'})
147 with nt.assert_raises(ValueError):
147 with pytest.raises(ValueError):
148 pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad'])
148 pt.select_figure_formats(ip, ['retina', 'pdf', 'bar', 'bad'])
149
149
150 def test_import_pylab():
150 def test_import_pylab():
151 ns = {}
151 ns = {}
152 pt.import_pylab(ns, import_all=False)
152 pt.import_pylab(ns, import_all=False)
153 nt.assert_true('plt' in ns)
153 assert "plt" in ns
154 nt.assert_equal(ns['np'], np)
154 assert ns["np"] == np
155
155
156
156 from traitlets.config import Config
157 from traitlets.config import Config
157
158
@@ -182,15 +183,13 b' class TestPylabSwitch(object):'
182 pt.activate_matplotlib = act_mpl
183 pt.activate_matplotlib = act_mpl
183 self._save_ip = pt.import_pylab
184 self._save_ip = pt.import_pylab
184 pt.import_pylab = lambda *a,**kw:None
185 pt.import_pylab = lambda *a,**kw:None
185 self._save_cis = matplotlib_inline.backend_inline.configure_inline_support
186 self._save_cis = backend_inline.configure_inline_support
186 matplotlib_inline.backend_inline.configure_inline_support = (
187 backend_inline.configure_inline_support = lambda *a, **kw: None
187 lambda *a, **kw: None
188 )
189
188
190 def teardown(self):
189 def teardown(self):
191 pt.activate_matplotlib = self._save_am
190 pt.activate_matplotlib = self._save_am
192 pt.import_pylab = self._save_ip
191 pt.import_pylab = self._save_ip
193 matplotlib_inline.backend_inline.configure_inline_support = self._save_cis
192 backend_inline.configure_inline_support = self._save_cis
194 import matplotlib
193 import matplotlib
195 matplotlib.rcParams = self._saved_rcParams
194 matplotlib.rcParams = self._saved_rcParams
196 matplotlib.rcParamsOrig = self._saved_rcParamsOrig
195 matplotlib.rcParamsOrig = self._saved_rcParamsOrig
@@ -199,68 +198,68 b' class TestPylabSwitch(object):'
199
198
200 s = self.Shell()
199 s = self.Shell()
201 gui, backend = s.enable_matplotlib(None)
200 gui, backend = s.enable_matplotlib(None)
202 nt.assert_equal(gui, 'qt')
201 assert gui == "qt"
203 nt.assert_equal(s.pylab_gui_select, 'qt')
202 assert s.pylab_gui_select == "qt"
204
203
205 gui, backend = s.enable_matplotlib('inline')
204 gui, backend = s.enable_matplotlib("inline")
206 nt.assert_equal(gui, 'inline')
205 assert gui == "inline"
207 nt.assert_equal(s.pylab_gui_select, 'qt')
206 assert s.pylab_gui_select == "qt"
208
207
209 gui, backend = s.enable_matplotlib('qt')
208 gui, backend = s.enable_matplotlib("qt")
210 nt.assert_equal(gui, 'qt')
209 assert gui == "qt"
211 nt.assert_equal(s.pylab_gui_select, 'qt')
210 assert s.pylab_gui_select == "qt"
212
211
213 gui, backend = s.enable_matplotlib('inline')
212 gui, backend = s.enable_matplotlib("inline")
214 nt.assert_equal(gui, 'inline')
213 assert gui == "inline"
215 nt.assert_equal(s.pylab_gui_select, 'qt')
214 assert s.pylab_gui_select == "qt"
216
215
217 gui, backend = s.enable_matplotlib()
216 gui, backend = s.enable_matplotlib()
218 nt.assert_equal(gui, 'qt')
217 assert gui == "qt"
219 nt.assert_equal(s.pylab_gui_select, 'qt')
218 assert s.pylab_gui_select == "qt"
220
219
221 def test_inline(self):
220 def test_inline(self):
222 s = self.Shell()
221 s = self.Shell()
223 gui, backend = s.enable_matplotlib('inline')
222 gui, backend = s.enable_matplotlib("inline")
224 nt.assert_equal(gui, 'inline')
223 assert gui == "inline"
225 nt.assert_equal(s.pylab_gui_select, None)
224 assert s.pylab_gui_select == None
226
225
227 gui, backend = s.enable_matplotlib('inline')
226 gui, backend = s.enable_matplotlib("inline")
228 nt.assert_equal(gui, 'inline')
227 assert gui == "inline"
229 nt.assert_equal(s.pylab_gui_select, None)
228 assert s.pylab_gui_select == None
230
229
231 gui, backend = s.enable_matplotlib('qt')
230 gui, backend = s.enable_matplotlib("qt")
232 nt.assert_equal(gui, 'qt')
231 assert gui == "qt"
233 nt.assert_equal(s.pylab_gui_select, 'qt')
232 assert s.pylab_gui_select == "qt"
234
233
235 def test_inline_twice(self):
234 def test_inline_twice(self):
236 "Using '%matplotlib inline' twice should not reset formatters"
235 "Using '%matplotlib inline' twice should not reset formatters"
237
236
238 ip = self.Shell()
237 ip = self.Shell()
239 gui, backend = ip.enable_matplotlib('inline')
238 gui, backend = ip.enable_matplotlib("inline")
240 nt.assert_equal(gui, 'inline')
239 assert gui == "inline"
241
240
242 fmts = {'png'}
241 fmts = {'png'}
243 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
242 active_mimes = {_fmt_mime_map[fmt] for fmt in fmts}
244 pt.select_figure_formats(ip, fmts)
243 pt.select_figure_formats(ip, fmts)
245
244
246 gui, backend = ip.enable_matplotlib('inline')
245 gui, backend = ip.enable_matplotlib("inline")
247 nt.assert_equal(gui, 'inline')
246 assert gui == "inline"
248
247
249 for mime, f in ip.display_formatter.formatters.items():
248 for mime, f in ip.display_formatter.formatters.items():
250 if mime in active_mimes:
249 if mime in active_mimes:
251 nt.assert_in(Figure, f)
250 assert Figure in f
252 else:
251 else:
253 nt.assert_not_in(Figure, f)
252 assert Figure not in f
254
253
255 def test_qt_gtk(self):
254 def test_qt_gtk(self):
256 s = self.Shell()
255 s = self.Shell()
257 gui, backend = s.enable_matplotlib('qt')
256 gui, backend = s.enable_matplotlib("qt")
258 nt.assert_equal(gui, 'qt')
257 assert gui == "qt"
259 nt.assert_equal(s.pylab_gui_select, 'qt')
258 assert s.pylab_gui_select == "qt"
260
259
261 gui, backend = s.enable_matplotlib('gtk')
260 gui, backend = s.enable_matplotlib("gtk")
262 nt.assert_equal(gui, 'qt')
261 assert gui == "qt"
263 nt.assert_equal(s.pylab_gui_select, 'qt')
262 assert s.pylab_gui_select == "qt"
264
263
265
264
266 def test_no_gui_backends():
265 def test_no_gui_backends():
@@ -26,8 +26,7 b' import textwrap'
26 import unittest
26 import unittest
27 from unittest.mock import patch
27 from unittest.mock import patch
28
28
29 import nose.tools as nt
29 import pytest
30 from nose import SkipTest
31
30
32 from IPython.testing import decorators as dec
31 from IPython.testing import decorators as dec
33 from IPython.testing import tools as tt
32 from IPython.testing import tools as tt
@@ -188,7 +187,7 b' class TestMagicRunPass(tt.TempFileMixin):'
188 bid1 = id(_ip.user_ns['__builtins__'])
187 bid1 = id(_ip.user_ns['__builtins__'])
189 self.run_tmpfile()
188 self.run_tmpfile()
190 bid2 = id(_ip.user_ns['__builtins__'])
189 bid2 = id(_ip.user_ns['__builtins__'])
191 nt.assert_equal(bid1, bid2)
190 assert bid1 == bid2
192
191
193 def test_builtins_type(self):
192 def test_builtins_type(self):
194 """Check that the type of __builtins__ doesn't change with %run.
193 """Check that the type of __builtins__ doesn't change with %run.
@@ -199,7 +198,7 b' class TestMagicRunPass(tt.TempFileMixin):'
199 """
198 """
200 _ip = get_ipython()
199 _ip = get_ipython()
201 self.run_tmpfile()
200 self.run_tmpfile()
202 nt.assert_equal(type(_ip.user_ns['__builtins__']),type(sys))
201 assert type(_ip.user_ns["__builtins__"]) == type(sys)
203
202
204 def test_run_profile( self ):
203 def test_run_profile(self):
205 """Test that the option -p, which invokes the profiler, do not
204 """Test that the option -p, which invokes the profiler, do not
@@ -232,9 +231,9 b' class TestMagicRunSimple(tt.TempFileMixin):'
232 src = ("class foo: pass\n"
231 src = ("class foo: pass\n"
233 "def f(): return foo()")
232 "def f(): return foo()")
234 self.mktmp(src)
233 self.mktmp(src)
235 _ip.magic('run %s' % self.fname)
234 _ip.magic("run %s" % self.fname)
236 _ip.run_cell('t = isinstance(f(), foo)')
235 _ip.run_cell("t = isinstance(f(), foo)")
237 nt.assert_true(_ip.user_ns['t'])
236 assert _ip.user_ns["t"] is True
238
237
239 def test_obj_del(self):
238 def test_obj_del(self):
240 """Test that object's __del__ methods are called on exit."""
239 """Test that object's __del__ methods are called on exit."""
@@ -242,7 +241,7 b' class TestMagicRunSimple(tt.TempFileMixin):'
242 try:
241 try:
243 import win32api
242 import win32api
244 except ImportError as e:
243 except ImportError as e:
245 raise SkipTest("Test requires pywin32") from e
244 raise unittest.SkipTest("Test requires pywin32") from e
246 src = ("class A(object):\n"
245 src = ("class A(object):\n"
247 " def __del__(self):\n"
246 " def __del__(self):\n"
248 " print('object A deleted')\n"
247 " print('object A deleted')\n"
@@ -258,34 +257,33 b' class TestMagicRunSimple(tt.TempFileMixin):'
258 # see ticket https://github.com/ipython/ipython/issues/238
257 # see ticket https://github.com/ipython/ipython/issues/238
259
258
260 with tt.TempFileMixin() as empty:
259 with tt.TempFileMixin() as empty:
261 empty.mktmp('')
260 empty.mktmp("")
262 # On Windows, the filename will have \users in it, so we need to use the
261 # On Windows, the filename will have \users in it, so we need to use the
263 # repr so that the \u becomes \\u.
262 # repr so that the \u becomes \\u.
264 src = ("ip = get_ipython()\n"
263 src = (
264 "ip = get_ipython()\n"
265 "for i in range(5):\n"
265 "for i in range(5):\n"
266 " try:\n"
266 " try:\n"
267 " ip.magic(%r)\n"
267 " ip.magic(%r)\n"
268 " except NameError as e:\n"
268 " except NameError as e:\n"
269 " print(i)\n"
269 " print(i)\n"
270 " break\n" % ('run ' + empty.fname))
270 " break\n" % ("run " + empty.fname)
271 )
271 self.mktmp(src)
272 self.mktmp(src)
272 _ip.magic('run %s' % self.fname)
273 _ip.magic("run %s" % self.fname)
273 _ip.run_cell('ip == get_ipython()')
274 _ip.run_cell("ip == get_ipython()")
274 nt.assert_equal(_ip.user_ns['i'], 4)
275 assert _ip.user_ns["i"] == 4
275
276
276 def test_run_second(self):
277 def test_run_second(self):
277 """Test that running a second file doesn't clobber the first, gh-3547
278 """Test that running a second file doesn't clobber the first, gh-3547"""
278 """
279 self.mktmp("avar = 1\n" "def afunc():\n" " return avar\n")
279 self.mktmp("avar = 1\n"
280 "def afunc():\n"
281 " return avar\n")
282
280
283 with tt.TempFileMixin() as empty:
281 with tt.TempFileMixin() as empty:
284 empty.mktmp("")
282 empty.mktmp("")
285
283
286 _ip.magic('run %s' % self.fname)
284 _ip.magic("run %s" % self.fname)
287 _ip.magic('run %s' % empty.fname)
285 _ip.magic("run %s" % empty.fname)
288 nt.assert_equal(_ip.user_ns['afunc'](), 1)
286 assert _ip.user_ns["afunc"]() == 1
289
287
290 @dec.skip_win32
288 @dec.skip_win32
291 def test_tclass(self):
289 def test_tclass(self):
@@ -312,15 +310,15 b' tclass.py: deleting object: C-third'
312 self.mktmp(src)
310 self.mktmp(src)
313 _ip.run_cell("zz = 23")
311 _ip.run_cell("zz = 23")
314 try:
312 try:
315 _ip.magic('run -i %s' % self.fname)
313 _ip.magic("run -i %s" % self.fname)
316 nt.assert_equal(_ip.user_ns['yy'], 23)
314 assert _ip.user_ns["yy"] == 23
317 finally:
315 finally:
318 _ip.magic('reset -f')
316 _ip.magic('reset -f')
319
317
320 _ip.run_cell("zz = 23")
318 _ip.run_cell("zz = 23")
321 try:
319 try:
322 _ip.magic('run -i %s' % self.fname)
320 _ip.magic("run -i %s" % self.fname)
323 nt.assert_equal(_ip.user_ns['yy'], 23)
321 assert _ip.user_ns["yy"] == 23
324 finally:
322 finally:
325 _ip.magic('reset -f')
323 _ip.magic('reset -f')
326
324
@@ -329,7 +327,7 b' tclass.py: deleting object: C-third'
329 mydir = os.path.dirname(__file__)
327 mydir = os.path.dirname(__file__)
330 na = os.path.join(mydir, 'nonascii.py')
328 na = os.path.join(mydir, 'nonascii.py')
331 _ip.magic('run "%s"' % na)
329 _ip.magic('run "%s"' % na)
332 nt.assert_equal(_ip.user_ns['u'], u'Ўт№Ф')
330 assert _ip.user_ns["u"] == "Ўт№Ф"
333
331
334 def test_run_py_file_attribute(self):
332 def test_run_py_file_attribute(self):
335 """Test handling of `__file__` attribute in `%run <file>.py`."""
333 """Test handling of `__file__` attribute in `%run <file>.py`."""
@@ -342,10 +340,10 b' tclass.py: deleting object: C-third'
342
340
343 # Check that __file__ was equal to the filename in the script's
341 # Check that __file__ was equal to the filename in the script's
344 # namespace.
342 # namespace.
345 nt.assert_equal(_ip.user_ns['t'], self.fname)
343 assert _ip.user_ns["t"] == self.fname
346
344
347 # Check that __file__ was not leaked back into user_ns.
345 # Check that __file__ was not leaked back into user_ns.
348 nt.assert_equal(file1, file2)
346 assert file1 == file2
349
347
350 def test_run_ipy_file_attribute(self):
348 def test_run_ipy_file_attribute(self):
351 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
349 """Test handling of `__file__` attribute in `%run <file.ipy>`."""
@@ -358,10 +356,10 b' tclass.py: deleting object: C-third'
358
356
359 # Check that __file__ was equal to the filename in the script's
357 # Check that __file__ was equal to the filename in the script's
360 # namespace.
358 # namespace.
361 nt.assert_equal(_ip.user_ns['t'], self.fname)
359 assert _ip.user_ns["t"] == self.fname
362
360
363 # Check that __file__ was not leaked back into user_ns.
361 # Check that __file__ was not leaked back into user_ns.
364 nt.assert_equal(file1, file2)
362 assert file1 == file2
365
363
366 def test_run_formatting(self):
364 def test_run_formatting(self):
367 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
365 """ Test that %run -t -N<N> does not raise a TypeError for N > 1."""
@@ -394,16 +392,16 b' tclass.py: deleting object: C-third'
394
392
395 _ip.magic("run %s" % self.fname)
393 _ip.magic("run %s" % self.fname)
396
394
397 nt.assert_equal(_ip.user_ns['answer'], 42)
395 assert _ip.user_ns["answer"] == 42
398
396
399 def test_run_nb_error(self):
397 def test_run_nb_error(self):
400 """Test %run notebook.ipynb error"""
398 """Test %run notebook.ipynb error"""
401 from nbformat import v4, writes
399 from nbformat import v4, writes
402 # %run when a file name isn't provided
400 # %run when a file name isn't provided
403 nt.assert_raises(Exception, _ip.magic, "run")
401 pytest.raises(Exception, _ip.magic, "run")
404
402
405 # %run when a file doesn't exist
403 # %run when a file doesn't exist
406 nt.assert_raises(Exception, _ip.magic, "run foobar.ipynb")
404 pytest.raises(Exception, _ip.magic, "run foobar.ipynb")
407
405
408 # %run on a notebook with an error
406 # %run on a notebook with an error
409 nb = v4.new_notebook(
407 nb = v4.new_notebook(
@@ -413,15 +411,15 b' tclass.py: deleting object: C-third'
413 )
411 )
414 src = writes(nb, version=4)
412 src = writes(nb, version=4)
415 self.mktmp(src, ext='.ipynb')
413 self.mktmp(src, ext='.ipynb')
416 nt.assert_raises(Exception, _ip.magic, "run %s" % self.fname)
414 pytest.raises(Exception, _ip.magic, "run %s" % self.fname)
417
415
418 def test_file_options(self):
416 def test_file_options(self):
419 src = ('import sys\n'
417 src = ('import sys\n'
420 'a = " ".join(sys.argv[1:])\n')
418 'a = " ".join(sys.argv[1:])\n')
421 self.mktmp(src)
419 self.mktmp(src)
422 test_opts = '-x 3 --verbose'
420 test_opts = "-x 3 --verbose"
423 _ip.run_line_magic("run", '{0} {1}'.format(self.fname, test_opts))
421 _ip.run_line_magic("run", "{0} {1}".format(self.fname, test_opts))
424 nt.assert_equal(_ip.user_ns['a'], test_opts)
422 assert _ip.user_ns["a"] == test_opts
425
423
426
424
427 class TestMagicRunWithPackage(unittest.TestCase):
425 class TestMagicRunWithPackage(unittest.TestCase):
@@ -500,16 +498,17 b' class TestMagicRunWithPackage(unittest.TestCase):'
500 self.check_run_submodule('relative', '-d')
498 self.check_run_submodule('relative', '-d')
501
499
502 def test_module_options(self):
500 def test_module_options(self):
503 _ip.user_ns.pop('a', None)
501 _ip.user_ns.pop("a", None)
504 test_opts = '-x abc -m test'
502 test_opts = "-x abc -m test"
505 _ip.run_line_magic('run', '-m {0}.args {1}'.format(self.package, test_opts))
503 _ip.run_line_magic("run", "-m {0}.args {1}".format(self.package, test_opts))
506 nt.assert_equal(_ip.user_ns['a'], test_opts)
504 assert _ip.user_ns["a"] == test_opts
507
505
508 def test_module_options_with_separator(self):
506 def test_module_options_with_separator(self):
509 _ip.user_ns.pop('a', None)
507 _ip.user_ns.pop("a", None)
510 test_opts = '-x abc -m test'
508 test_opts = "-x abc -m test"
511 _ip.run_line_magic('run', '-m {0}.args -- {1}'.format(self.package, test_opts))
509 _ip.run_line_magic("run", "-m {0}.args -- {1}".format(self.package, test_opts))
512 nt.assert_equal(_ip.user_ns['a'], test_opts)
510 assert _ip.user_ns["a"] == test_opts
511
513
512
514 def test_run__name__():
513 def test_run__name__():
515 with TemporaryDirectory() as td:
514 with TemporaryDirectory() as td:
@@ -517,16 +516,16 b' def test_run__name__():'
517 with open(path, 'w') as f:
516 with open(path, 'w') as f:
518 f.write("q = __name__")
517 f.write("q = __name__")
519
518
520 _ip.user_ns.pop('q', None)
519 _ip.user_ns.pop("q", None)
521 _ip.magic('run {}'.format(path))
520 _ip.magic("run {}".format(path))
522 nt.assert_equal(_ip.user_ns.pop('q'), '__main__')
521 assert _ip.user_ns.pop("q") == "__main__"
523
522
524 _ip.magic('run -n {}'.format(path))
523 _ip.magic("run -n {}".format(path))
525 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
524 assert _ip.user_ns.pop("q") == "foo"
526
525
527 try:
526 try:
528 _ip.magic('run -i -n {}'.format(path))
527 _ip.magic("run -i -n {}".format(path))
529 nt.assert_equal(_ip.user_ns.pop('q'), 'foo')
528 assert _ip.user_ns.pop("q") == "foo"
530 finally:
529 finally:
531 _ip.magic('reset -f')
530 _ip.magic('reset -f')
532
531
@@ -546,9 +545,9 b' def test_run_tb():'
546 with capture_output() as io:
545 with capture_output() as io:
547 _ip.magic('run {}'.format(path))
546 _ip.magic('run {}'.format(path))
548 out = io.stdout
547 out = io.stdout
549 nt.assert_not_in("execfile", out)
548 assert "execfile" not in out
550 nt.assert_in("RuntimeError", out)
549 assert "RuntimeError" in out
551 nt.assert_equal(out.count("---->"), 3)
550 assert out.count("---->") == 3
552 del ip.user_ns['bar']
551 del ip.user_ns['bar']
553 del ip.user_ns['foo']
552 del ip.user_ns['foo']
554
553
@@ -572,10 +571,10 b' def test_multiprocessing_run():'
572 _ip.run_line_magic('run', path)
571 _ip.run_line_magic('run', path)
573 _ip.run_cell("i_m_undefined")
572 _ip.run_cell("i_m_undefined")
574 out = io.stdout
573 out = io.stdout
575 nt.assert_in("hoy", out)
574 assert "hoy" in out
576 nt.assert_not_in("AttributeError", out)
575 assert "AttributeError" not in out
577 nt.assert_in("NameError", out)
576 assert "NameError" in out
578 nt.assert_equal(out.count("---->"), 1)
577 assert out.count("---->") == 1
579 except:
578 except:
580 raise
579 raise
581 finally:
580 finally:
@@ -595,7 +594,6 b' def test_script_tb():'
595 "foo()",
594 "foo()",
596 ]))
595 ]))
597 out, err = tt.ipexec(path)
596 out, err = tt.ipexec(path)
598 nt.assert_not_in("execfile", out)
597 assert "execfile" not in out
599 nt.assert_in("RuntimeError", out)
598 assert "RuntimeError" in out
600 nt.assert_equal(out.count("---->"), 3)
599 assert out.count("---->") == 3
601
@@ -1,38 +1,38 b''
1 # coding: utf-8
1 # coding: utf-8
2 import nose.tools as nt
3
2
4 from IPython.core.splitinput import split_user_input, LineInfo
3 from IPython.core.splitinput import split_user_input, LineInfo
5 from IPython.testing import tools as tt
4 from IPython.testing import tools as tt
6
5
7 tests = [
6 tests = [
8 ('x=1', ('', '', 'x', '=1')),
7 ("x=1", ("", "", "x", "=1")),
9 ('?', ('', '?', '', '')),
8 ("?", ("", "?", "", "")),
10 ('??', ('', '??', '', '')),
9 ("??", ("", "??", "", "")),
11 (' ?', (' ', '?', '', '')),
10 (" ?", (" ", "?", "", "")),
12 (' ??', (' ', '??', '', '')),
11 (" ??", (" ", "??", "", "")),
13 ('??x', ('', '??', 'x', '')),
12 ("??x", ("", "??", "x", "")),
14 ('?x=1', ('', '?', 'x', '=1')),
13 ("?x=1", ("", "?", "x", "=1")),
15 ('!ls', ('', '!', 'ls', '')),
14 ("!ls", ("", "!", "ls", "")),
16 (' !ls', (' ', '!', 'ls', '')),
15 (" !ls", (" ", "!", "ls", "")),
17 ('!!ls', ('', '!!', 'ls', '')),
16 ("!!ls", ("", "!!", "ls", "")),
18 (' !!ls', (' ', '!!', 'ls', '')),
17 (" !!ls", (" ", "!!", "ls", "")),
19 (',ls', ('', ',', 'ls', '')),
18 (",ls", ("", ",", "ls", "")),
20 (';ls', ('', ';', 'ls', '')),
19 (";ls", ("", ";", "ls", "")),
21 (' ;ls', (' ', ';', 'ls', '')),
20 (" ;ls", (" ", ";", "ls", "")),
22 ('f.g(x)', ('', '', 'f.g', '(x)')),
21 ("f.g(x)", ("", "", "f.g", "(x)")),
23 ('f.g (x)', ('', '', 'f.g', '(x)')),
22 ("f.g (x)", ("", "", "f.g", "(x)")),
24 ('?%hist1', ('', '?', '%hist1', '')),
23 ("?%hist1", ("", "?", "%hist1", "")),
25 ('?%%hist2', ('', '?', '%%hist2', '')),
24 ("?%%hist2", ("", "?", "%%hist2", "")),
26 ('??%hist3', ('', '??', '%hist3', '')),
25 ("??%hist3", ("", "??", "%hist3", "")),
27 ('??%%hist4', ('', '??', '%%hist4', '')),
26 ("??%%hist4", ("", "??", "%%hist4", "")),
28 ('?x*', ('', '?', 'x*', '')),
27 ("?x*", ("", "?", "x*", "")),
29 ]
28 ]
30 tests.append((u"Pérez Fernando", (u'', u'', u'Pérez', u'Fernando')))
29 tests.append(("Pérez Fernando", ("", "", "Pérez", "Fernando")))
30
31
31
32 def test_split_user_input():
32 def test_split_user_input():
33 return tt.check_pairs(split_user_input, tests)
33 return tt.check_pairs(split_user_input, tests)
34
34
35 def test_LineInfo():
35 def test_LineInfo():
36 """Simple test for LineInfo construction and str()"""
36 """Simple test for LineInfo construction and str()"""
37 linfo = LineInfo(' %cd /home')
37 linfo = LineInfo(" %cd /home")
38 nt.assert_equal(str(linfo), 'LineInfo [ |%|cd|/home]')
38 assert str(linfo) == "LineInfo [ |%|cd|/home]"
@@ -21,7 +21,6 b' import random'
21 import time
21 import time
22 from io import StringIO
22 from io import StringIO
23
23
24 import nose.tools as nt
25 import IPython.testing.tools as tt
24 import IPython.testing.tools as tt
26
25
27 from unittest import TestCase
26 from unittest import TestCase
@@ -227,12 +226,12 b' class TestAutoreload(Fixture):'
227 self.shell.run_code("from %s import MyClass" % mod_name)
226 self.shell.run_code("from %s import MyClass" % mod_name)
228 self.shell.run_code("first = MyClass(5)")
227 self.shell.run_code("first = MyClass(5)")
229 self.shell.run_code("first.square()")
228 self.shell.run_code("first.square()")
230 with nt.assert_raises(AttributeError):
229 with self.assertRaises(AttributeError):
231 self.shell.run_code("first.cube()")
230 self.shell.run_code("first.cube()")
232 with nt.assert_raises(AttributeError):
231 with self.assertRaises(AttributeError):
233 self.shell.run_code("first.power(5)")
232 self.shell.run_code("first.power(5)")
234 self.shell.run_code("first.b")
233 self.shell.run_code("first.b")
235 with nt.assert_raises(AttributeError):
234 with self.assertRaises(AttributeError):
236 self.shell.run_code("first.toto")
235 self.shell.run_code("first.toto")
237
236
238 # remove square, add power
237 # remove square, add power
@@ -258,13 +257,13 b' class TestAutoreload(Fixture):'
258
257
259 for object_name in {"first", "second"}:
258 for object_name in {"first", "second"}:
260 self.shell.run_code(f"{object_name}.power(5)")
259 self.shell.run_code(f"{object_name}.power(5)")
261 with nt.assert_raises(AttributeError):
260 with self.assertRaises(AttributeError):
262 self.shell.run_code(f"{object_name}.cube()")
261 self.shell.run_code(f"{object_name}.cube()")
263 with nt.assert_raises(AttributeError):
262 with self.assertRaises(AttributeError):
264 self.shell.run_code(f"{object_name}.square()")
263 self.shell.run_code(f"{object_name}.square()")
265 self.shell.run_code(f"{object_name}.b")
264 self.shell.run_code(f"{object_name}.b")
266 self.shell.run_code(f"{object_name}.a")
265 self.shell.run_code(f"{object_name}.a")
267 with nt.assert_raises(AttributeError):
266 with self.assertRaises(AttributeError):
268 self.shell.run_code(f"{object_name}.toto")
267 self.shell.run_code(f"{object_name}.toto")
269
268
270 def test_autoload_newly_added_objects(self):
269 def test_autoload_newly_added_objects(self):
@@ -275,11 +274,11 b' class TestAutoreload(Fixture):'
275 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
274 mod_name, mod_fn = self.new_module(textwrap.dedent(mod_code))
276 self.shell.run_code(f"from {mod_name} import *")
275 self.shell.run_code(f"from {mod_name} import *")
277 self.shell.run_code("func1()")
276 self.shell.run_code("func1()")
278 with nt.assert_raises(NameError):
277 with self.assertRaises(NameError):
279 self.shell.run_code("func2()")
278 self.shell.run_code("func2()")
280 with nt.assert_raises(NameError):
279 with self.assertRaises(NameError):
281 self.shell.run_code("t = Test()")
280 self.shell.run_code("t = Test()")
282 with nt.assert_raises(NameError):
281 with self.assertRaises(NameError):
283 self.shell.run_code("number")
282 self.shell.run_code("number")
284
283
285 # ----------- TEST NEW OBJ LOADED --------------------------
284 # ----------- TEST NEW OBJ LOADED --------------------------
@@ -391,19 +390,19 b" class Bar: # old-style class: weakref doesn't work for it on Python < 2.7"
391 self.shell.magic_aimport(mod_name)
390 self.shell.magic_aimport(mod_name)
392 stream = StringIO()
391 stream = StringIO()
393 self.shell.magic_aimport("", stream=stream)
392 self.shell.magic_aimport("", stream=stream)
394 nt.assert_in(("Modules to reload:\n%s" % mod_name), stream.getvalue())
393 self.assertIn(("Modules to reload:\n%s" % mod_name), stream.getvalue())
395
394
396 with nt.assert_raises(ImportError):
395 with self.assertRaises(ImportError):
397 self.shell.magic_aimport("tmpmod_as318989e89ds")
396 self.shell.magic_aimport("tmpmod_as318989e89ds")
398 else:
397 else:
399 self.shell.magic_autoreload("2")
398 self.shell.magic_autoreload("2")
400 self.shell.run_code("import %s" % mod_name)
399 self.shell.run_code("import %s" % mod_name)
401 stream = StringIO()
400 stream = StringIO()
402 self.shell.magic_aimport("", stream=stream)
401 self.shell.magic_aimport("", stream=stream)
403 nt.assert_true(
402 self.assertTrue(
404 "Modules to reload:\nall-except-skipped" in stream.getvalue()
403 "Modules to reload:\nall-except-skipped" in stream.getvalue()
405 )
404 )
406 nt.assert_in(mod_name, self.shell.ns)
405 self.assertIn(mod_name, self.shell.ns)
407
406
408 mod = sys.modules[mod_name]
407 mod = sys.modules[mod_name]
409
408
@@ -415,21 +414,21 b" class Bar: # old-style class: weakref doesn't work for it on Python < 2.7"
415 old_obj2 = mod.Bar()
414 old_obj2 = mod.Bar()
416
415
417 def check_module_contents():
416 def check_module_contents():
418 nt.assert_equal(mod.x, 9)
417 self.assertEqual(mod.x, 9)
419 nt.assert_equal(mod.z, 123)
418 self.assertEqual(mod.z, 123)
420
419
421 nt.assert_equal(old_foo(0), 3)
420 self.assertEqual(old_foo(0), 3)
422 nt.assert_equal(mod.foo(0), 3)
421 self.assertEqual(mod.foo(0), 3)
423
422
424 obj = mod.Baz(9)
423 obj = mod.Baz(9)
425 nt.assert_equal(old_obj.bar(1), 10)
424 self.assertEqual(old_obj.bar(1), 10)
426 nt.assert_equal(obj.bar(1), 10)
425 self.assertEqual(obj.bar(1), 10)
427 nt.assert_equal(obj.quux, 42)
426 self.assertEqual(obj.quux, 42)
428 nt.assert_equal(obj.zzz(), 99)
427 self.assertEqual(obj.zzz(), 99)
429
428
430 obj2 = mod.Bar()
429 obj2 = mod.Bar()
431 nt.assert_equal(old_obj2.foo(), 1)
430 self.assertEqual(old_obj2.foo(), 1)
432 nt.assert_equal(obj2.foo(), 1)
431 self.assertEqual(obj2.foo(), 1)
433
432
434 check_module_contents()
433 check_module_contents()
435
434
@@ -481,25 +480,25 b' class Bar: # old-style class'
481 )
480 )
482
481
483 def check_module_contents():
482 def check_module_contents():
484 nt.assert_equal(mod.x, 10)
483 self.assertEqual(mod.x, 10)
485 nt.assert_false(hasattr(mod, "z"))
484 self.assertFalse(hasattr(mod, "z"))
486
485
487 nt.assert_equal(old_foo(0), 4) # superreload magic!
486 self.assertEqual(old_foo(0), 4) # superreload magic!
488 nt.assert_equal(mod.foo(0), 4)
487 self.assertEqual(mod.foo(0), 4)
489
488
490 obj = mod.Baz(9)
489 obj = mod.Baz(9)
491 nt.assert_equal(old_obj.bar(1), 11) # superreload magic!
490 self.assertEqual(old_obj.bar(1), 11) # superreload magic!
492 nt.assert_equal(obj.bar(1), 11)
491 self.assertEqual(obj.bar(1), 11)
493
492
494 nt.assert_equal(old_obj.quux, 43)
493 self.assertEqual(old_obj.quux, 43)
495 nt.assert_equal(obj.quux, 43)
494 self.assertEqual(obj.quux, 43)
496
495
497 nt.assert_false(hasattr(old_obj, "zzz"))
496 self.assertFalse(hasattr(old_obj, "zzz"))
498 nt.assert_false(hasattr(obj, "zzz"))
497 self.assertFalse(hasattr(obj, "zzz"))
499
498
500 obj2 = mod.Bar()
499 obj2 = mod.Bar()
501 nt.assert_equal(old_obj2.foo(), 2)
500 self.assertEqual(old_obj2.foo(), 2)
502 nt.assert_equal(obj2.foo(), 2)
501 self.assertEqual(obj2.foo(), 2)
503
502
504 self.shell.run_code("pass") # trigger reload
503 self.shell.run_code("pass") # trigger reload
505 check_module_contents()
504 check_module_contents()
@@ -519,7 +518,7 b' class Bar: # old-style class'
519 self.shell.magic_aimport("-" + mod_name)
518 self.shell.magic_aimport("-" + mod_name)
520 stream = StringIO()
519 stream = StringIO()
521 self.shell.magic_aimport("", stream=stream)
520 self.shell.magic_aimport("", stream=stream)
522 nt.assert_true(("Modules to skip:\n%s" % mod_name) in stream.getvalue())
521 self.assertTrue(("Modules to skip:\n%s" % mod_name) in stream.getvalue())
523
522
524 # This should succeed, although no such module exists
523 # This should succeed, although no such module exists
525 self.shell.magic_aimport("-tmpmod_as318989e89ds")
524 self.shell.magic_aimport("-tmpmod_as318989e89ds")
@@ -546,7 +545,7 b' x = -99'
546 self.shell.magic_autoreload("")
545 self.shell.magic_autoreload("")
547
546
548 self.shell.run_code("pass") # trigger reload
547 self.shell.run_code("pass") # trigger reload
549 nt.assert_equal(mod.x, -99)
548 self.assertEqual(mod.x, -99)
550
549
551 def test_smoketest_aimport(self):
550 def test_smoketest_aimport(self):
552 self._check_smoketest(use_aimport=True)
551 self._check_smoketest(use_aimport=True)
@@ -1,7 +1,6 b''
1 import tempfile, os
1 import tempfile, os
2
2
3 from traitlets.config.loader import Config
3 from traitlets.config.loader import Config
4 import nose.tools as nt
5
4
6
5
7 def setup_module():
6 def setup_module():
@@ -23,10 +22,10 b' def test_store_restore():'
23 ip.magic('store foobar foobaz')
22 ip.magic('store foobar foobaz')
24
23
25 # Check storing
24 # Check storing
26 nt.assert_equal(ip.db['autorestore/foo'], 78)
25 assert ip.db["autorestore/foo"] == 78
27 nt.assert_in('bar', ip.db['stored_aliases'])
26 assert "bar" in ip.db["stored_aliases"]
28 nt.assert_equal(ip.db['autorestore/foobar'], 79)
27 assert ip.db["autorestore/foobar"] == 79
29 nt.assert_equal(ip.db['autorestore/foobaz'], '80')
28 assert ip.db["autorestore/foobaz"] == "80"
30
29
31 # Remove those items
30 # Remove those items
32 ip.user_ns.pop('foo', None)
31 ip.user_ns.pop('foo', None)
@@ -37,14 +36,14 b' def test_store_restore():'
37 ip.user_ns['_dh'][:] = []
36 ip.user_ns['_dh'][:] = []
38
37
39 # Check restoring
38 # Check restoring
40 ip.magic('store -r foo bar foobar foobaz')
39 ip.magic("store -r foo bar foobar foobaz")
41 nt.assert_equal(ip.user_ns['foo'], 78)
40 assert ip.user_ns["foo"] == 78
42 assert ip.alias_manager.is_alias('bar')
41 assert ip.alias_manager.is_alias("bar")
43 nt.assert_equal(ip.user_ns['foobar'], 79)
42 assert ip.user_ns["foobar"] == 79
44 nt.assert_equal(ip.user_ns['foobaz'], '80')
43 assert ip.user_ns["foobaz"] == "80"
45
44
46 ip.magic('store -r') # restores _dh too
45 ip.magic("store -r") # restores _dh too
47 nt.assert_in(os.path.realpath(tmpd), ip.user_ns['_dh'])
46 assert os.path.realpath(tmpd) in ip.user_ns["_dh"]
48
47
49 os.rmdir(tmpd)
48 os.rmdir(tmpd)
50
49
@@ -57,10 +56,10 b' def test_autorestore():'
57 orig_config = ip.config
56 orig_config = ip.config
58 try:
57 try:
59 ip.config = c
58 ip.config = c
60 ip.extension_manager.reload_extension('storemagic')
59 ip.extension_manager.reload_extension("storemagic")
61 nt.assert_not_in('foo', ip.user_ns)
60 assert "foo" not in ip.user_ns
62 c.StoreMagics.autorestore = True
61 c.StoreMagics.autorestore = True
63 ip.extension_manager.reload_extension('storemagic')
62 ip.extension_manager.reload_extension("storemagic")
64 nt.assert_equal(ip.user_ns['foo'], 95)
63 assert ip.user_ns["foo"] == 95
65 finally:
64 finally:
66 ip.config = orig_config
65 ip.config = orig_config
@@ -1,5 +1,3 b''
1 import nose.tools as nt
2
3 from IPython.core.error import TryNext
1 from IPython.core.error import TryNext
4 from IPython.lib.clipboard import ClipboardEmpty
2 from IPython.lib.clipboard import ClipboardEmpty
5 from IPython.testing.decorators import skip_if_no_x11
3 from IPython.testing.decorators import skip_if_no_x11
@@ -18,4 +16,4 b' def test_clipboard_get():'
18 # No clipboard access API available
16 # No clipboard access API available
19 pass
17 pass
20 else:
18 else:
21 nt.assert_is_instance(a, str)
19 assert isinstance(a, str)
@@ -6,8 +6,6 b''
6
6
7 from pathlib import Path
7 from pathlib import Path
8
8
9 import nose.tools as nt
10
11 from IPython.utils.syspathcontext import prepended_to_syspath
9 from IPython.utils.syspathcontext import prepended_to_syspath
12 from IPython.utils.tempdir import TemporaryDirectory
10 from IPython.utils.tempdir import TemporaryDirectory
13 from IPython.lib.deepreload import reload as dreload
11 from IPython.lib.deepreload import reload as dreload
@@ -28,9 +26,9 b' def test_deepreload():'
28 # Test that A is not reloaded.
26 # Test that A is not reloaded.
29 obj = A.Object()
27 obj = A.Object()
30 dreload(B, exclude=["A"])
28 dreload(B, exclude=["A"])
31 nt.assert_true(isinstance(obj, A.Object))
29 assert isinstance(obj, A.Object) is True
32
30
33 # Test that A is reloaded.
31 # Test that A is reloaded.
34 obj = A.Object()
32 obj = A.Object()
35 dreload(B)
33 dreload(B)
36 nt.assert_false(isinstance(obj, A.Object))
34 assert isinstance(obj, A.Object) is False
@@ -21,7 +21,7 b' import wave'
21 from io import BytesIO
21 from io import BytesIO
22
22
23 # Third-party imports
23 # Third-party imports
24 import nose.tools as nt
24 import pytest
25
25
26 try:
26 try:
27 import numpy
27 import numpy
@@ -48,10 +48,10 b' def test_instantiation_FileLink():'
48 fl = display.FileLink(pathlib.PurePath('example.txt'))
48 fl = display.FileLink(pathlib.PurePath('example.txt'))
49
49
50 def test_warning_on_non_existent_path_FileLink():
50 def test_warning_on_non_existent_path_FileLink():
51 """FileLink: Calling _repr_html_ on non-existent files returns a warning
51 """FileLink: Calling _repr_html_ on non-existent files returns a warning"""
52 """
52 fl = display.FileLink("example.txt")
53 fl = display.FileLink('example.txt')
53 assert fl._repr_html_().startswith("Path (<tt>example.txt</tt>)")
54 nt.assert_true(fl._repr_html_().startswith('Path (<tt>example.txt</tt>)'))
54
55
55
56 def test_existing_path_FileLink():
56 def test_existing_path_FileLink():
57 """FileLink: Calling _repr_html_ functions as expected on existing filepath
57 """FileLink: Calling _repr_html_ functions as expected on existing filepath
@@ -77,7 +77,7 b' def test_error_on_directory_to_FileLink():'
77 """FileLink: Raises error when passed directory
77 """FileLink: Raises error when passed directory
78 """
78 """
79 td = mkdtemp()
79 td = mkdtemp()
80 nt.assert_raises(ValueError,display.FileLink,td)
80 pytest.raises(ValueError, display.FileLink, td)
81
81
82 #--------------------------
82 #--------------------------
83 # FileLinks tests
83 # FileLinks tests
@@ -89,10 +89,10 b' def test_instantiation_FileLinks():'
89 fls = display.FileLinks('example')
89 fls = display.FileLinks('example')
90
90
91 def test_warning_on_non_existent_path_FileLinks():
91 def test_warning_on_non_existent_path_FileLinks():
92 """FileLinks: Calling _repr_html_ on non-existent files returns a warning
92 """FileLinks: Calling _repr_html_ on non-existent files returns a warning"""
93 """
93 fls = display.FileLinks("example")
94 fls = display.FileLinks('example')
94 assert fls._repr_html_().startswith("Path (<tt>example</tt>)")
95 nt.assert_true(fls._repr_html_().startswith('Path (<tt>example</tt>)'))
95
96
96
97 def test_existing_path_FileLinks():
97 def test_existing_path_FileLinks():
98 """FileLinks: Calling _repr_html_ functions as expected on existing dir
98 """FileLinks: Calling _repr_html_ functions as expected on existing dir
@@ -172,7 +172,8 b' def test_error_on_file_to_FileLinks():'
172 """
172 """
173 td = mkdtemp()
173 td = mkdtemp()
174 tf1 = NamedTemporaryFile(dir=td)
174 tf1 = NamedTemporaryFile(dir=td)
175 nt.assert_raises(ValueError,display.FileLinks,tf1.name)
175 pytest.raises(ValueError, display.FileLinks, tf1.name)
176
176
177
177 def test_recursive_FileLinks():
178 def test_recursive_FileLinks():
178 """FileLinks: Does not recurse when recursive=False
179 """FileLinks: Does not recurse when recursive=False
@@ -210,7 +211,7 b' class TestAudioDataWithNumpy(TestCase):'
210
211
211 @skipif_not_numpy
212 @skipif_not_numpy
212 def test_audio_from_numpy_array_without_rate_raises(self):
213 def test_audio_from_numpy_array_without_rate_raises(self):
213 nt.assert_raises(ValueError, display.Audio, get_test_tone())
214 self.assertRaises(ValueError, display.Audio, get_test_tone())
214
215
215 @skipif_not_numpy
216 @skipif_not_numpy
216 def test_audio_data_normalization(self):
217 def test_audio_data_normalization(self):
@@ -232,10 +233,10 b' class TestAudioDataWithNumpy(TestCase):'
232 assert actual_max_value == expected_max_value
233 assert actual_max_value == expected_max_value
233
234
234 def test_audio_data_without_normalization_raises_for_invalid_data(self):
235 def test_audio_data_without_normalization_raises_for_invalid_data(self):
235 nt.assert_raises(
236 self.assertRaises(
236 ValueError,
237 ValueError,
237 lambda: display.Audio([1.001], rate=44100, normalize=False))
238 lambda: display.Audio([1.001], rate=44100, normalize=False))
238 nt.assert_raises(
239 self.assertRaises(
239 ValueError,
240 ValueError,
240 lambda: display.Audio([-1.001], rate=44100, normalize=False))
241 lambda: display.Audio([-1.001], rate=44100, normalize=False))
241
242
@@ -253,9 +254,8 b' class TestAudioDataWithoutNumpy(TestAudioDataWithNumpy):'
253 @skipif_not_numpy
254 @skipif_not_numpy
254 def test_audio_raises_for_nested_list(self):
255 def test_audio_raises_for_nested_list(self):
255 stereo_signal = [list(get_test_tone())] * 2
256 stereo_signal = [list(get_test_tone())] * 2
256 nt.assert_raises(
257 self.assertRaises(TypeError, lambda: display.Audio(stereo_signal, rate=44100))
257 TypeError,
258
258 lambda: display.Audio(stereo_signal, rate=44100))
259
259
260 @skipif_not_numpy
260 @skipif_not_numpy
261 def get_test_tone(scale=1):
261 def get_test_tone(scale=1):
@@ -5,7 +5,6 b''
5 from contextlib import contextmanager
5 from contextlib import contextmanager
6 from unittest.mock import patch
6 from unittest.mock import patch
7
7
8 import nose.tools as nt
9 import pytest
8 import pytest
10
9
11 from IPython.lib import latextools
10 from IPython.lib import latextools
@@ -185,7 +184,13 b' def test_latex_to_png_invalid_hex_colors():'
185 Test that invalid hex colors provided to dvipng gives an exception.
184 Test that invalid hex colors provided to dvipng gives an exception.
186 """
185 """
187 latex_string = "$x^2$"
186 latex_string = "$x^2$"
188 nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
187 pytest.raises(
189 backend='dvipng', color="#f00bar"))
188 ValueError,
190 nt.assert_raises(ValueError, lambda: latextools.latex_to_png(latex_string,
189 lambda: latextools.latex_to_png(
191 backend='dvipng', color="#f00"))
190 latex_string, backend="dvipng", color="#f00bar"
191 ),
192 )
193 pytest.raises(
194 ValueError,
195 lambda: latextools.latex_to_png(latex_string, backend="dvipng", color="#f00"),
196 )
@@ -11,7 +11,6 b' import types'
11 import string
11 import string
12 import unittest
12 import unittest
13
13
14 import nose.tools as nt
15 import pytest
14 import pytest
16
15
17 from IPython.lib import pretty
16 from IPython.lib import pretty
@@ -70,7 +69,6 b' class BreakingRepr(object):'
70 return "Breaking(\n)"
69 return "Breaking(\n)"
71
70
72 class BadRepr(object):
71 class BadRepr(object):
73
74 def __repr__(self):
72 def __repr__(self):
75 return 1/0
73 return 1/0
76
74
@@ -178,7 +176,7 b' def test_pprint_break_repr():'
178
176
179 def test_bad_repr():
177 def test_bad_repr():
180 """Don't catch bad repr errors"""
178 """Don't catch bad repr errors"""
181 with nt.assert_raises(ZeroDivisionError):
179 with pytest.raises(ZeroDivisionError):
182 pretty.pretty(BadRepr())
180 pretty.pretty(BadRepr())
183
181
184 class BadException(Exception):
182 class BadException(Exception):
@@ -195,7 +193,7 b' class ReallyBadRepr(object):'
195 raise BadException()
193 raise BadException()
196
194
197 def test_really_bad_repr():
195 def test_really_bad_repr():
198 with nt.assert_raises(BadException):
196 with pytest.raises(BadException):
199 pretty.pretty(ReallyBadRepr())
197 pretty.pretty(ReallyBadRepr())
200
198
201
199
@@ -293,7 +291,7 b' def test_basic_class():'
293 output = stream.getvalue()
291 output = stream.getvalue()
294
292
295 assert output == "%s.MyObj" % __name__
293 assert output == "%s.MyObj" % __name__
296 nt.assert_true(type_pprint_wrapper.called)
294 assert type_pprint_wrapper.called is True
297
295
298
296
299 # TODO : pytest.mark.parametrise once nose is gone.
297 # TODO : pytest.mark.parametrise once nose is gone.
@@ -478,7 +476,7 b' def test_function_pretty():'
478 return 42
476 return 42
479 return "Don't panic"
477 return "Don't panic"
480
478
481 nt.assert_in('meaning_of_life(question=None)', pretty.pretty(meaning_of_life))
479 assert "meaning_of_life(question=None)" in pretty.pretty(meaning_of_life)
482
480
483
481
484 class OrderedCounter(Counter, OrderedDict):
482 class OrderedCounter(Counter, OrderedDict):
@@ -497,6 +495,6 b' class MySet(set): # Override repr of a basic type'
497 def test_custom_repr():
495 def test_custom_repr():
498 """A custom repr should override a pretty printer for a parent type"""
496 """A custom repr should override a pretty printer for a parent type"""
499 oc = OrderedCounter("abracadabra")
497 oc = OrderedCounter("abracadabra")
500 nt.assert_in("OrderedCounter(OrderedDict", pretty.pretty(oc))
498 assert "OrderedCounter(OrderedDict" in pretty.pretty(oc)
501
499
502 assert pretty.pretty(MySet()) == "mine"
500 assert pretty.pretty(MySet()) == "mine"
@@ -14,7 +14,7 b''
14 import os
14 import os
15 import subprocess
15 import subprocess
16 import sys
16 import sys
17 import nose.tools as nt
17
18 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
18 from IPython.utils.tempdir import NamedFileInTemporaryDirectory
19 from IPython.testing.decorators import skip_win32
19 from IPython.testing.decorators import skip_win32
20 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
20 from IPython.testing import IPYTHON_TESTING_TIMEOUT_SCALE
@@ -55,12 +55,13 b' def test_ipython_embed():'
55 out, err = p.communicate(_exit)
55 out, err = p.communicate(_exit)
56 std = out.decode('UTF-8')
56 std = out.decode('UTF-8')
57
57
58 nt.assert_equal(p.returncode, 0)
58 assert p.returncode == 0
59 nt.assert_in('3 . 14', std)
59 assert "3 . 14" in std
60 if os.name != 'nt':
60 if os.name != "nt":
61 # TODO: Fix up our different stdout references, see issue gh-14
61 # TODO: Fix up our different stdout references, see issue gh-14
62 nt.assert_in('IPython', std)
62 assert "IPython" in std
63 nt.assert_in('bye!', std)
63 assert "bye!" in std
64
64
65
65 @skip_win32
66 @skip_win32
66 def test_nest_embed():
67 def test_nest_embed():
@@ -12,29 +12,42 b' from IPython.testing import tools as tt'
12 from IPython.utils.capture import capture_output
12 from IPython.utils.capture import capture_output
13
13
14 from IPython.terminal.ptutils import _elide, _adjust_completion_text_based_on_context
14 from IPython.terminal.ptutils import _elide, _adjust_completion_text_based_on_context
15 import nose.tools as nt
16
15
17 class TestElide(unittest.TestCase):
18
16
17 class TestElide(unittest.TestCase):
19 def test_elide(self):
18 def test_elide(self):
20 _elide('concatenate((a1, a2, ...), axis', '') # do not raise
19 _elide("concatenate((a1, a2, ...), axis", "") # do not raise
21 _elide('concatenate((a1, a2, ..), . axis', '') # do not raise
20 _elide("concatenate((a1, a2, ..), . axis", "") # do not raise
22 nt.assert_equal(_elide('aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh',''), 'aaaa.b…g.hhhhhh')
21 self.assertEqual(
23
22 _elide("aaaa.bbbb.ccccc.dddddd.eeeee.fffff.gggggg.hhhhhh", ""),
24 test_string = os.sep.join(['', 10*'a', 10*'b', 10*'c', ''])
23 "aaaa.b…g.hhhhhh",
25 expect_stirng = os.sep + 'a' + '\N{HORIZONTAL ELLIPSIS}' + 'b' + os.sep + 10*'c'
24 )
26 nt.assert_equal(_elide(test_string, ''), expect_stirng)
25
26 test_string = os.sep.join(["", 10 * "a", 10 * "b", 10 * "c", ""])
27 expect_stirng = (
28 os.sep + "a" + "\N{HORIZONTAL ELLIPSIS}" + "b" + os.sep + 10 * "c"
29 )
30 self.assertEqual(_elide(test_string, ""), expect_stirng)
27
31
28 def test_elide_typed_normal(self):
32 def test_elide_typed_normal(self):
29 nt.assert_equal(_elide('the quick brown fox jumped over the lazy dog', 'the quick brown fox', min_elide=10), 'the…fox jumped over the lazy dog')
33 self.assertEqual(
30
34 _elide(
35 "the quick brown fox jumped over the lazy dog",
36 "the quick brown fox",
37 min_elide=10,
38 ),
39 "the…fox jumped over the lazy dog",
40 )
31
41
32 def test_elide_typed_short_match(self):
42 def test_elide_typed_short_match(self):
33 """
43 """
34 if the match is too short we don't elide.
44 if the match is too short we don't elide.
35 avoid the "the...the"
45 avoid the "the...the"
36 """
46 """
37 nt.assert_equal(_elide('the quick brown fox jumped over the lazy dog', 'the', min_elide=10), 'the quick brown fox jumped over the lazy dog')
47 self.assertEqual(
48 _elide("the quick brown fox jumped over the lazy dog", "the", min_elide=10),
49 "the quick brown fox jumped over the lazy dog",
50 )
38
51
39 def test_elide_typed_no_match(self):
52 def test_elide_typed_no_match(self):
40 """
53 """
@@ -42,22 +55,41 b' class TestElide(unittest.TestCase):'
42 avoid the "the...the"
55 avoid the "the...the"
43 """
56 """
44 # here we typed red instead of brown
57 # here we typed red instead of brown
45 nt.assert_equal(_elide('the quick brown fox jumped over the lazy dog', 'the quick red fox', min_elide=10), 'the quick brown fox jumped over the lazy dog')
58 self.assertEqual(
59 _elide(
60 "the quick brown fox jumped over the lazy dog",
61 "the quick red fox",
62 min_elide=10,
63 ),
64 "the quick brown fox jumped over the lazy dog",
65 )
46
66
47 class TestContextAwareCompletion(unittest.TestCase):
48
67
68 class TestContextAwareCompletion(unittest.TestCase):
49 def test_adjust_completion_text_based_on_context(self):
69 def test_adjust_completion_text_based_on_context(self):
50 # Adjusted case
70 # Adjusted case
51 nt.assert_equal(_adjust_completion_text_based_on_context('arg1=', 'func1(a=)', 7), 'arg1')
71 self.assertEqual(
72 _adjust_completion_text_based_on_context("arg1=", "func1(a=)", 7), "arg1"
73 )
52
74
53 # Untouched cases
75 # Untouched cases
54 nt.assert_equal(_adjust_completion_text_based_on_context('arg1=', 'func1(a)', 7), 'arg1=')
76 self.assertEqual(
55 nt.assert_equal(_adjust_completion_text_based_on_context('arg1=', 'func1(a', 7), 'arg1=')
77 _adjust_completion_text_based_on_context("arg1=", "func1(a)", 7), "arg1="
56 nt.assert_equal(_adjust_completion_text_based_on_context('%magic', 'func1(a=)', 7), '%magic')
78 )
57 nt.assert_equal(_adjust_completion_text_based_on_context('func2', 'func1(a=)', 7), 'func2')
79 self.assertEqual(
80 _adjust_completion_text_based_on_context("arg1=", "func1(a", 7), "arg1="
81 )
82 self.assertEqual(
83 _adjust_completion_text_based_on_context("%magic", "func1(a=)", 7), "%magic"
84 )
85 self.assertEqual(
86 _adjust_completion_text_based_on_context("func2", "func1(a=)", 7), "func2"
87 )
88
58
89
59 # Decorator for interaction loop tests -----------------------------------------
90 # Decorator for interaction loop tests -----------------------------------------
60
91
92
61 class mock_input_helper(object):
93 class mock_input_helper(object):
62 """Machinery for tests of the main interact loop.
94 """Machinery for tests of the main interact loop.
63
95
@@ -6,9 +6,6 b''
6 import inspect
6 import inspect
7 import sys
7 import sys
8
8
9 # Third party
10 import nose.tools as nt
11
12 # Our own
9 # Our own
13 from IPython.testing import decorators as dec
10 from IPython.testing import decorators as dec
14 from IPython.testing.skipdoctest import skip_doctest
11 from IPython.testing.skipdoctest import skip_doctest
@@ -95,7 +92,7 b' def test_skip_dt_decorator():'
95 # Fetch the docstring from doctest_bad after decoration.
92 # Fetch the docstring from doctest_bad after decoration.
96 val = doctest_bad.__doc__
93 val = doctest_bad.__doc__
97
94
98 nt.assert_equal(check,val,"doctest_bad docstrings don't match")
95 assert check == val, "doctest_bad docstrings don't match"
99
96
100
97
101 # Doctest skipping should work for class methods too
98 # Doctest skipping should work for class methods too
@@ -156,13 +153,14 b' def test_skip_dt_decorator2():'
156
153
157 @dec.skip_linux
154 @dec.skip_linux
158 def test_linux():
155 def test_linux():
159 nt.assert_false(sys.platform.startswith('linux'),"This test can't run under linux")
156 assert sys.platform.startswith("linux") is False, "This test can't run under linux"
157
160
158
161 @dec.skip_win32
159 @dec.skip_win32
162 def test_win32():
160 def test_win32():
163 nt.assert_not_equal(sys.platform,'win32',"This test can't run under windows")
161 assert sys.platform != "win32", "This test can't run under windows"
162
164
163
165 @dec.skip_osx
164 @dec.skip_osx
166 def test_osx():
165 def test_osx():
167 nt.assert_not_equal(sys.platform,'darwin',"This test can't run under osx")
166 assert sys.platform != "darwin", "This test can't run under osx"
168
@@ -17,8 +17,6 b' Tests for testing.tools'
17 import os
17 import os
18 import unittest
18 import unittest
19
19
20 import nose.tools as nt
21
22 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
23 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
24
22
@@ -28,26 +26,26 b' from IPython.testing import tools as tt'
28
26
29 @dec.skip_win32
27 @dec.skip_win32
30 def test_full_path_posix():
28 def test_full_path_posix():
31 spath = '/foo/bar.py'
29 spath = "/foo/bar.py"
32 result = tt.full_path(spath,['a.txt','b.txt'])
30 result = tt.full_path(spath, ["a.txt", "b.txt"])
33 nt.assert_equal(result, ['/foo/a.txt', '/foo/b.txt'])
31 assert result, ["/foo/a.txt" == "/foo/b.txt"]
34 spath = '/foo'
32 spath = "/foo"
35 result = tt.full_path(spath,['a.txt','b.txt'])
33 result = tt.full_path(spath, ["a.txt", "b.txt"])
36 nt.assert_equal(result, ['/a.txt', '/b.txt'])
34 assert result, ["/a.txt" == "/b.txt"]
37 result = tt.full_path(spath,'a.txt')
35 result = tt.full_path(spath, "a.txt")
38 nt.assert_equal(result, ['/a.txt'])
36 assert result == ["/a.txt"]
39
37
40
38
41 @dec.skip_if_not_win32
39 @dec.skip_if_not_win32
42 def test_full_path_win32():
40 def test_full_path_win32():
43 spath = 'c:\\foo\\bar.py'
41 spath = "c:\\foo\\bar.py"
44 result = tt.full_path(spath,['a.txt','b.txt'])
42 result = tt.full_path(spath, ["a.txt", "b.txt"])
45 nt.assert_equal(result, ['c:\\foo\\a.txt', 'c:\\foo\\b.txt'])
43 assert result, ["c:\\foo\\a.txt" == "c:\\foo\\b.txt"]
46 spath = 'c:\\foo'
44 spath = "c:\\foo"
47 result = tt.full_path(spath,['a.txt','b.txt'])
45 result = tt.full_path(spath, ["a.txt", "b.txt"])
48 nt.assert_equal(result, ['c:\\a.txt', 'c:\\b.txt'])
46 assert result, ["c:\\a.txt" == "c:\\b.txt"]
49 result = tt.full_path(spath,'a.txt')
47 result = tt.full_path(spath, "a.txt")
50 nt.assert_equal(result, ['c:\\a.txt'])
48 assert result == ["c:\\a.txt"]
51
49
52
50
53 def test_parser():
51 def test_parser():
@@ -56,8 +54,8 b' def test_parser():'
56 both = ("FAILED (errors=1, failures=1)", 1, 1)
54 both = ("FAILED (errors=1, failures=1)", 1, 1)
57 for txt, nerr, nfail in [err, fail, both]:
55 for txt, nerr, nfail in [err, fail, both]:
58 nerr1, nfail1 = tt.parse_test_output(txt)
56 nerr1, nfail1 = tt.parse_test_output(txt)
59 nt.assert_equal(nerr, nerr1)
57 assert nerr == nerr1
60 nt.assert_equal(nfail, nfail1)
58 assert nfail == nfail1
61
59
62
60
63 def test_temp_pyfile():
61 def test_temp_pyfile():
@@ -66,7 +64,7 b' def test_temp_pyfile():'
66 assert os.path.isfile(fname)
64 assert os.path.isfile(fname)
67 with open(fname) as fh2:
65 with open(fname) as fh2:
68 src2 = fh2.read()
66 src2 = fh2.read()
69 nt.assert_equal(src2, src)
67 assert src2 == src
70
68
71 class TestAssertPrints(unittest.TestCase):
69 class TestAssertPrints(unittest.TestCase):
72 def test_passing(self):
70 def test_passing(self):
@@ -1,6 +1,7 b''
1 import nose.tools as nt
2 from IPython.utils.dir2 import dir2
1 from IPython.utils.dir2 import dir2
3
2
3 import pytest
4
4
5
5 class Base(object):
6 class Base(object):
6 x = 1
7 x = 1
@@ -9,12 +10,13 b' class Base(object):'
9
10
10 def test_base():
11 def test_base():
11 res = dir2(Base())
12 res = dir2(Base())
12 assert ('x' in res)
13 assert "x" in res
13 assert ('z' in res)
14 assert "z" in res
14 assert ('y' not in res)
15 assert "y" not in res
15 assert ('__class__' in res)
16 assert "__class__" in res
16 nt.assert_equal(res.count('x'), 1)
17 assert res.count("x") == 1
17 nt.assert_equal(res.count('__class__'), 1)
18 assert res.count("__class__") == 1
19
18
20
19 def test_SubClass():
21 def test_SubClass():
20
22
@@ -22,9 +24,9 b' def test_SubClass():'
22 y = 2
24 y = 2
23
25
24 res = dir2(SubClass())
26 res = dir2(SubClass())
25 assert ('y' in res)
27 assert "y" in res
26 nt.assert_equal(res.count('y'), 1)
28 assert res.count("y") == 1
27 nt.assert_equal(res.count('x'), 1)
29 assert res.count("x") == 1
28
30
29
31
30 def test_SubClass_with_trait_names_attr():
32 def test_SubClass_with_trait_names_attr():
@@ -35,24 +37,31 b' def test_SubClass_with_trait_names_attr():'
35 trait_names = 44
37 trait_names = 44
36
38
37 res = dir2(SubClass())
39 res = dir2(SubClass())
38 assert('trait_names' in res)
40 assert "trait_names" in res
39
41
40
42
41 def test_misbehaving_object_without_trait_names():
43 def test_misbehaving_object_without_trait_names():
42 # dir2 shouldn't raise even when objects are dumb and raise
44 # dir2 shouldn't raise even when objects are dumb and raise
43 # something other than AttribteErrors on bad getattr.
45 # something other than AttribteErrors on bad getattr.
44
46
45 class MisbehavingGetattr(object):
47 class MisbehavingGetattr:
46 def __getattr__(self):
48 def __getattr__(self, attr):
47 raise KeyError("I should be caught")
49 raise KeyError("I should be caught")
48
50
49 def some_method(self):
51 def some_method(self):
50 pass
52 return True
51
53
52 class SillierWithDir(MisbehavingGetattr):
54 class SillierWithDir(MisbehavingGetattr):
53 def __dir__(self):
55 def __dir__(self):
54 return ['some_method']
56 return ['some_method']
55
57
56 for bad_klass in (MisbehavingGetattr, SillierWithDir):
58 for bad_klass in (MisbehavingGetattr, SillierWithDir):
57 res = dir2(bad_klass())
59 obj = bad_klass()
58 assert('some_method' in res)
60
61 assert obj.some_method()
62
63 with pytest.raises(KeyError):
64 obj.other_method()
65
66 res = dir2(obj)
67 assert "some_method" in res
@@ -11,7 +11,7 b''
11 # Imports
11 # Imports
12 #-----------------------------------------------------------------------------
12 #-----------------------------------------------------------------------------
13
13
14 import nose.tools as nt
14 import pytest
15
15
16 from IPython.utils.importstring import import_item
16 from IPython.utils.importstring import import_item
17
17
@@ -22,18 +22,19 b' from IPython.utils.importstring import import_item'
22 def test_import_plain():
22 def test_import_plain():
23 "Test simple imports"
23 "Test simple imports"
24 import os
24 import os
25 os2 = import_item('os')
25
26 nt.assert_true(os is os2)
26 os2 = import_item("os")
27 assert os is os2
27
28
28
29
29 def test_import_nested():
30 def test_import_nested():
30 "Test nested imports from the stdlib"
31 "Test nested imports from the stdlib"
31 from os import path
32 from os import path
32 path2 = import_item('os.path')
33
33 nt.assert_true(path is path2)
34 path2 = import_item("os.path")
35 assert path is path2
34
36
35
37
36 def test_import_raises():
38 def test_import_raises():
37 "Test that failing imports raise the right exception"
39 "Test that failing imports raise the right exception"
38 nt.assert_raises(ImportError, import_item, 'IPython.foobar')
40 pytest.raises(ImportError, import_item, "IPython.foobar")
39
@@ -11,8 +11,6 b' from io import StringIO'
11 from subprocess import Popen, PIPE
11 from subprocess import Popen, PIPE
12 import unittest
12 import unittest
13
13
14 import nose.tools as nt
15
16 from IPython.utils.io import IOStream, Tee, capture_output
14 from IPython.utils.io import IOStream, Tee, capture_output
17
15
18
16
@@ -22,7 +20,7 b' def test_tee_simple():'
22 text = 'Hello'
20 text = 'Hello'
23 tee = Tee(chan, channel='stdout')
21 tee = Tee(chan, channel='stdout')
24 print(text, file=chan)
22 print(text, file=chan)
25 nt.assert_equal(chan.getvalue(), text+"\n")
23 assert chan.getvalue() == text + "\n"
26
24
27
25
28 class TeeTestCase(unittest.TestCase):
26 class TeeTestCase(unittest.TestCase):
@@ -39,7 +37,7 b' class TeeTestCase(unittest.TestCase):'
39
37
40 print(text, end='', file=chan)
38 print(text, end='', file=chan)
41 trap_val = trap.getvalue()
39 trap_val = trap.getvalue()
42 nt.assert_equal(chan.getvalue(), text)
40 self.assertEqual(chan.getvalue(), text)
43
41
44 tee.close()
42 tee.close()
45
43
@@ -82,8 +80,8 b' class TestIOStream(unittest.TestCase):'
82 """capture_output() context works"""
80 """capture_output() context works"""
83
81
84 with capture_output() as io:
82 with capture_output() as io:
85 print('hi, stdout')
83 print("hi, stdout")
86 print('hi, stderr', file=sys.stderr)
84 print("hi, stderr", file=sys.stderr)
87
85
88 nt.assert_equal(io.stdout, 'hi, stdout\n')
86 self.assertEqual(io.stdout, "hi, stdout\n")
89 nt.assert_equal(io.stderr, 'hi, stderr\n')
87 self.assertEqual(io.stderr, "hi, stderr\n")
@@ -22,8 +22,6 b' from IPython.testing.tools import make_tempfile'
22
22
23 import IPython.utils.module_paths as mp
23 import IPython.utils.module_paths as mp
24
24
25 import nose.tools as nt
26
27 TEST_FILE_PATH = Path(__file__).resolve().parent
25 TEST_FILE_PATH = Path(__file__).resolve().parent
28
26
29 TMP_TEST_DIR = Path(tempfile.mkdtemp(suffix="with.dot"))
27 TMP_TEST_DIR = Path(tempfile.mkdtemp(suffix="with.dot"))
@@ -67,7 +65,7 b' def test_tempdir():'
67 """
65 """
68 Ensure the test are done with a temporary file that have a dot somewhere.
66 Ensure the test are done with a temporary file that have a dot somewhere.
69 """
67 """
70 nt.assert_in(".", str(TMP_TEST_DIR))
68 assert "." in str(TMP_TEST_DIR)
71
69
72
70
73 def test_find_mod_1():
71 def test_find_mod_1():
@@ -76,7 +74,7 b' def test_find_mod_1():'
76 Expected output: a path to that directory's __init__.py file.
74 Expected output: a path to that directory's __init__.py file.
77 """
75 """
78 modpath = TMP_TEST_DIR / "xmod" / "__init__.py"
76 modpath = TMP_TEST_DIR / "xmod" / "__init__.py"
79 nt.assert_equal(Path(mp.find_mod("xmod")), modpath)
77 assert Path(mp.find_mod("xmod")) == modpath
80
78
81 def test_find_mod_2():
79 def test_find_mod_2():
82 """
80 """
@@ -85,7 +83,7 b' def test_find_mod_2():'
85 TODO: Confirm why this is a duplicate test.
83 TODO: Confirm why this is a duplicate test.
86 """
84 """
87 modpath = TMP_TEST_DIR / "xmod" / "__init__.py"
85 modpath = TMP_TEST_DIR / "xmod" / "__init__.py"
88 nt.assert_equal(Path(mp.find_mod("xmod")), modpath)
86 assert Path(mp.find_mod("xmod")) == modpath
89
87
90 def test_find_mod_3():
88 def test_find_mod_3():
91 """
89 """
@@ -93,7 +91,7 b' def test_find_mod_3():'
93 Expected output: full path with .py extension.
91 Expected output: full path with .py extension.
94 """
92 """
95 modpath = TMP_TEST_DIR / "xmod" / "sub.py"
93 modpath = TMP_TEST_DIR / "xmod" / "sub.py"
96 nt.assert_equal(Path(mp.find_mod("xmod.sub")), modpath)
94 assert Path(mp.find_mod("xmod.sub")) == modpath
97
95
98 def test_find_mod_4():
96 def test_find_mod_4():
99 """
97 """
@@ -101,11 +99,11 b' def test_find_mod_4():'
101 Expected output: full path with .py extension
99 Expected output: full path with .py extension
102 """
100 """
103 modpath = TMP_TEST_DIR / "pack.py"
101 modpath = TMP_TEST_DIR / "pack.py"
104 nt.assert_equal(Path(mp.find_mod("pack")), modpath)
102 assert Path(mp.find_mod("pack")) == modpath
105
103
106 def test_find_mod_5():
104 def test_find_mod_5():
107 """
105 """
108 Search for a filename with a .pyc extension
106 Search for a filename with a .pyc extension
109 Expected output: TODO: do we exclude or include .pyc files?
107 Expected output: TODO: do we exclude or include .pyc files?
110 """
108 """
111 nt.assert_equal(mp.find_mod("packpyc"), None)
109 assert mp.find_mod("packpyc") == None
@@ -1,6 +1,5 b''
1 import io
1 import io
2 import os.path
2 import os.path
3 import nose.tools as nt
4
3
5 from IPython.utils import openpy
4 from IPython.utils import openpy
6
5
@@ -11,14 +10,14 b' nonascii_path = os.path.join(mydir, "../../core/tests/nonascii.py")'
11 def test_detect_encoding():
10 def test_detect_encoding():
12 with open(nonascii_path, "rb") as f:
11 with open(nonascii_path, "rb") as f:
13 enc, lines = openpy.detect_encoding(f.readline)
12 enc, lines = openpy.detect_encoding(f.readline)
14 nt.assert_equal(enc, "iso-8859-5")
13 assert enc == "iso-8859-5"
15
14
16
15
17 def test_read_file():
16 def test_read_file():
18 with io.open(nonascii_path, encoding="iso-8859-5") as f:
17 with io.open(nonascii_path, encoding="iso-8859-5") as f:
19 read_specified_enc = f.read()
18 read_specified_enc = f.read()
20 read_detected_enc = openpy.read_py_file(nonascii_path, skip_encoding_cookie=False)
19 read_detected_enc = openpy.read_py_file(nonascii_path, skip_encoding_cookie=False)
21 nt.assert_equal(read_detected_enc, read_specified_enc)
20 assert read_detected_enc == read_specified_enc
22 assert "coding: iso-8859-5" in read_detected_enc
21 assert "coding: iso-8859-5" in read_detected_enc
23
22
24 read_strip_enc_cookie = openpy.read_py_file(
23 read_strip_enc_cookie = openpy.read_py_file(
@@ -30,10 +29,10 b' def test_read_file():'
30 def test_source_to_unicode():
29 def test_source_to_unicode():
31 with io.open(nonascii_path, "rb") as f:
30 with io.open(nonascii_path, "rb") as f:
32 source_bytes = f.read()
31 source_bytes = f.read()
33 nt.assert_equal(
32 assert (
34 openpy.source_to_unicode(source_bytes, skip_encoding_cookie=False).splitlines(),
33 openpy.source_to_unicode(source_bytes, skip_encoding_cookie=False).splitlines()
35 source_bytes.decode("iso-8859-5").splitlines(),
34 == source_bytes.decode("iso-8859-5").splitlines()
36 )
35 )
37
36
38 source_no_cookie = openpy.source_to_unicode(source_bytes, skip_encoding_cookie=True)
37 source_no_cookie = openpy.source_to_unicode(source_bytes, skip_encoding_cookie=True)
39 nt.assert_not_in("coding: iso-8859-5", source_no_cookie)
38 assert "coding: iso-8859-5" not in source_no_cookie
@@ -15,7 +15,7 b' from os.path import join, abspath'
15 from imp import reload
15 from imp import reload
16
16
17 from nose import SkipTest, with_setup
17 from nose import SkipTest, with_setup
18 import nose.tools as nt
18 import pytest
19
19
20 import IPython
20 import IPython
21 from IPython import paths
21 from IPython import paths
@@ -155,7 +155,7 b' def test_get_home_dir_5():'
155 env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
155 env['HOME'] = abspath(HOME_TEST_DIR+'garbage')
156 # set os.name = posix, to prevent My Documents fallback on Windows
156 # set os.name = posix, to prevent My Documents fallback on Windows
157 os.name = 'posix'
157 os.name = 'posix'
158 nt.assert_raises(path.HomeDirError, path.get_home_dir, True)
158 pytest.raises(path.HomeDirError, path.get_home_dir, True)
159
159
160 # Should we stub wreg fully so we can run the test on all platforms?
160 # Should we stub wreg fully so we can run the test on all platforms?
161 @skip_if_not_win32
161 @skip_if_not_win32
@@ -237,8 +237,7 b' def test_get_xdg_dir_3():'
237 env.pop('IPYTHONDIR', None)
237 env.pop('IPYTHONDIR', None)
238 env.pop('XDG_CONFIG_HOME', None)
238 env.pop('XDG_CONFIG_HOME', None)
239 cfgdir=os.path.join(path.get_home_dir(), '.config')
239 cfgdir=os.path.join(path.get_home_dir(), '.config')
240 if not os.path.exists(cfgdir):
240 os.makedirs(cfgdir, exist_ok=True)
241 os.makedirs(cfgdir)
242
241
243 assert path.get_xdg_dir() is None
242 assert path.get_xdg_dir() is None
244
243
@@ -305,15 +304,15 b' def test_get_py_filename():'
305 assert path.get_py_filename("foo") == "foo.py"
304 assert path.get_py_filename("foo") == "foo.py"
306 with make_tempfile("foo"):
305 with make_tempfile("foo"):
307 assert path.get_py_filename("foo") == "foo"
306 assert path.get_py_filename("foo") == "foo"
308 nt.assert_raises(IOError, path.get_py_filename, "foo.py")
307 pytest.raises(IOError, path.get_py_filename, "foo.py")
309 nt.assert_raises(IOError, path.get_py_filename, "foo")
308 pytest.raises(IOError, path.get_py_filename, "foo")
310 nt.assert_raises(IOError, path.get_py_filename, "foo.py")
309 pytest.raises(IOError, path.get_py_filename, "foo.py")
311 true_fn = "foo with spaces.py"
310 true_fn = "foo with spaces.py"
312 with make_tempfile(true_fn):
311 with make_tempfile(true_fn):
313 assert path.get_py_filename("foo with spaces") == true_fn
312 assert path.get_py_filename("foo with spaces") == true_fn
314 assert path.get_py_filename("foo with spaces.py") == true_fn
313 assert path.get_py_filename("foo with spaces.py") == true_fn
315 nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"')
314 pytest.raises(IOError, path.get_py_filename, '"foo with spaces.py"')
316 nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'")
315 pytest.raises(IOError, path.get_py_filename, "'foo with spaces.py'")
317
316
318 @onlyif_unicode_paths
317 @onlyif_unicode_paths
319 def test_unicode_in_filename():
318 def test_unicode_in_filename():
@@ -414,7 +413,7 b' def test_ensure_dir_exists():'
414 path.ensure_dir_exists(d) # no-op
413 path.ensure_dir_exists(d) # no-op
415 f = os.path.join(td, 'ƒile')
414 f = os.path.join(td, 'ƒile')
416 open(f, 'w').close() # touch
415 open(f, 'w').close() # touch
417 with nt.assert_raises(IOError):
416 with pytest.raises(IOError):
418 path.ensure_dir_exists(f)
417 path.ensure_dir_exists(f)
419
418
420 class TestLinkOrCopy(unittest.TestCase):
419 class TestLinkOrCopy(unittest.TestCase):
@@ -20,9 +20,8 b' import os'
20 import time
20 import time
21 from _thread import interrupt_main # Py 3
21 from _thread import interrupt_main # Py 3
22 import threading
22 import threading
23 from unittest import SkipTest
24
23
25 import nose.tools as nt
24 import pytest
26
25
27 from IPython.utils.process import (find_cmd, FindCmdError, arg_split,
26 from IPython.utils.process import (find_cmd, FindCmdError, arg_split,
28 system, getoutput, getoutputerror,
27 system, getoutput, getoutputerror,
@@ -41,8 +40,8 b' python = os.path.basename(sys.executable)'
41 @dec.skip_win32
40 @dec.skip_win32
42 def test_find_cmd_ls():
41 def test_find_cmd_ls():
43 """Make sure we can find the full path to ls."""
42 """Make sure we can find the full path to ls."""
44 path = find_cmd('ls')
43 path = find_cmd("ls")
45 nt.assert_true(path.endswith('ls'))
44 assert path.endswith("ls")
46
45
47
46
48 def has_pywin32():
47 def has_pywin32():
@@ -64,7 +63,7 b' def test_find_cmd_pythonw():'
64 "This test runs on posix or in win32 with win32api installed")
63 "This test runs on posix or in win32 with win32api installed")
65 def test_find_cmd_fail():
64 def test_find_cmd_fail():
66 """Make sure that FindCmdError is raised if we can't find the cmd."""
65 """Make sure that FindCmdError is raised if we can't find the cmd."""
67 nt.assert_raises(FindCmdError,find_cmd,'asdfasdf')
66 pytest.raises(FindCmdError, find_cmd, "asdfasdf")
68
67
69
68
70 # TODO: move to pytest.mark.parametrize once nose gone
69 # TODO: move to pytest.mark.parametrize once nose gone
@@ -121,7 +120,7 b' class SubProcessTestCase(tt.TempFileMixin):'
121 Interrupt a subprocess after a second.
120 Interrupt a subprocess after a second.
122 """
121 """
123 if threading.main_thread() != threading.current_thread():
122 if threading.main_thread() != threading.current_thread():
124 raise nt.SkipTest("Can't run this test if not in main thread.")
123 raise pytest.skip("Can't run this test if not in main thread.")
125
124
126 # Some tests can overwrite SIGINT handler (by using pdb for example),
125 # Some tests can overwrite SIGINT handler (by using pdb for example),
127 # which then breaks this test, so just make sure it's operating
126 # which then breaks this test, so just make sure it's operating
@@ -17,9 +17,6 b' Authors'
17 # Imports
17 # Imports
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 # third party
21 import nose.tools as nt
22
23 from IPython.testing.decorators import skip_iptest_but_not_pytest
20 from IPython.testing.decorators import skip_iptest_but_not_pytest
24
21
25 # our own
22 # our own
@@ -65,7 +62,7 b' def test_parse_sample(style):'
65 buf.seek(0)
62 buf.seek(0)
66 f1 = buf.read()
63 f1 = buf.read()
67
64
68 nt.assert_not_in("ERROR", f1)
65 assert "ERROR" not in f1
69
66
70
67
71 @skip_iptest_but_not_pytest
68 @skip_iptest_but_not_pytest
@@ -73,4 +70,4 b' def test_parse_error(style):'
73 p = Parser(style=style)
70 p = Parser(style=style)
74 f1 = p.format(")", "str")
71 f1 = p.format(")", "str")
75 if style != "NoColor":
72 if style != "NoColor":
76 nt.assert_in("ERROR", f1)
73 assert "ERROR" in f1
@@ -5,7 +5,6 b''
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 import json
7 import json
8 import nose.tools as nt
9
8
10 from IPython.utils import sysinfo
9 from IPython.utils import sysinfo
11
10
@@ -17,9 +17,10 b' import math'
17 import random
17 import random
18 import sys
18 import sys
19
19
20 import nose.tools as nt
21 from pathlib import Path
20 from pathlib import Path
22
21
22 import pytest
23
23 from IPython.utils import text
24 from IPython.utils import text
24
25
25 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
@@ -117,7 +118,8 b' def eval_formatter_check(f):'
117 # This decodes in a platform dependent manner, but it shouldn't error out
118 # This decodes in a platform dependent manner, but it shouldn't error out
118 s = f.format("{b}", **ns)
119 s = f.format("{b}", **ns)
119
120
120 nt.assert_raises(NameError, f.format, '{dne}', **ns)
121 pytest.raises(NameError, f.format, "{dne}", **ns)
122
121
123
122 def eval_formatter_slicing_check(f):
124 def eval_formatter_slicing_check(f):
123 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
125 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
@@ -128,7 +130,7 b' def eval_formatter_slicing_check(f):'
128 s = f.format("{stuff[::2]}", **ns)
130 s = f.format("{stuff[::2]}", **ns)
129 assert s == ns["stuff"][::2]
131 assert s == ns["stuff"][::2]
130
132
131 nt.assert_raises(SyntaxError, f.format, "{n:x}", **ns)
133 pytest.raises(SyntaxError, f.format, "{n:x}", **ns)
132
134
133 def eval_formatter_no_slicing_check(f):
135 def eval_formatter_no_slicing_check(f):
134 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
136 ns = dict(n=12, pi=math.pi, stuff='hello there', os=os)
@@ -194,7 +196,7 b' def test_LSString():'
194 assert lss.l == ["abc", "def"]
196 assert lss.l == ["abc", "def"]
195 assert lss.s == "abc def"
197 assert lss.s == "abc def"
196 lss = text.LSString(os.getcwd())
198 lss = text.LSString(os.getcwd())
197 nt.assert_is_instance(lss.p[0], Path)
199 assert isinstance(lss.p[0], Path)
198
200
199 def test_SList():
201 def test_SList():
200 sl = text.SList(["a 11", "b 1", "a 2"])
202 sl = text.SList(["a 11", "b 1", "a 2"])
@@ -2,7 +2,6 b''
2 # Copyright (c) IPython Development Team.
2 # Copyright (c) IPython Development Team.
3 # Distributed under the terms of the Modified BSD License.
3 # Distributed under the terms of the Modified BSD License.
4
4
5 import nose.tools as nt
6 import pytest
5 import pytest
7 from IPython.testing.decorators import skip_iptest_but_not_pytest
6 from IPython.testing.decorators import skip_iptest_but_not_pytest
8
7
@@ -17,12 +16,15 b' def expect_token(expected, cell, cursor_pos):'
17 else:
16 else:
18 offset += len(line)+1
17 offset += len(line)+1
19 column = cursor_pos - offset
18 column = cursor_pos - offset
20 line_with_cursor = '%s|%s' % (line[:column], line[column:])
19 line_with_cursor = "%s|%s" % (line[:column], line[column:])
21 nt.assert_equal(token, expected,
20 assert token == expected, "Expected %r, got %r in: %r (pos %i)" % (
22 "Expected %r, got %r in: %r (pos %i)" % (
21 expected,
23 expected, token, line_with_cursor, cursor_pos)
22 token,
23 line_with_cursor,
24 cursor_pos,
24 )
25 )
25
26
27
26 def test_simple():
28 def test_simple():
27 cell = "foo"
29 cell = "foo"
28 for i in range(len(cell)):
30 for i in range(len(cell)):
@@ -107,20 +109,20 b' def test_attrs():'
107 def test_line_at_cursor():
109 def test_line_at_cursor():
108 cell = ""
110 cell = ""
109 (line, offset) = line_at_cursor(cell, cursor_pos=11)
111 (line, offset) = line_at_cursor(cell, cursor_pos=11)
110 nt.assert_equal(line, "")
112 assert line == ""
111 nt.assert_equal(offset, 0)
113 assert offset == 0
112
114
113 # The position after a newline should be the start of the following line.
115 # The position after a newline should be the start of the following line.
114 cell = "One\nTwo\n"
116 cell = "One\nTwo\n"
115 (line, offset) = line_at_cursor(cell, cursor_pos=4)
117 (line, offset) = line_at_cursor(cell, cursor_pos=4)
116 nt.assert_equal(line, "Two\n")
118 assert line == "Two\n"
117 nt.assert_equal(offset, 4)
119 assert offset == 4
118
120
119 # The end of a cell should be on the last line
121 # The end of a cell should be on the last line
120 cell = "pri\npri"
122 cell = "pri\npri"
121 (line, offset) = line_at_cursor(cell, cursor_pos=7)
123 (line, offset) = line_at_cursor(cell, cursor_pos=7)
122 nt.assert_equal(line, "pri")
124 assert line == "pri"
123 nt.assert_equal(offset, 4)
125 assert offset == 4
124
126
125
127
126 @pytest.mark.parametrize(
128 @pytest.mark.parametrize(
@@ -8,6 +8,7 b' include pytest.ini'
8 include mypy.ini
8 include mypy.ini
9 include .mailmap
9 include .mailmap
10 include .flake8
10 include .flake8
11 include .pre-commit-config.yaml
11
12
12 recursive-exclude tools *
13 recursive-exclude tools *
13 exclude tools
14 exclude tools
@@ -176,6 +176,7 b' extras_require = dict('
176 doc=["Sphinx>=1.3"],
176 doc=["Sphinx>=1.3"],
177 test=[
177 test=[
178 "nose>=0.10.1",
178 "nose>=0.10.1",
179 "pytest",
179 "requests",
180 "requests",
180 "testpath",
181 "testpath",
181 "pygments",
182 "pygments",
General Comments 0
You need to be logged in to leave comments. Login now