##// END OF EJS Templates
minor test fixes for win32
MinRK -
Show More
@@ -1,138 +1,144 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 sys
10 import sys
11 import tempfile
11 import tempfile
12 import unittest
12 import unittest
13 from datetime import datetime
13 from datetime import datetime
14
14
15 # third party
15 # third party
16 import nose.tools as nt
16 import nose.tools as nt
17
17
18 # our own packages
18 # our own packages
19 from IPython.config.loader import Config
19 from IPython.config.loader import Config
20 from IPython.utils.tempdir import TemporaryDirectory
20 from IPython.utils.tempdir import TemporaryDirectory
21 from IPython.core.history import HistoryManager, extract_hist_ranges
21 from IPython.core.history import HistoryManager, extract_hist_ranges
22 from IPython.utils import py3compat
22 from IPython.utils import py3compat
23
23
24 def setUp():
24 def setUp():
25 nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
25 nt.assert_equal(sys.getdefaultencoding(), "utf-8" if py3compat.PY3 else "ascii")
26
26
27 def test_history():
27 def test_history():
28 ip = get_ipython()
28 ip = get_ipython()
29 with TemporaryDirectory() as tmpdir:
29 with TemporaryDirectory() as tmpdir:
30 hist_manager_ori = ip.history_manager
30 hist_manager_ori = ip.history_manager
31 hist_file = os.path.join(tmpdir, 'history.sqlite')
31 hist_file = os.path.join(tmpdir, 'history.sqlite')
32 try:
32 try:
33 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
33 ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file)
34 hist = ['a=1', 'def f():\n test = 1\n return test', u"b='β‚¬Γ†ΒΎΓ·ΓŸ'"]
34 hist = ['a=1', 'def f():\n test = 1\n return test', u"b='β‚¬Γ†ΒΎΓ·ΓŸ'"]
35 for i, h in enumerate(hist, start=1):
35 for i, h in enumerate(hist, start=1):
36 ip.history_manager.store_inputs(i, h)
36 ip.history_manager.store_inputs(i, h)
37
37
38 ip.history_manager.db_log_output = True
38 ip.history_manager.db_log_output = True
39 # Doesn't match the input, but we'll just check it's stored.
39 # Doesn't match the input, but we'll just check it's stored.
40 ip.history_manager.output_hist_reprs[3] = "spam"
40 ip.history_manager.output_hist_reprs[3] = "spam"
41 ip.history_manager.store_output(3)
41 ip.history_manager.store_output(3)
42
42
43 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
43 nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist)
44
44
45 # Detailed tests for _get_range_session
45 # Detailed tests for _get_range_session
46 grs = ip.history_manager._get_range_session
46 grs = ip.history_manager._get_range_session
47 nt.assert_equal(list(grs(start=2,stop=-1)), zip([0], [2], hist[1:-1]))
47 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:]))
48 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'])))
49 nt.assert_equal(list(grs(output=True)), zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam'])))
50
50
51 # Check whether specifying a range beyond the end of the current
51 # Check whether specifying a range beyond the end of the current
52 # session results in an error (gh-804)
52 # session results in an error (gh-804)
53 ip.magic('%hist 2-500')
53 ip.magic('%hist 2-500')
54
54
55 # New session
55 # New session
56 ip.history_manager.reset()
56 ip.history_manager.reset()
57 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
57 newcmds = ["z=5","class X(object):\n pass", "k='p'"]
58 for i, cmd in enumerate(newcmds, start=1):
58 for i, cmd in enumerate(newcmds, start=1):
59 ip.history_manager.store_inputs(i, cmd)
59 ip.history_manager.store_inputs(i, cmd)
60 gothist = ip.history_manager.get_range(start=1, stop=4)
60 gothist = ip.history_manager.get_range(start=1, stop=4)
61 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
61 nt.assert_equal(list(gothist), zip([0,0,0],[1,2,3], newcmds))
62 # Previous session:
62 # Previous session:
63 gothist = ip.history_manager.get_range(-1, 1, 4)
63 gothist = ip.history_manager.get_range(-1, 1, 4)
64 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
64 nt.assert_equal(list(gothist), zip([1,1,1],[1,2,3], hist))
65
65
66 # Check get_hist_tail
66 # Check get_hist_tail
67 gothist = ip.history_manager.get_tail(4, output=True,
67 gothist = ip.history_manager.get_tail(4, output=True,
68 include_latest=True)
68 include_latest=True)
69 expected = [(1, 3, (hist[-1], "spam")),
69 expected = [(1, 3, (hist[-1], "spam")),
70 (2, 1, (newcmds[0], None)),
70 (2, 1, (newcmds[0], None)),
71 (2, 2, (newcmds[1], None)),
71 (2, 2, (newcmds[1], None)),
72 (2, 3, (newcmds[2], None)),]
72 (2, 3, (newcmds[2], None)),]
73 nt.assert_equal(list(gothist), expected)
73 nt.assert_equal(list(gothist), expected)
74
74
75 gothist = ip.history_manager.get_tail(2)
75 gothist = ip.history_manager.get_tail(2)
76 expected = [(2, 1, newcmds[0]),
76 expected = [(2, 1, newcmds[0]),
77 (2, 2, newcmds[1])]
77 (2, 2, newcmds[1])]
78 nt.assert_equal(list(gothist), expected)
78 nt.assert_equal(list(gothist), expected)
79
79
80 # Check get_hist_search
80 # Check get_hist_search
81 gothist = ip.history_manager.search("*test*")
81 gothist = ip.history_manager.search("*test*")
82 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
82 nt.assert_equal(list(gothist), [(1,2,hist[1])] )
83 gothist = ip.history_manager.search("b*", output=True)
83 gothist = ip.history_manager.search("b*", output=True)
84 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
84 nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] )
85
85
86 # Cross testing: check that magic %save can get previous session.
86 # Cross testing: check that magic %save can get previous session.
87 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
87 testfilename = os.path.realpath(os.path.join(tmpdir, "test.py"))
88 ip.magic_save(testfilename + " ~1/1-3")
88 ip.magic_save(testfilename + " ~1/1-3")
89 with py3compat.open(testfilename) as testfile:
89 with py3compat.open(testfilename) as testfile:
90 nt.assert_equal(testfile.read(),
90 nt.assert_equal(testfile.read(),
91 u"# coding: utf-8\n" + u"\n".join(hist))
91 u"# coding: utf-8\n" + u"\n".join(hist))
92
92
93 # Duplicate line numbers - check that it doesn't crash, and
93 # Duplicate line numbers - check that it doesn't crash, and
94 # gets a new session
94 # gets a new session
95 ip.history_manager.store_inputs(1, "rogue")
95 ip.history_manager.store_inputs(1, "rogue")
96 ip.history_manager.writeout_cache()
96 ip.history_manager.writeout_cache()
97 nt.assert_equal(ip.history_manager.session_number, 3)
97 nt.assert_equal(ip.history_manager.session_number, 3)
98 finally:
98 finally:
99 # Restore history manager
99 # Restore history manager
100 ip.history_manager = hist_manager_ori
100 ip.history_manager = hist_manager_ori
101
101
102
102
103 def test_extract_hist_ranges():
103 def test_extract_hist_ranges():
104 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5"
104 instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5"
105 expected = [(0, 1, 2), # 0 == current session
105 expected = [(0, 1, 2), # 0 == current session
106 (2, 3, 4),
106 (2, 3, 4),
107 (-4, 5, 7),
107 (-4, 5, 7),
108 (-4, 7, 10),
108 (-4, 7, 10),
109 (-9, 2, None), # None == to end
109 (-9, 2, None), # None == to end
110 (-8, 1, None),
110 (-8, 1, None),
111 (-7, 1, 6)]
111 (-7, 1, 6)]
112 actual = list(extract_hist_ranges(instr))
112 actual = list(extract_hist_ranges(instr))
113 nt.assert_equal(actual, expected)
113 nt.assert_equal(actual, expected)
114
114
115 def test_magic_rerun():
115 def test_magic_rerun():
116 """Simple test for %rerun (no args -> rerun last line)"""
116 """Simple test for %rerun (no args -> rerun last line)"""
117 ip = get_ipython()
117 ip = get_ipython()
118 ip.run_cell("a = 10", store_history=True)
118 ip.run_cell("a = 10", store_history=True)
119 ip.run_cell("a += 1", store_history=True)
119 ip.run_cell("a += 1", store_history=True)
120 nt.assert_equal(ip.user_ns["a"], 11)
120 nt.assert_equal(ip.user_ns["a"], 11)
121 ip.run_cell("%rerun", store_history=True)
121 ip.run_cell("%rerun", store_history=True)
122 nt.assert_equal(ip.user_ns["a"], 12)
122 nt.assert_equal(ip.user_ns["a"], 12)
123
123
124 def test_timestamp_type():
124 def test_timestamp_type():
125 ip = get_ipython()
125 ip = get_ipython()
126 info = ip.history_manager.get_session_info()
126 info = ip.history_manager.get_session_info()
127 nt.assert_true(isinstance(info[1], datetime))
127 nt.assert_true(isinstance(info[1], datetime))
128
128
129 def test_hist_file_config():
129 def test_hist_file_config():
130 cfg = Config()
130 cfg = Config()
131 tfile = tempfile.NamedTemporaryFile(delete=False)
131 tfile = tempfile.NamedTemporaryFile(delete=False)
132 cfg.HistoryManager.hist_file = tfile.name
132 cfg.HistoryManager.hist_file = tfile.name
133 try:
133 try:
134 hm = HistoryManager(shell=get_ipython(), config=cfg)
134 hm = HistoryManager(shell=get_ipython(), config=cfg)
135 nt.assert_equals(hm.hist_file, cfg.HistoryManager.hist_file)
135 nt.assert_equals(hm.hist_file, cfg.HistoryManager.hist_file)
136 finally:
136 finally:
137 os.remove(tfile.name)
137 try:
138 os.remove(tfile.name)
139 except OSError:
140 # same catch as in testing.tools.TempFileMixin
141 # On Windows, even though we close the file, we still can't
142 # delete it. I have no clue why
143 pass
138
144
@@ -1,103 +1,113 b''
1 """Tests for profile-related functions.
1 """Tests for profile-related functions.
2
2
3 Currently only the startup-dir functionality is tested, but more tests should
3 Currently only the startup-dir functionality is tested, but more tests should
4 be added for:
4 be added for:
5
5
6 * ipython profile create
6 * ipython profile create
7 * ipython profile list
7 * ipython profile list
8 * ipython profile create --parallel
8 * ipython profile create --parallel
9 * security dir permissions
9 * security dir permissions
10
10
11 Authors
11 Authors
12 -------
12 -------
13
13
14 * MinRK
14 * MinRK
15
15
16 """
16 """
17 from __future__ import absolute_import
17 from __future__ import absolute_import
18
18
19 #-----------------------------------------------------------------------------
19 #-----------------------------------------------------------------------------
20 # Imports
20 # Imports
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22
22
23 import os
23 import os
24 import shutil
24 import shutil
25 import sys
25 import sys
26 import tempfile
26 import tempfile
27
27
28 import nose.tools as nt
28 import nose.tools as nt
29 from nose import SkipTest
29 from nose import SkipTest
30
30
31 from IPython.core.profiledir import ProfileDir
31 from IPython.core.profiledir import ProfileDir
32
32
33 from IPython.testing import decorators as dec
33 from IPython.testing import decorators as dec
34 from IPython.testing import tools as tt
34 from IPython.testing import tools as tt
35 from IPython.utils import py3compat
35 from IPython.utils import py3compat
36
36
37
37
38 #-----------------------------------------------------------------------------
38 #-----------------------------------------------------------------------------
39 # Globals
39 # Globals
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 TMP_TEST_DIR = tempfile.mkdtemp()
41 TMP_TEST_DIR = tempfile.mkdtemp()
42 HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir")
42 HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir")
43 IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython')
43 IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython')
44
44
45 #
45 #
46 # Setup/teardown functions/decorators
46 # Setup/teardown functions/decorators
47 #
47 #
48
48
49 def setup():
49 def setup():
50 """Setup test environment for the module:
50 """Setup test environment for the module:
51
51
52 - Adds dummy home dir tree
52 - Adds dummy home dir tree
53 """
53 """
54 # Do not mask exceptions here. In particular, catching WindowsError is a
54 # Do not mask exceptions here. In particular, catching WindowsError is a
55 # problem because that exception is only defined on Windows...
55 # problem because that exception is only defined on Windows...
56 os.makedirs(IP_TEST_DIR)
56 os.makedirs(IP_TEST_DIR)
57
57
58
58
59 def teardown():
59 def teardown():
60 """Teardown test environment for the module:
60 """Teardown test environment for the module:
61
61
62 - Remove dummy home dir tree
62 - Remove dummy home dir tree
63 """
63 """
64 # Note: we remove the parent test dir, which is the root of all test
64 # Note: we remove the parent test dir, which is the root of all test
65 # subdirs we may have created. Use shutil instead of os.removedirs, so
65 # subdirs we may have created. Use shutil instead of os.removedirs, so
66 # that non-empty directories are all recursively removed.
66 # that non-empty directories are all recursively removed.
67 shutil.rmtree(TMP_TEST_DIR)
67 shutil.rmtree(TMP_TEST_DIR)
68
68
69
69
70 #-----------------------------------------------------------------------------
70 #-----------------------------------------------------------------------------
71 # Test functions
71 # Test functions
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 def win32_without_pywin32():
74 if sys.platform == 'win32':
75 try:
76 import pywin32
77 except ImportError:
78 return True
79 return False
80
73
81
82 @dec.skipif(win32_without_pywin32(), "Test requires pywin32 on Windows")
74 def test_startup_py():
83 def test_startup_py():
75 # create profile dir
84 # create profile dir
76 pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, 'test')
85 pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, 'test')
77 # write startup python file
86 # write startup python file
78 with open(os.path.join(pd.startup_dir, '00-start.py'), 'w') as f:
87 with open(os.path.join(pd.startup_dir, '00-start.py'), 'w') as f:
79 f.write('zzz=123\n')
88 f.write('zzz=123\n')
80 # write simple test file, to check that the startup file was run
89 # write simple test file, to check that the startup file was run
81 fname = os.path.join(TMP_TEST_DIR, 'test.py')
90 fname = os.path.join(TMP_TEST_DIR, 'test.py')
82 with open(fname, 'w') as f:
91 with open(fname, 'w') as f:
83 f.write(py3compat.doctest_refactor_print('print zzz\n'))
92 f.write(py3compat.doctest_refactor_print('print zzz\n'))
84 # validate output
93 # validate output
85 tt.ipexec_validate(fname, '123', '',
94 tt.ipexec_validate(fname, '123', '',
86 options=['--ipython-dir', IP_TEST_DIR, '--profile', 'test'])
95 options=['--ipython-dir', IP_TEST_DIR, '--profile', 'test'])
87
96
97 @dec.skipif(win32_without_pywin32(), "Test requires pywin32 on Windows")
88 def test_startup_ipy():
98 def test_startup_ipy():
89 # create profile dir
99 # create profile dir
90 pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, 'test')
100 pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, 'test')
91 # write startup ipython file
101 # write startup ipython file
92 with open(os.path.join(pd.startup_dir, '00-start.ipy'), 'w') as f:
102 with open(os.path.join(pd.startup_dir, '00-start.ipy'), 'w') as f:
93 f.write('%profile\n')
103 f.write('%profile\n')
94 # write empty script, because we don't need anything to happen
104 # write empty script, because we don't need anything to happen
95 # after the startup file is run
105 # after the startup file is run
96 fname = os.path.join(TMP_TEST_DIR, 'test.py')
106 fname = os.path.join(TMP_TEST_DIR, 'test.py')
97 with open(fname, 'w') as f:
107 with open(fname, 'w') as f:
98 f.write('')
108 f.write('')
99 # validate output
109 # validate output
100 tt.ipexec_validate(fname, 'test', '',
110 tt.ipexec_validate(fname, 'test', '',
101 options=['--ipython-dir', IP_TEST_DIR, '--profile', 'test'])
111 options=['--ipython-dir', IP_TEST_DIR, '--profile', 'test'])
102
112
103
113
General Comments 0
You need to be logged in to leave comments. Login now