##// END OF EJS Templates
Fix tests in IPython.core
Thomas Kluyver -
Show More
@@ -1,135 +1,135
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """
2 """
3 Color schemes for exception handling code in IPython.
3 Color schemes for exception handling code in IPython.
4 """
4 """
5
5
6 #*****************************************************************************
6 #*****************************************************************************
7 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
7 # Copyright (C) 2005-2006 Fernando Perez <fperez@colorado.edu>
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #*****************************************************************************
11 #*****************************************************************************
12
12
13 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
13 from IPython.utils.coloransi import ColorSchemeTable, TermColors, ColorScheme
14
14
15 def exception_colors():
15 def exception_colors():
16 """Return a color table with fields for exception reporting.
16 """Return a color table with fields for exception reporting.
17
17
18 The table is an instance of ColorSchemeTable with schemes added for
18 The table is an instance of ColorSchemeTable with schemes added for
19 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
19 'Linux', 'LightBG' and 'NoColor' and fields for exception handling filled
20 in.
20 in.
21
21
22 Examples:
22 Examples:
23
23
24 >>> ec = exception_colors()
24 >>> ec = exception_colors()
25 >>> ec.active_scheme_name
25 >>> ec.active_scheme_name
26 ''
26 ''
27 >>> print ec.active_colors
27 >>> print(ec.active_colors)
28 None
28 None
29
29
30 Now we activate a color scheme:
30 Now we activate a color scheme:
31 >>> ec.set_active_scheme('NoColor')
31 >>> ec.set_active_scheme('NoColor')
32 >>> ec.active_scheme_name
32 >>> ec.active_scheme_name
33 'NoColor'
33 'NoColor'
34 >>> sorted(ec.active_colors.keys())
34 >>> sorted(ec.active_colors.keys())
35 ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
35 ['Normal', 'caret', 'em', 'excName', 'filename', 'filenameEm', 'line',
36 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
36 'lineno', 'linenoEm', 'name', 'nameEm', 'normalEm', 'topline', 'vName',
37 'val', 'valEm']
37 'val', 'valEm']
38 """
38 """
39
39
40 ex_colors = ColorSchemeTable()
40 ex_colors = ColorSchemeTable()
41
41
42 # Populate it with color schemes
42 # Populate it with color schemes
43 C = TermColors # shorthand and local lookup
43 C = TermColors # shorthand and local lookup
44 ex_colors.add_scheme(ColorScheme(
44 ex_colors.add_scheme(ColorScheme(
45 'NoColor',
45 'NoColor',
46 # The color to be used for the top line
46 # The color to be used for the top line
47 topline = C.NoColor,
47 topline = C.NoColor,
48
48
49 # The colors to be used in the traceback
49 # The colors to be used in the traceback
50 filename = C.NoColor,
50 filename = C.NoColor,
51 lineno = C.NoColor,
51 lineno = C.NoColor,
52 name = C.NoColor,
52 name = C.NoColor,
53 vName = C.NoColor,
53 vName = C.NoColor,
54 val = C.NoColor,
54 val = C.NoColor,
55 em = C.NoColor,
55 em = C.NoColor,
56
56
57 # Emphasized colors for the last frame of the traceback
57 # Emphasized colors for the last frame of the traceback
58 normalEm = C.NoColor,
58 normalEm = C.NoColor,
59 filenameEm = C.NoColor,
59 filenameEm = C.NoColor,
60 linenoEm = C.NoColor,
60 linenoEm = C.NoColor,
61 nameEm = C.NoColor,
61 nameEm = C.NoColor,
62 valEm = C.NoColor,
62 valEm = C.NoColor,
63
63
64 # Colors for printing the exception
64 # Colors for printing the exception
65 excName = C.NoColor,
65 excName = C.NoColor,
66 line = C.NoColor,
66 line = C.NoColor,
67 caret = C.NoColor,
67 caret = C.NoColor,
68 Normal = C.NoColor
68 Normal = C.NoColor
69 ))
69 ))
70
70
71 # make some schemes as instances so we can copy them for modification easily
71 # make some schemes as instances so we can copy them for modification easily
72 ex_colors.add_scheme(ColorScheme(
72 ex_colors.add_scheme(ColorScheme(
73 'Linux',
73 'Linux',
74 # The color to be used for the top line
74 # The color to be used for the top line
75 topline = C.LightRed,
75 topline = C.LightRed,
76
76
77 # The colors to be used in the traceback
77 # The colors to be used in the traceback
78 filename = C.Green,
78 filename = C.Green,
79 lineno = C.Green,
79 lineno = C.Green,
80 name = C.Purple,
80 name = C.Purple,
81 vName = C.Cyan,
81 vName = C.Cyan,
82 val = C.Green,
82 val = C.Green,
83 em = C.LightCyan,
83 em = C.LightCyan,
84
84
85 # Emphasized colors for the last frame of the traceback
85 # Emphasized colors for the last frame of the traceback
86 normalEm = C.LightCyan,
86 normalEm = C.LightCyan,
87 filenameEm = C.LightGreen,
87 filenameEm = C.LightGreen,
88 linenoEm = C.LightGreen,
88 linenoEm = C.LightGreen,
89 nameEm = C.LightPurple,
89 nameEm = C.LightPurple,
90 valEm = C.LightBlue,
90 valEm = C.LightBlue,
91
91
92 # Colors for printing the exception
92 # Colors for printing the exception
93 excName = C.LightRed,
93 excName = C.LightRed,
94 line = C.Yellow,
94 line = C.Yellow,
95 caret = C.White,
95 caret = C.White,
96 Normal = C.Normal
96 Normal = C.Normal
97 ))
97 ))
98
98
99 # For light backgrounds, swap dark/light colors
99 # For light backgrounds, swap dark/light colors
100 ex_colors.add_scheme(ColorScheme(
100 ex_colors.add_scheme(ColorScheme(
101 'LightBG',
101 'LightBG',
102 # The color to be used for the top line
102 # The color to be used for the top line
103 topline = C.Red,
103 topline = C.Red,
104
104
105 # The colors to be used in the traceback
105 # The colors to be used in the traceback
106 filename = C.LightGreen,
106 filename = C.LightGreen,
107 lineno = C.LightGreen,
107 lineno = C.LightGreen,
108 name = C.LightPurple,
108 name = C.LightPurple,
109 vName = C.Cyan,
109 vName = C.Cyan,
110 val = C.LightGreen,
110 val = C.LightGreen,
111 em = C.Cyan,
111 em = C.Cyan,
112
112
113 # Emphasized colors for the last frame of the traceback
113 # Emphasized colors for the last frame of the traceback
114 normalEm = C.Cyan,
114 normalEm = C.Cyan,
115 filenameEm = C.Green,
115 filenameEm = C.Green,
116 linenoEm = C.Green,
116 linenoEm = C.Green,
117 nameEm = C.Purple,
117 nameEm = C.Purple,
118 valEm = C.Blue,
118 valEm = C.Blue,
119
119
120 # Colors for printing the exception
120 # Colors for printing the exception
121 excName = C.Red,
121 excName = C.Red,
122 #line = C.Brown, # brown often is displayed as yellow
122 #line = C.Brown, # brown often is displayed as yellow
123 line = C.Red,
123 line = C.Red,
124 caret = C.Normal,
124 caret = C.Normal,
125 Normal = C.Normal,
125 Normal = C.Normal,
126 ))
126 ))
127
127
128 return ex_colors
128 return ex_colors
129
129
130
130
131 # For backwards compatibility, keep around a single global object. Note that
131 # For backwards compatibility, keep around a single global object. Note that
132 # this should NOT be used, the factory function should be used instead, since
132 # this should NOT be used, the factory function should be used instead, since
133 # these objects are stateful and it's very easy to get strange bugs if any code
133 # these objects are stateful and it's very easy to get strange bugs if any code
134 # modifies the module-level object's state.
134 # modifies the module-level object's state.
135 ExceptionColors = exception_colors()
135 ExceptionColors = exception_colors()
@@ -1,183 +1,183
1 # coding: utf-8
1 # coding: utf-8
2 """Tests for the IPython tab-completion machinery.
2 """Tests for the IPython tab-completion machinery.
3 """
3 """
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Module imports
5 # Module imports
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7
7
8 # stdlib
8 # stdlib
9 import os
9 import os
10 import sys
10 import sys
11 import tempfile
11 import tempfile
12 from datetime import datetime
12 from datetime import datetime
13
13
14 # third party
14 # third party
15 import nose.tools as nt
15 import nose.tools as nt
16
16
17 # our own packages
17 # our own packages
18 from IPython.config.loader import Config
18 from IPython.config.loader import Config
19 from IPython.utils.tempdir import TemporaryDirectory
19 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.core.history import HistoryManager, extract_hist_ranges
20 from IPython.core.history import HistoryManager, extract_hist_ranges
21 from IPython.utils import py3compat
21 from IPython.utils import py3compat
22
22
23 def setUp():
23 def setUp():
24 nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
24 nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
25
25
26 def test_history():
26 def test_history():
27 ip = get_ipython()
27 ip = get_ipython()
28 with TemporaryDirectory() as tmpdir:
28 with TemporaryDirectory() as tmpdir:
29 hist_manager_ori = ip.history_manager
29 hist_manager_ori = ip.history_manager
30 hist_file = os.path.join(tmpdir, 'history.sqlite')
30 hist_file = os.path.join(tmpdir, 'history.sqlite')
31 try:
31 try:
32 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
32 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
33 hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='β‚¬Γ†ΒΎΓ·ΓŸ'"]
33 hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='β‚¬Γ†ΒΎΓ·ΓŸ'"]
34 for i, h in enumerate(hist, start=1):
34 for i, h in enumerate(hist, start=1):
35 ip.history_manager.store_inputs(i, h)
35 ip.history_manager.store_inputs(i, h)
36
36
37 ip.history_manager.db_log_output = True
37 ip.history_manager.db_log_output = True
38 # Doesn't match the input, but we'll just check it's stored.
38 # Doesn't match the input, but we'll just check it's stored.
39 ip.history_manager.output_hist_reprs[3] = "spam"
39 ip.history_manager.output_hist_reprs[3] = "spam"
40 ip.history_manager.store_output(3)
40 ip.history_manager.store_output(3)
41
41
42 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
42 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
43
43
44 # Detailed tests for _get_range_session
44 # Detailed tests for _get_range_session
45 grs = ip.history_manager._get_range_session
45 grs = ip.history_manager._get_range_session
46 nt.assert_equal(list(grs(start=2,stop=-1)), zip([0], [2], hist[1:-1]))
46 nt.assert_equal(list(grs(start=2,stop=-1)), list(zip([0], [2], hist[1:-1])))
47 nt.assert_equal(list(grs(start=-2)), zip([0,0], [2,3], hist[-2:]))
47 nt.assert_equal(list(grs(start=-2)), list(zip([0,0], [2,3], hist[-2:])))
48 nt.assert_equal(list(grs(output=True)), zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam'])))
48 nt.assert_equal(list(grs(output=True)), list(zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam']))))
49
49
50 # Check whether specifying a range beyond the end of the current
50 # Check whether specifying a range beyond the end of the current
51 # session results in an error (gh-804)
51 # session results in an error (gh-804)
52 ip.magic('%hist 2-500')
52 ip.magic('%hist 2-500')
53
53
54 # Check that we can write non-ascii characters to a file
54 # Check that we can write non-ascii characters to a file
55 ip.magic("%%hist -f %s" % os.path.join(tmpdir, "test1"))
55 ip.magic("%%hist -f %s" % os.path.join(tmpdir, "test1"))
56 ip.magic("%%hist -pf %s" % os.path.join(tmpdir, "test2"))
56 ip.magic("%%hist -pf %s" % os.path.join(tmpdir, "test2"))
57 ip.magic("%%hist -nf %s" % os.path.join(tmpdir, "test3"))
57 ip.magic("%%hist -nf %s" % os.path.join(tmpdir, "test3"))
58 ip.magic("%%save %s 1-10" % os.path.join(tmpdir, "test4"))
58 ip.magic("%%save %s 1-10" % os.path.join(tmpdir, "test4"))
59
59
60 # New session
60 # New session
61 ip.history_manager.reset()
61 ip.history_manager.reset()
62 newcmds = [u"z=5",
62 newcmds = [u"z=5",
63 u"class X(object):\n pass",
63 u"class X(object):\n pass",
64 u"k='p'",
64 u"k='p'",
65 u"z=5"]
65 u"z=5"]
66 for i, cmd in enumerate(newcmds, start=1):
66 for i, cmd in enumerate(newcmds, start=1):
67 ip.history_manager.store_inputs(i, cmd)
67 ip.history_manager.store_inputs(i, cmd)
68 gothist = ip.history_manager.get_range(start=1, stop=4)
68 gothist = ip.history_manager.get_range(start=1, stop=4)
69 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
69 nt.assert_equal(list(gothist), list(zip([0,0,0],[1,2,3], newcmds)))
70 # Previous session:
70 # Previous session:
71 gothist = ip.history_manager.get_range(-1, 1, 4)
71 gothist = ip.history_manager.get_range(-1, 1, 4)
72 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
72 nt.assert_equal(list(gothist), list(zip([1,1,1],[1,2,3], hist)))
73
73
74 newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)]
74 newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)]
75
75
76 # Check get_hist_tail
76 # Check get_hist_tail
77 gothist = ip.history_manager.get_tail(5, output=True,
77 gothist = ip.history_manager.get_tail(5, output=True,
78 include_latest=True)
78 include_latest=True)
79 expected = [(1, 3, (hist[-1], "spam"))] \
79 expected = [(1, 3, (hist[-1], "spam"))] \
80 + [(s, n, (c, None)) for (s, n, c) in newhist]
80 + [(s, n, (c, None)) for (s, n, c) in newhist]
81 nt.assert_equal(list(gothist), expected)
81 nt.assert_equal(list(gothist), expected)
82
82
83 gothist = ip.history_manager.get_tail(2)
83 gothist = ip.history_manager.get_tail(2)
84 expected = newhist[-3:-1]
84 expected = newhist[-3:-1]
85 nt.assert_equal(list(gothist), expected)
85 nt.assert_equal(list(gothist), expected)
86
86
87 # Check get_hist_search
87 # Check get_hist_search
88 gothist = ip.history_manager.search("*test*")
88 gothist = ip.history_manager.search("*test*")
89 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
89 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
90
90
91 gothist = ip.history_manager.search("*=*")
91 gothist = ip.history_manager.search("*=*")
92 nt.assert_equal(list(gothist),
92 nt.assert_equal(list(gothist),
93 [(1, 1, hist[0]),
93 [(1, 1, hist[0]),
94 (1, 2, hist[1]),
94 (1, 2, hist[1]),
95 (1, 3, hist[2]),
95 (1, 3, hist[2]),
96 newhist[0],
96 newhist[0],
97 newhist[2],
97 newhist[2],
98 newhist[3]])
98 newhist[3]])
99
99
100 gothist = ip.history_manager.search("*=*", n=4)
100 gothist = ip.history_manager.search("*=*", n=4)
101 nt.assert_equal(list(gothist),
101 nt.assert_equal(list(gothist),
102 [(1, 3, hist[2]),
102 [(1, 3, hist[2]),
103 newhist[0],
103 newhist[0],
104 newhist[2],
104 newhist[2],
105 newhist[3]])
105 newhist[3]])
106
106
107 gothist = ip.history_manager.search("*=*", unique=True)
107 gothist = ip.history_manager.search("*=*", unique=True)
108 nt.assert_equal(list(gothist),
108 nt.assert_equal(list(gothist),
109 [(1, 1, hist[0]),
109 [(1, 1, hist[0]),
110 (1, 2, hist[1]),
110 (1, 2, hist[1]),
111 (1, 3, hist[2]),
111 (1, 3, hist[2]),
112 newhist[2],
112 newhist[2],
113 newhist[3]])
113 newhist[3]])
114
114
115 gothist = ip.history_manager.search("*=*", unique=True, n=3)
115 gothist = ip.history_manager.search("*=*", unique=True, n=3)
116 nt.assert_equal(list(gothist),
116 nt.assert_equal(list(gothist),
117 [(1, 3, hist[2]),
117 [(1, 3, hist[2]),
118 newhist[2],
118 newhist[2],
119 newhist[3]])
119 newhist[3]])
120
120
121 gothist = ip.history_manager.search("b*", output=True)
121 gothist = ip.history_manager.search("b*", output=True)
122 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
122 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
123
123
124 # Cross testing: check that magic %save can get previous session.
124 # Cross testing: check that magic %save can get previous session.
125 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
125 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
126 ip.magic("save " + testfilename + " ~1/1-3")
126 ip.magic("save " + testfilename + " ~1/1-3")
127 with py3compat.open(testfilename, encoding='utf-8') as testfile:
127 with py3compat.open(testfilename, encoding='utf-8') as testfile:
128 nt.assert_equal(testfile.read(),
128 nt.assert_equal(testfile.read(),
129 u"# coding: utf-8\n" + u"\n".join(hist)+u"\n")
129 u"# coding: utf-8\n" + u"\n".join(hist)+u"\n")
130
130
131 # Duplicate line numbers - check that it doesn't crash, and
131 # Duplicate line numbers - check that it doesn't crash, and
132 # gets a new session
132 # gets a new session
133 ip.history_manager.store_inputs(1, "rogue")
133 ip.history_manager.store_inputs(1, "rogue")
134 ip.history_manager.writeout_cache()
134 ip.history_manager.writeout_cache()
135 nt.assert_equal(ip.history_manager.session_number, 3)
135 nt.assert_equal(ip.history_manager.session_number, 3)
136 finally:
136 finally:
137 # Restore history manager
137 # Restore history manager
138 ip.history_manager = hist_manager_ori
138 ip.history_manager = hist_manager_ori
139
139
140
140
141 def test_extract_hist_ranges():
141 def test_extract_hist_ranges():
142 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5 ~10/"
142 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5 ~10/"
143 expected = [(0, 1, 2), # 0 == current session
143 expected = [(0, 1, 2), # 0 == current session
144 (2, 3, 4),
144 (2, 3, 4),
145 (-4, 5, 7),
145 (-4, 5, 7),
146 (-4, 7, 10),
146 (-4, 7, 10),
147 (-9, 2, None), # None == to end
147 (-9, 2, None), # None == to end
148 (-8, 1, None),
148 (-8, 1, None),
149 (-7, 1, 6),
149 (-7, 1, 6),
150 (-10, 1, None)]
150 (-10, 1, None)]
151 actual = list(extract_hist_ranges(instr))
151 actual = list(extract_hist_ranges(instr))
152 nt.assert_equal(actual, expected)
152 nt.assert_equal(actual, expected)
153
153
154 def test_magic_rerun():
154 def test_magic_rerun():
155 """Simple test for %rerun (no args -> rerun last line)"""
155 """Simple test for %rerun (no args -> rerun last line)"""
156 ip = get_ipython()
156 ip = get_ipython()
157 ip.run_cell("a = 10", store_history=True)
157 ip.run_cell("a = 10", store_history=True)
158 ip.run_cell("a += 1", store_history=True)
158 ip.run_cell("a += 1", store_history=True)
159 nt.assert_equal(ip.user_ns["a"], 11)
159 nt.assert_equal(ip.user_ns["a"], 11)
160 ip.run_cell("%rerun", store_history=True)
160 ip.run_cell("%rerun", store_history=True)
161 nt.assert_equal(ip.user_ns["a"], 12)
161 nt.assert_equal(ip.user_ns["a"], 12)
162
162
163 def test_timestamp_type():
163 def test_timestamp_type():
164 ip = get_ipython()
164 ip = get_ipython()
165 info = ip.history_manager.get_session_info()
165 info = ip.history_manager.get_session_info()
166 nt.assert_true(isinstance(info[1], datetime))
166 nt.assert_true(isinstance(info[1], datetime))
167
167
168 def test_hist_file_config():
168 def test_hist_file_config():
169 cfg = Config()
169 cfg = Config()
170 tfile = tempfile.NamedTemporaryFile(delete=False)
170 tfile = tempfile.NamedTemporaryFile(delete=False)
171 cfg.HistoryManager.hist_file = tfile.name
171 cfg.HistoryManager.hist_file = tfile.name
172 try:
172 try:
173 hm = HistoryManager(shell=get_ipython(), config=cfg)
173 hm = HistoryManager(shell=get_ipython(), config=cfg)
174 nt.assert_equal(hm.hist_file, cfg.HistoryManager.hist_file)
174 nt.assert_equal(hm.hist_file, cfg.HistoryManager.hist_file)
175 finally:
175 finally:
176 try:
176 try:
177 os.remove(tfile.name)
177 os.remove(tfile.name)
178 except OSError:
178 except OSError:
179 # same catch as in testing.tools.TempFileMixin
179 # same catch as in testing.tools.TempFileMixin
180 # On Windows, even though we close the file, we still can't
180 # On Windows, even though we close the file, we still can't
181 # delete it. I have no clue why
181 # delete it. I have no clue why
182 pass
182 pass
183
183
General Comments 0
You need to be logged in to leave comments. Login now