##// END OF EJS Templates
Add test for writing non-ascii characters to file with %hist.
Thomas Kluyver -
Show More
@@ -1,144 +1,153 b''
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 shutil
10 import sys
11 import sys
11 import tempfile
12 import tempfile
12 import unittest
13 import unittest
13 from datetime import datetime
14 from datetime import datetime
14
15
15 # third party
16 # third party
16 import nose.tools as nt
17 import nose.tools as nt
17
18
18 # our own packages
19 # our own packages
19 from IPython.config.loader import Config
20 from IPython.config.loader import Config
20 from IPython.utils.tempdir import TemporaryDirectory
21 from IPython.utils.tempdir import TemporaryDirectory
21 from IPython.core.history import HistoryManager, extract_hist_ranges
22 from IPython.core.history import HistoryManager, extract_hist_ranges
22 from IPython.utils import py3compat
23 from IPython.utils import py3compat
23
24
24 def setUp():
25 def setUp():
25 nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
26 nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
26
27
27 def test_history():
28 def test_history():
28 ip = get_ipython()
29 ip = get_ipython()
29 with TemporaryDirectory() as tmpdir:
30 with TemporaryDirectory() as tmpdir:
30 hist_manager_ori = ip.history_manager
31 hist_manager_ori = ip.history_manager
31 hist_file = os.path.join(tmpdir, 'history.sqlite')
32 hist_file = os.path.join(tmpdir, 'history.sqlite')
32 try:
33 try:
33 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
34 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
34 hist = ['a=1', 'def f():\n test = 1\n return test', u"b='β‚¬Γ†ΒΎΓ·ΓŸ'"]
35 hist = ['a=1', 'def f():\n test = 1\n return test', u"b='β‚¬Γ†ΒΎΓ·ΓŸ'"]
35 for i, h in enumerate(hist, start=1):
36 for i, h in enumerate(hist, start=1):
36 ip.history_manager.store_inputs(i, h)
37 ip.history_manager.store_inputs(i, h)
37
38
38 ip.history_manager.db_log_output = True
39 ip.history_manager.db_log_output = True
39 # Doesn't match the input, but we'll just check it's stored.
40 # Doesn't match the input, but we'll just check it's stored.
40 ip.history_manager.output_hist_reprs[3] = "spam"
41 ip.history_manager.output_hist_reprs[3] = "spam"
41 ip.history_manager.store_output(3)
42 ip.history_manager.store_output(3)
42
43
43 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
44 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
44
45
45 # Detailed tests for _get_range_session
46 # Detailed tests for _get_range_session
46 grs = ip.history_manager._get_range_session
47 grs = ip.history_manager._get_range_session
47 nt.assert_equal(list(grs(start=2,stop=-1)), zip([0], [2], hist[1:-1]))
48 nt.assert_equal(list(grs(start=2,stop=-1)), zip([0], [2], hist[1:-1]))
48 nt.assert_equal(list(grs(start=-2)), zip([0,0], [2,3], hist[-2:]))
49 nt.assert_equal(list(grs(start=-2)), zip([0,0], [2,3], hist[-2:]))
49 nt.assert_equal(list(grs(output=True)), zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam'])))
50 nt.assert_equal(list(grs(output=True)), zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam'])))
50
51
51 # Check whether specifying a range beyond the end of the current
52 # Check whether specifying a range beyond the end of the current
52 # session results in an error (gh-804)
53 # session results in an error (gh-804)
53 ip.magic('%hist 2-500')
54 ip.magic('%hist 2-500')
55
56 # Check that we can write non-ascii characters to a file
57 tmpdir = tempfile.mkdtemp()
58 try:
59 ip.magic("%%hist -f %s" % os.path.join(tmpdir, "test1"))
60 ip.magic("%%save %s 1-10" % os.path.join(tmpdir, "test2"))
61 finally:
62 shutil.rmtree(tmpdir)
54
63
55 # New session
64 # New session
56 ip.history_manager.reset()
65 ip.history_manager.reset()
57 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
66 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
58 for i, cmd in enumerate(newcmds, start=1):
67 for i, cmd in enumerate(newcmds, start=1):
59 ip.history_manager.store_inputs(i, cmd)
68 ip.history_manager.store_inputs(i, cmd)
60 gothist = ip.history_manager.get_range(start=1, stop=4)
69 gothist = ip.history_manager.get_range(start=1, stop=4)
61 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
70 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
62 # Previous session:
71 # Previous session:
63 gothist = ip.history_manager.get_range(-1, 1, 4)
72 gothist = ip.history_manager.get_range(-1, 1, 4)
64 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
73 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
65
74
66 # Check get_hist_tail
75 # Check get_hist_tail
67 gothist = ip.history_manager.get_tail(4, output=True,
76 gothist = ip.history_manager.get_tail(4, output=True,
68 include_latest=True)
77 include_latest=True)
69 expected = [(1, 3, (hist[-1], "spam")),
78 expected = [(1, 3, (hist[-1], "spam")),
70 (2, 1, (newcmds[0], None)),
79 (2, 1, (newcmds[0], None)),
71 (2, 2, (newcmds[1], None)),
80 (2, 2, (newcmds[1], None)),
72 (2, 3, (newcmds[2], None)),]
81 (2, 3, (newcmds[2], None)),]
73 nt.assert_equal(list(gothist), expected)
82 nt.assert_equal(list(gothist), expected)
74
83
75 gothist = ip.history_manager.get_tail(2)
84 gothist = ip.history_manager.get_tail(2)
76 expected = [(2, 1, newcmds[0]),
85 expected = [(2, 1, newcmds[0]),
77 (2, 2, newcmds[1])]
86 (2, 2, newcmds[1])]
78 nt.assert_equal(list(gothist), expected)
87 nt.assert_equal(list(gothist), expected)
79
88
80 # Check get_hist_search
89 # Check get_hist_search
81 gothist = ip.history_manager.search("*test*")
90 gothist = ip.history_manager.search("*test*")
82 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
91 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
83 gothist = ip.history_manager.search("b*", output=True)
92 gothist = ip.history_manager.search("b*", output=True)
84 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
93 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
85
94
86 # Cross testing: check that magic %save can get previous session.
95 # Cross testing: check that magic %save can get previous session.
87 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
96 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
88 ip.magic_save(testfilename + " ~1/1-3")
97 ip.magic_save(testfilename + " ~1/1-3")
89 with py3compat.open(testfilename) as testfile:
98 with py3compat.open(testfilename) as testfile:
90 nt.assert_equal(testfile.read(),
99 nt.assert_equal(testfile.read(),
91 u"# coding: utf-8\n" + u"\n".join(hist))
100 u"# coding: utf-8\n" + u"\n".join(hist))
92
101
93 # Duplicate line numbers - check that it doesn't crash, and
102 # Duplicate line numbers - check that it doesn't crash, and
94 # gets a new session
103 # gets a new session
95 ip.history_manager.store_inputs(1, "rogue")
104 ip.history_manager.store_inputs(1, "rogue")
96 ip.history_manager.writeout_cache()
105 ip.history_manager.writeout_cache()
97 nt.assert_equal(ip.history_manager.session_number, 3)
106 nt.assert_equal(ip.history_manager.session_number, 3)
98 finally:
107 finally:
99 # Restore history manager
108 # Restore history manager
100 ip.history_manager = hist_manager_ori
109 ip.history_manager = hist_manager_ori
101
110
102
111
103 def test_extract_hist_ranges():
112 def test_extract_hist_ranges():
104 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5"
113 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5"
105 expected = [(0, 1, 2), # 0 == current session
114 expected = [(0, 1, 2), # 0 == current session
106 (2, 3, 4),
115 (2, 3, 4),
107 (-4, 5, 7),
116 (-4, 5, 7),
108 (-4, 7, 10),
117 (-4, 7, 10),
109 (-9, 2, None), # None == to end
118 (-9, 2, None), # None == to end
110 (-8, 1, None),
119 (-8, 1, None),
111 (-7, 1, 6)]
120 (-7, 1, 6)]
112 actual = list(extract_hist_ranges(instr))
121 actual = list(extract_hist_ranges(instr))
113 nt.assert_equal(actual, expected)
122 nt.assert_equal(actual, expected)
114
123
115 def test_magic_rerun():
124 def test_magic_rerun():
116 """Simple test for %rerun (no args -> rerun last line)"""
125 """Simple test for %rerun (no args -> rerun last line)"""
117 ip = get_ipython()
126 ip = get_ipython()
118 ip.run_cell("a = 10", store_history=True)
127 ip.run_cell("a = 10", store_history=True)
119 ip.run_cell("a += 1", store_history=True)
128 ip.run_cell("a += 1", store_history=True)
120 nt.assert_equal(ip.user_ns["a"], 11)
129 nt.assert_equal(ip.user_ns["a"], 11)
121 ip.run_cell("%rerun", store_history=True)
130 ip.run_cell("%rerun", store_history=True)
122 nt.assert_equal(ip.user_ns["a"], 12)
131 nt.assert_equal(ip.user_ns["a"], 12)
123
132
124 def test_timestamp_type():
133 def test_timestamp_type():
125 ip = get_ipython()
134 ip = get_ipython()
126 info = ip.history_manager.get_session_info()
135 info = ip.history_manager.get_session_info()
127 nt.assert_true(isinstance(info[1], datetime))
136 nt.assert_true(isinstance(info[1], datetime))
128
137
129 def test_hist_file_config():
138 def test_hist_file_config():
130 cfg = Config()
139 cfg = Config()
131 tfile = tempfile.NamedTemporaryFile(delete=False)
140 tfile = tempfile.NamedTemporaryFile(delete=False)
132 cfg.HistoryManager.hist_file = tfile.name
141 cfg.HistoryManager.hist_file = tfile.name
133 try:
142 try:
134 hm = HistoryManager(shell=get_ipython(), config=cfg)
143 hm = HistoryManager(shell=get_ipython(), config=cfg)
135 nt.assert_equals(hm.hist_file, cfg.HistoryManager.hist_file)
144 nt.assert_equals(hm.hist_file, cfg.HistoryManager.hist_file)
136 finally:
145 finally:
137 try:
146 try:
138 os.remove(tfile.name)
147 os.remove(tfile.name)
139 except OSError:
148 except OSError:
140 # same catch as in testing.tools.TempFileMixin
149 # same catch as in testing.tools.TempFileMixin
141 # On Windows, even though we close the file, we still can't
150 # On Windows, even though we close the file, we still can't
142 # delete it. I have no clue why
151 # delete it. I have no clue why
143 pass
152 pass
144
153
General Comments 0
You need to be logged in to leave comments. Login now