##// END OF EJS Templates
Passing IPython.core tests.
Thomas Kluyver -
Show More
@@ -97,6 +97,7 b' class HistoryManager(Configurable):'
97 '%quit', '%Exit', '%exit'])
97 '%quit', '%Exit', '%exit'])
98
98
99 def init_db(self):
99 def init_db(self):
100 """Connect to the database and get new session number."""
100 self.db = sqlite3.connect(self.hist_file)
101 self.db = sqlite3.connect(self.hist_file)
101 self.db.execute("""CREATE TABLE IF NOT EXISTS history
102 self.db.execute("""CREATE TABLE IF NOT EXISTS history
102 (session integer, line integer, source text, source_raw text,
103 (session integer, line integer, source text, source_raw text,
@@ -173,7 +174,8 b' class HistoryManager(Configurable):'
173 start : int
174 start : int
174 First line to retrieve.
175 First line to retrieve.
175 stop : int
176 stop : int
176 Last line to retrieve. If None, retrieve to the end of the session.
177 End of line range (excluded from output itself). If None, retrieve
178 to the end of the session.
177 raw : bool
179 raw : bool
178 If True, return untranslated input
180 If True, return untranslated input
179 output : bool
181 output : bool
@@ -294,13 +296,17 b' class HistoryManager(Configurable):'
294 self.input_hist_parsed[:lp-lr] = []
296 self.input_hist_parsed[:lp-lr] = []
295
297
296 def reset(self):
298 def reset(self):
297 """Clear all histories managed by this object."""
299 """Clear all histories managed by this object, and start a new
298 self.input_hist_parsed[:] = []
300 session."""
299 self.input_hist_raw[:] = []
301 self.input_hist_parsed[:] = [""]
302 self.input_hist_raw[:] = [""]
300 self.output_hist.clear()
303 self.output_hist.clear()
301 # The directory history can't be completely empty
304 # The directory history can't be completely empty
302 self.dir_hist[:] = [os.getcwd()]
305 self.dir_hist[:] = [os.getcwd()]
303
306
307 self.writeout_cache()
308 self.init_db() # New session
309
304 # To match, e.g. ~5/8-~2/3
310 # To match, e.g. ~5/8-~2/3
305 range_re = re.compile(r"""
311 range_re = re.compile(r"""
306 ((?P<startsess>~?\d+)/)?
312 ((?P<startsess>~?\d+)/)?
@@ -483,7 +489,7 b" def magic_history(self, parameter_s = ''):"
483 line_sep = '\n' if multiline else ''
489 line_sep = '\n' if multiline else ''
484 if print_nums:
490 if print_nums:
485 print('%s:%s' % (_format_lineno(session, lineno).ljust(width),
491 print('%s:%s' % (_format_lineno(session, lineno).ljust(width),
486 line_sep[multiline]), file=outfile, end='')
492 line_sep), file=outfile, end='')
487 if pyprompts:
493 if pyprompts:
488 print(">>> ", end="", file=outfile)
494 print(">>> ", end="", file=outfile)
489 if multiline:
495 if multiline:
@@ -1603,7 +1603,7 b' Currently the magic system has the following functions:\\n"""'
1603
1603
1604 stats = None
1604 stats = None
1605 try:
1605 try:
1606 self.shell.save_history()
1606 #self.shell.save_history()
1607
1607
1608 if opts.has_key('p'):
1608 if opts.has_key('p'):
1609 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
1609 stats = self.magic_prun('',0,opts,arg_lst,prog_ns)
@@ -1722,7 +1722,7 b' Currently the magic system has the following functions:\\n"""'
1722 # contained therein.
1722 # contained therein.
1723 del sys.modules[main_mod_name]
1723 del sys.modules[main_mod_name]
1724
1724
1725 self.shell.reload_history()
1725 #self.shell.reload_history()
1726
1726
1727 return stats
1727 return stats
1728
1728
@@ -14,52 +14,61 b' import nose.tools as nt'
14
14
15 # our own packages
15 # our own packages
16 from IPython.utils.tempdir import TemporaryDirectory
16 from IPython.utils.tempdir import TemporaryDirectory
17 from IPython.core.history import HistoryManager
17 from IPython.core.history import HistoryManager, extract_hist_ranges
18
18
19 def test_history():
19 def test_history():
20
20
21 ip = get_ipython()
21 ip = get_ipython()
22 with TemporaryDirectory() as tmpdir:
22 with TemporaryDirectory() as tmpdir:
23 #tmpdir = '/software/temp'
23 #tmpdir = '/software/temp'
24 histfile = os.path.realpath(os.path.join(tmpdir, 'history.json'))
24 histfile = os.path.realpath(os.path.join(tmpdir, 'history.sqlite'))
25 # Ensure that we restore the history management that we mess with in
25 # Ensure that we restore the history management that we mess with in
26 # this test doesn't affect the IPython instance used by the test suite
26 # this test doesn't affect the IPython instance used by the test suite
27 # beyond this test.
27 # beyond this test.
28 hist_manager_ori = ip.history_manager
28 hist_manager_ori = ip.history_manager
29 try:
29 try:
30 ip.history_manager = HistoryManager(ip)
30 ip.history_manager = HistoryManager(shell=ip)
31 ip.history_manager.hist_file = histfile
31 ip.history_manager.hist_file = histfile
32 ip.history_manager.init_db() # Has to be called after changing file
32 print 'test',histfile
33 print 'test',histfile
33 hist = ['a=1', 'def f():\n test = 1\n return test', 'b=2']
34 hist = ['a=1', 'def f():\n test = 1\n return test', 'b=2']
34 # test save and load
35 for i, h in enumerate(hist, start=1):
35 ip.history_manager.input_hist_raw[:] = []
36 ip.history_manager.store_inputs(i, h)
36 for h in hist:
37
37 ip.history_manager.store_inputs(h)
38 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
38 ip.save_history()
39
39 ip.history_manager.input_hist_raw[:] = []
40 # Check lines were written to DB
40 ip.reload_history()
41 c = ip.history_manager.db.execute("SELECT source_raw FROM history")
41 print type(ip.history_manager.input_hist_raw)
42 nt.assert_equal([x for x, in c], hist)
42 print ip.history_manager.input_hist_raw
43 nt.assert_equal(len(ip.history_manager.input_hist_raw), len(hist))
44 for i,h in enumerate(hist):
45 nt.assert_equal(hist[i], ip.history_manager.input_hist_raw[i])
46
43
47 # Test that session offset works.
44 # New session
48 ip.history_manager.session_offset = \
45 ip.history_manager.reset()
49 len(ip.history_manager.input_hist_raw) -1
50 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
46 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
51 for cmd in newcmds:
47 for i, cmd in enumerate(newcmds):
52 ip.history_manager.store_inputs(cmd)
48 ip.history_manager.store_inputs(i, cmd)
53 gothist = ip.history_manager.get_history((1,4),
49 gothist = ip.history_manager.get_history(start=1, stop=4)
54 raw=True, output=False)
50 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
55 nt.assert_equal(gothist, dict(zip([1,2,3], newcmds)))
51 # Previous session:
52 gothist = ip.history_manager.get_history(-1, 1, 4)
53 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
56
54
57 # Cross testing: check that magic %save picks up on the session
55 # Cross testing: check that magic %save can get previous session.
58 # offset.
59 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
56 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
60 ip.magic_save(testfilename + " 1-3")
57 ip.magic_save(testfilename + " ~1/1-3")
61 testfile = open(testfilename, "r")
58 testfile = open(testfilename, "r")
62 nt.assert_equal(testfile.read(), "\n".join(newcmds))
59 nt.assert_equal(testfile.read(), "\n".join(hist))
63 finally:
60 finally:
64 # Restore history manager
61 # Restore history manager
65 ip.history_manager = hist_manager_ori
62 ip.history_manager = hist_manager_ori
63
64 def test_extract_hist_ranges():
65 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5"
66 expected = [(0, 1, 2), # 0 == current session
67 (2, 3, 4),
68 (-4, 5, 7),
69 (-4, 7, 10),
70 (-9, 2, None), # None == to end
71 (-8, 1, None),
72 (-7, 1, 6)]
73 actual = list(extract_hist_ranges(instr))
74 nt.assert_equal(actual, expected)
@@ -62,7 +62,7 b' def doctest_hist_f():'
62
62
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64
64
65 In [11]: %hist -n -f $tfile 3
65 In [11]: %hist -nl -f $tfile 3
66
66
67 In [13]: import os; os.unlink(tfile)
67 In [13]: import os; os.unlink(tfile)
68 """
68 """
@@ -80,7 +80,7 b' def doctest_hist_r():'
80
80
81 In [2]: x=1
81 In [2]: x=1
82
82
83 In [3]: %hist -r 2
83 In [3]: %hist -rl 2
84 x=1 # random
84 x=1 # random
85 %hist -r 2
85 %hist -r 2
86 """
86 """
@@ -150,36 +150,14 b' def doctest_hist_op():'
150 <...s instance at ...>
150 <...s instance at ...>
151 >>>
151 >>>
152 """
152 """
153
153
154 def test_shist():
155 # Simple tests of ShadowHist class - test generator.
156 import os, shutil, tempfile
157
158 from IPython.utils import pickleshare
159 from IPython.core.history import ShadowHist
160
161 tfile = tempfile.mktemp('','tmp-ipython-')
162
163 db = pickleshare.PickleShareDB(tfile)
164 s = ShadowHist(db, get_ipython())
165 s.add('hello')
166 s.add('world')
167 s.add('hello')
168 s.add('hello')
169 s.add('karhu')
170
171 yield nt.assert_equals,s.all(),[(1, 'hello'), (2, 'world'), (3, 'karhu')]
172
173 yield nt.assert_equal,s.get(2),'world'
174
175 shutil.rmtree(tfile)
176
177 def test_macro():
154 def test_macro():
178 ip = get_ipython()
155 ip = get_ipython()
179 ip.history_manager.reset() # Clear any existing history.
156 ip.history_manager.reset() # Clear any existing history.
180 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
181 for cmd in cmds:
158 for i, cmd in enumerate(cmds, start=1):
182 ip.history_manager.store_inputs(cmd)
159 ip.history_manager.store_inputs(i, cmd)
160 print i, cmd
183 ip.magic("macro test 1-3")
161 ip.magic("macro test 1-3")
184 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
162 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
185
163
General Comments 0
You need to be logged in to leave comments. Login now