Show More
@@ -1,73 +1,73 b'' | |||||
1 | # coding: utf-8 |
|
1 | # coding: utf-8 | |
2 | """Tests for the compilerop module. |
|
2 | """Tests for the compilerop module. | |
3 | """ |
|
3 | """ | |
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2010-2011 The IPython Development Team. |
|
5 | # Copyright (C) 2010-2011 The IPython Development Team. | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the BSD License. |
|
7 | # Distributed under the terms of the BSD License. | |
8 | # |
|
8 | # | |
9 | # The full license is in the file COPYING.txt, distributed with this software. |
|
9 | # The full license is in the file COPYING.txt, distributed with this software. | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 |
|
11 | |||
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 | # Imports |
|
13 | # Imports | |
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 |
|
15 | |||
16 | # Stdlib imports |
|
16 | # Stdlib imports | |
17 | import linecache |
|
17 | import linecache | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | # Third-party imports |
|
20 | # Third-party imports | |
21 | import nose.tools as nt |
|
21 | import nose.tools as nt | |
22 |
|
22 | |||
23 | # Our own imports |
|
23 | # Our own imports | |
24 | from IPython.core import compilerop |
|
24 | from IPython.core import compilerop | |
25 |
|
25 | |||
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 | # Test functions |
|
27 | # Test functions | |
28 | #----------------------------------------------------------------------------- |
|
28 | #----------------------------------------------------------------------------- | |
29 |
|
29 | |||
30 | def test_code_name(): |
|
30 | def test_code_name(): | |
31 | code = 'x=1' |
|
31 | code = 'x=1' | |
32 | name = compilerop.code_name(code) |
|
32 | name = compilerop.code_name(code) | |
33 | nt.assert_true(name.startswith('<ipython-input-0')) |
|
33 | nt.assert_true(name.startswith('<ipython-input-0')) | |
34 |
|
34 | |||
35 |
|
35 | |||
36 | def test_code_name2(): |
|
36 | def test_code_name2(): | |
37 | code = 'x=1' |
|
37 | code = 'x=1' | |
38 | name = compilerop.code_name(code, 9) |
|
38 | name = compilerop.code_name(code, 9) | |
39 | nt.assert_true(name.startswith('<ipython-input-9')) |
|
39 | nt.assert_true(name.startswith('<ipython-input-9')) | |
40 |
|
40 | |||
41 |
|
41 | |||
42 | def test_cache(): |
|
42 | def test_cache(): | |
43 | """Test the compiler correctly compiles and caches inputs |
|
43 | """Test the compiler correctly compiles and caches inputs | |
44 | """ |
|
44 | """ | |
45 | cp = compilerop.CachingCompiler() |
|
45 | cp = compilerop.CachingCompiler() | |
46 | ncache = len(linecache.cache) |
|
46 | ncache = len(linecache.cache) | |
47 | cp.cache('x=1') |
|
47 | cp.cache('x=1') | |
48 | nt.assert_true(len(linecache.cache) > ncache) |
|
48 | nt.assert_true(len(linecache.cache) > ncache) | |
49 |
|
49 | |||
50 | def setUp(): |
|
50 | def test_proper_default_encoding(): | |
51 | # Check we're in a proper Python 2 environment (some imports, such |
|
51 | # Check we're in a proper Python 2 environment (some imports, such | |
52 | # as GTK, can change the default encoding, which can hide bugs.) |
|
52 | # as GTK, can change the default encoding, which can hide bugs.) | |
53 | nt.assert_equal(sys.getdefaultencoding(), "utf-8") |
|
53 | nt.assert_equal(sys.getdefaultencoding(), "utf-8") | |
54 |
|
54 | |||
55 | def test_cache_unicode(): |
|
55 | def test_cache_unicode(): | |
56 | cp = compilerop.CachingCompiler() |
|
56 | cp = compilerop.CachingCompiler() | |
57 | ncache = len(linecache.cache) |
|
57 | ncache = len(linecache.cache) | |
58 | cp.cache(u"t = 'ΕΎΔΔΕ‘Δ'") |
|
58 | cp.cache(u"t = 'ΕΎΔΔΕ‘Δ'") | |
59 | nt.assert_true(len(linecache.cache) > ncache) |
|
59 | nt.assert_true(len(linecache.cache) > ncache) | |
60 |
|
60 | |||
61 | def test_compiler_check_cache(): |
|
61 | def test_compiler_check_cache(): | |
62 | """Test the compiler properly manages the cache. |
|
62 | """Test the compiler properly manages the cache. | |
63 | """ |
|
63 | """ | |
64 | # Rather simple-minded tests that just exercise the API |
|
64 | # Rather simple-minded tests that just exercise the API | |
65 | cp = compilerop.CachingCompiler() |
|
65 | cp = compilerop.CachingCompiler() | |
66 | cp.cache('x=1', 99) |
|
66 | cp.cache('x=1', 99) | |
67 | # Ensure now that after clearing the cache, our entries survive |
|
67 | # Ensure now that after clearing the cache, our entries survive | |
68 | linecache.checkcache() |
|
68 | linecache.checkcache() | |
69 | for k in linecache.cache: |
|
69 | for k in linecache.cache: | |
70 | if k.startswith('<ipython-input-99'): |
|
70 | if k.startswith('<ipython-input-99'): | |
71 | break |
|
71 | break | |
72 | else: |
|
72 | else: | |
73 | raise AssertionError('Entry for input-99 missing from linecache') |
|
73 | raise AssertionError('Entry for input-99 missing from linecache') |
@@ -1,214 +1,214 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 io |
|
9 | import io | |
10 | import os |
|
10 | import os | |
11 | import sys |
|
11 | import sys | |
12 | import tempfile |
|
12 | import tempfile | |
13 | from datetime import datetime |
|
13 | from datetime import datetime | |
14 | import sqlite3 |
|
14 | import sqlite3 | |
15 |
|
15 | |||
16 | # third party |
|
16 | # third party | |
17 | import nose.tools as nt |
|
17 | import nose.tools as nt | |
18 |
|
18 | |||
19 | # our own packages |
|
19 | # our own packages | |
20 | from traitlets.config.loader import Config |
|
20 | from traitlets.config.loader import Config | |
21 | from IPython.utils.tempdir import TemporaryDirectory |
|
21 | from IPython.utils.tempdir import TemporaryDirectory | |
22 | from IPython.core.history import HistoryManager, extract_hist_ranges |
|
22 | from IPython.core.history import HistoryManager, extract_hist_ranges | |
23 | from IPython.testing.decorators import skipif |
|
23 | from IPython.testing.decorators import skipif | |
24 |
|
24 | |||
25 | def setUp(): |
|
25 | def test_proper_default_encoding(): | |
26 | nt.assert_equal(sys.getdefaultencoding(), "utf-8") |
|
26 | nt.assert_equal(sys.getdefaultencoding(), "utf-8") | |
27 |
|
27 | |||
28 | @skipif(sqlite3.sqlite_version_info > (3,24,0)) |
|
28 | @skipif(sqlite3.sqlite_version_info > (3,24,0)) | |
29 | def test_history(): |
|
29 | def test_history(): | |
30 | ip = get_ipython() |
|
30 | ip = get_ipython() | |
31 | with TemporaryDirectory() as tmpdir: |
|
31 | with TemporaryDirectory() as tmpdir: | |
32 | hist_manager_ori = ip.history_manager |
|
32 | hist_manager_ori = ip.history_manager | |
33 | hist_file = os.path.join(tmpdir, 'history.sqlite') |
|
33 | hist_file = os.path.join(tmpdir, 'history.sqlite') | |
34 | try: |
|
34 | try: | |
35 | ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file) |
|
35 | ip.history_manager = HistoryManager(shell=ip, hist_file=hist_file) | |
36 | hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='β¬ΓΒΎΓ·Γ'"] |
|
36 | hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='β¬ΓΒΎΓ·Γ'"] | |
37 | for i, h in enumerate(hist, start=1): |
|
37 | for i, h in enumerate(hist, start=1): | |
38 | ip.history_manager.store_inputs(i, h) |
|
38 | ip.history_manager.store_inputs(i, h) | |
39 |
|
39 | |||
40 | ip.history_manager.db_log_output = True |
|
40 | ip.history_manager.db_log_output = True | |
41 | # Doesn't match the input, but we'll just check it's stored. |
|
41 | # Doesn't match the input, but we'll just check it's stored. | |
42 | ip.history_manager.output_hist_reprs[3] = "spam" |
|
42 | ip.history_manager.output_hist_reprs[3] = "spam" | |
43 | ip.history_manager.store_output(3) |
|
43 | ip.history_manager.store_output(3) | |
44 |
|
44 | |||
45 | nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist) |
|
45 | nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist) | |
46 |
|
46 | |||
47 | # Detailed tests for _get_range_session |
|
47 | # Detailed tests for _get_range_session | |
48 | grs = ip.history_manager._get_range_session |
|
48 | grs = ip.history_manager._get_range_session | |
49 | nt.assert_equal(list(grs(start=2,stop=-1)), list(zip([0], [2], hist[1:-1]))) |
|
49 | nt.assert_equal(list(grs(start=2,stop=-1)), list(zip([0], [2], hist[1:-1]))) | |
50 | nt.assert_equal(list(grs(start=-2)), list(zip([0,0], [2,3], hist[-2:]))) |
|
50 | nt.assert_equal(list(grs(start=-2)), list(zip([0,0], [2,3], hist[-2:]))) | |
51 | nt.assert_equal(list(grs(output=True)), list(zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam'])))) |
|
51 | nt.assert_equal(list(grs(output=True)), list(zip([0,0,0], [1,2,3], zip(hist, [None,None,'spam'])))) | |
52 |
|
52 | |||
53 | # Check whether specifying a range beyond the end of the current |
|
53 | # Check whether specifying a range beyond the end of the current | |
54 | # session results in an error (gh-804) |
|
54 | # session results in an error (gh-804) | |
55 | ip.magic('%hist 2-500') |
|
55 | ip.magic('%hist 2-500') | |
56 |
|
56 | |||
57 | # Check that we can write non-ascii characters to a file |
|
57 | # Check that we can write non-ascii characters to a file | |
58 | ip.magic("%%hist -f %s" % os.path.join(tmpdir, "test1")) |
|
58 | ip.magic("%%hist -f %s" % os.path.join(tmpdir, "test1")) | |
59 | ip.magic("%%hist -pf %s" % os.path.join(tmpdir, "test2")) |
|
59 | ip.magic("%%hist -pf %s" % os.path.join(tmpdir, "test2")) | |
60 | ip.magic("%%hist -nf %s" % os.path.join(tmpdir, "test3")) |
|
60 | ip.magic("%%hist -nf %s" % os.path.join(tmpdir, "test3")) | |
61 | ip.magic("%%save %s 1-10" % os.path.join(tmpdir, "test4")) |
|
61 | ip.magic("%%save %s 1-10" % os.path.join(tmpdir, "test4")) | |
62 |
|
62 | |||
63 | # New session |
|
63 | # New session | |
64 | ip.history_manager.reset() |
|
64 | ip.history_manager.reset() | |
65 | newcmds = [u"z=5", |
|
65 | newcmds = [u"z=5", | |
66 | u"class X(object):\n pass", |
|
66 | u"class X(object):\n pass", | |
67 | u"k='p'", |
|
67 | u"k='p'", | |
68 | u"z=5"] |
|
68 | u"z=5"] | |
69 | for i, cmd in enumerate(newcmds, start=1): |
|
69 | for i, cmd in enumerate(newcmds, start=1): | |
70 | ip.history_manager.store_inputs(i, cmd) |
|
70 | ip.history_manager.store_inputs(i, cmd) | |
71 | gothist = ip.history_manager.get_range(start=1, stop=4) |
|
71 | gothist = ip.history_manager.get_range(start=1, stop=4) | |
72 | nt.assert_equal(list(gothist), list(zip([0,0,0],[1,2,3], newcmds))) |
|
72 | nt.assert_equal(list(gothist), list(zip([0,0,0],[1,2,3], newcmds))) | |
73 | # Previous session: |
|
73 | # Previous session: | |
74 | gothist = ip.history_manager.get_range(-1, 1, 4) |
|
74 | gothist = ip.history_manager.get_range(-1, 1, 4) | |
75 | nt.assert_equal(list(gothist), list(zip([1,1,1],[1,2,3], hist))) |
|
75 | nt.assert_equal(list(gothist), list(zip([1,1,1],[1,2,3], hist))) | |
76 |
|
76 | |||
77 | newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)] |
|
77 | newhist = [(2, i, c) for (i, c) in enumerate(newcmds, 1)] | |
78 |
|
78 | |||
79 | # Check get_hist_tail |
|
79 | # Check get_hist_tail | |
80 | gothist = ip.history_manager.get_tail(5, output=True, |
|
80 | gothist = ip.history_manager.get_tail(5, output=True, | |
81 | include_latest=True) |
|
81 | include_latest=True) | |
82 | expected = [(1, 3, (hist[-1], "spam"))] \ |
|
82 | expected = [(1, 3, (hist[-1], "spam"))] \ | |
83 | + [(s, n, (c, None)) for (s, n, c) in newhist] |
|
83 | + [(s, n, (c, None)) for (s, n, c) in newhist] | |
84 | nt.assert_equal(list(gothist), expected) |
|
84 | nt.assert_equal(list(gothist), expected) | |
85 |
|
85 | |||
86 | gothist = ip.history_manager.get_tail(2) |
|
86 | gothist = ip.history_manager.get_tail(2) | |
87 | expected = newhist[-3:-1] |
|
87 | expected = newhist[-3:-1] | |
88 | nt.assert_equal(list(gothist), expected) |
|
88 | nt.assert_equal(list(gothist), expected) | |
89 |
|
89 | |||
90 | # Check get_hist_search |
|
90 | # Check get_hist_search | |
91 |
|
91 | |||
92 | gothist = ip.history_manager.search("*test*") |
|
92 | gothist = ip.history_manager.search("*test*") | |
93 | nt.assert_equal(list(gothist), [(1,2,hist[1])] ) |
|
93 | nt.assert_equal(list(gothist), [(1,2,hist[1])] ) | |
94 |
|
94 | |||
95 | gothist = ip.history_manager.search("*=*") |
|
95 | gothist = ip.history_manager.search("*=*") | |
96 | nt.assert_equal(list(gothist), |
|
96 | nt.assert_equal(list(gothist), | |
97 | [(1, 1, hist[0]), |
|
97 | [(1, 1, hist[0]), | |
98 | (1, 2, hist[1]), |
|
98 | (1, 2, hist[1]), | |
99 | (1, 3, hist[2]), |
|
99 | (1, 3, hist[2]), | |
100 | newhist[0], |
|
100 | newhist[0], | |
101 | newhist[2], |
|
101 | newhist[2], | |
102 | newhist[3]]) |
|
102 | newhist[3]]) | |
103 |
|
103 | |||
104 | gothist = ip.history_manager.search("*=*", n=4) |
|
104 | gothist = ip.history_manager.search("*=*", n=4) | |
105 | nt.assert_equal(list(gothist), |
|
105 | nt.assert_equal(list(gothist), | |
106 | [(1, 3, hist[2]), |
|
106 | [(1, 3, hist[2]), | |
107 | newhist[0], |
|
107 | newhist[0], | |
108 | newhist[2], |
|
108 | newhist[2], | |
109 | newhist[3]]) |
|
109 | newhist[3]]) | |
110 |
|
110 | |||
111 | gothist = ip.history_manager.search("*=*", unique=True) |
|
111 | gothist = ip.history_manager.search("*=*", unique=True) | |
112 | nt.assert_equal(list(gothist), |
|
112 | nt.assert_equal(list(gothist), | |
113 | [(1, 1, hist[0]), |
|
113 | [(1, 1, hist[0]), | |
114 | (1, 2, hist[1]), |
|
114 | (1, 2, hist[1]), | |
115 | (1, 3, hist[2]), |
|
115 | (1, 3, hist[2]), | |
116 | newhist[2], |
|
116 | newhist[2], | |
117 | newhist[3]]) |
|
117 | newhist[3]]) | |
118 |
|
118 | |||
119 | gothist = ip.history_manager.search("*=*", unique=True, n=3) |
|
119 | gothist = ip.history_manager.search("*=*", unique=True, n=3) | |
120 | nt.assert_equal(list(gothist), |
|
120 | nt.assert_equal(list(gothist), | |
121 | [(1, 3, hist[2]), |
|
121 | [(1, 3, hist[2]), | |
122 | newhist[2], |
|
122 | newhist[2], | |
123 | newhist[3]]) |
|
123 | newhist[3]]) | |
124 |
|
124 | |||
125 | gothist = ip.history_manager.search("b*", output=True) |
|
125 | gothist = ip.history_manager.search("b*", output=True) | |
126 | nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] ) |
|
126 | nt.assert_equal(list(gothist), [(1,3,(hist[2],"spam"))] ) | |
127 |
|
127 | |||
128 | # Cross testing: check that magic %save can get previous session. |
|
128 | # Cross testing: check that magic %save can get previous session. | |
129 | testfilename = os.path.realpath(os.path.join(tmpdir, "test.py")) |
|
129 | testfilename = os.path.realpath(os.path.join(tmpdir, "test.py")) | |
130 | ip.magic("save " + testfilename + " ~1/1-3") |
|
130 | ip.magic("save " + testfilename + " ~1/1-3") | |
131 | with io.open(testfilename, encoding='utf-8') as testfile: |
|
131 | with io.open(testfilename, encoding='utf-8') as testfile: | |
132 | nt.assert_equal(testfile.read(), |
|
132 | nt.assert_equal(testfile.read(), | |
133 | u"# coding: utf-8\n" + u"\n".join(hist)+u"\n") |
|
133 | u"# coding: utf-8\n" + u"\n".join(hist)+u"\n") | |
134 |
|
134 | |||
135 | # Duplicate line numbers - check that it doesn't crash, and |
|
135 | # Duplicate line numbers - check that it doesn't crash, and | |
136 | # gets a new session |
|
136 | # gets a new session | |
137 | ip.history_manager.store_inputs(1, "rogue") |
|
137 | ip.history_manager.store_inputs(1, "rogue") | |
138 | ip.history_manager.writeout_cache() |
|
138 | ip.history_manager.writeout_cache() | |
139 | nt.assert_equal(ip.history_manager.session_number, 3) |
|
139 | nt.assert_equal(ip.history_manager.session_number, 3) | |
140 | finally: |
|
140 | finally: | |
141 | # Ensure saving thread is shut down before we try to clean up the files |
|
141 | # Ensure saving thread is shut down before we try to clean up the files | |
142 | ip.history_manager.save_thread.stop() |
|
142 | ip.history_manager.save_thread.stop() | |
143 | # Forcibly close database rather than relying on garbage collection |
|
143 | # Forcibly close database rather than relying on garbage collection | |
144 | ip.history_manager.db.close() |
|
144 | ip.history_manager.db.close() | |
145 | # Restore history manager |
|
145 | # Restore history manager | |
146 | ip.history_manager = hist_manager_ori |
|
146 | ip.history_manager = hist_manager_ori | |
147 |
|
147 | |||
148 |
|
148 | |||
149 | def test_extract_hist_ranges(): |
|
149 | def test_extract_hist_ranges(): | |
150 | instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5 ~10/" |
|
150 | instr = "1 2/3 ~4/5-6 ~4/7-~4/9 ~9/2-~7/5 ~10/" | |
151 | expected = [(0, 1, 2), # 0 == current session |
|
151 | expected = [(0, 1, 2), # 0 == current session | |
152 | (2, 3, 4), |
|
152 | (2, 3, 4), | |
153 | (-4, 5, 7), |
|
153 | (-4, 5, 7), | |
154 | (-4, 7, 10), |
|
154 | (-4, 7, 10), | |
155 | (-9, 2, None), # None == to end |
|
155 | (-9, 2, None), # None == to end | |
156 | (-8, 1, None), |
|
156 | (-8, 1, None), | |
157 | (-7, 1, 6), |
|
157 | (-7, 1, 6), | |
158 | (-10, 1, None)] |
|
158 | (-10, 1, None)] | |
159 | actual = list(extract_hist_ranges(instr)) |
|
159 | actual = list(extract_hist_ranges(instr)) | |
160 | nt.assert_equal(actual, expected) |
|
160 | nt.assert_equal(actual, expected) | |
161 |
|
161 | |||
162 | def test_magic_rerun(): |
|
162 | def test_magic_rerun(): | |
163 | """Simple test for %rerun (no args -> rerun last line)""" |
|
163 | """Simple test for %rerun (no args -> rerun last line)""" | |
164 | ip = get_ipython() |
|
164 | ip = get_ipython() | |
165 | ip.run_cell("a = 10", store_history=True) |
|
165 | ip.run_cell("a = 10", store_history=True) | |
166 | ip.run_cell("a += 1", store_history=True) |
|
166 | ip.run_cell("a += 1", store_history=True) | |
167 | nt.assert_equal(ip.user_ns["a"], 11) |
|
167 | nt.assert_equal(ip.user_ns["a"], 11) | |
168 | ip.run_cell("%rerun", store_history=True) |
|
168 | ip.run_cell("%rerun", store_history=True) | |
169 | nt.assert_equal(ip.user_ns["a"], 12) |
|
169 | nt.assert_equal(ip.user_ns["a"], 12) | |
170 |
|
170 | |||
171 | def test_timestamp_type(): |
|
171 | def test_timestamp_type(): | |
172 | ip = get_ipython() |
|
172 | ip = get_ipython() | |
173 | info = ip.history_manager.get_session_info() |
|
173 | info = ip.history_manager.get_session_info() | |
174 | nt.assert_true(isinstance(info[1], datetime)) |
|
174 | nt.assert_true(isinstance(info[1], datetime)) | |
175 |
|
175 | |||
176 | def test_hist_file_config(): |
|
176 | def test_hist_file_config(): | |
177 | cfg = Config() |
|
177 | cfg = Config() | |
178 | tfile = tempfile.NamedTemporaryFile(delete=False) |
|
178 | tfile = tempfile.NamedTemporaryFile(delete=False) | |
179 | cfg.HistoryManager.hist_file = tfile.name |
|
179 | cfg.HistoryManager.hist_file = tfile.name | |
180 | try: |
|
180 | try: | |
181 | hm = HistoryManager(shell=get_ipython(), config=cfg) |
|
181 | hm = HistoryManager(shell=get_ipython(), config=cfg) | |
182 | nt.assert_equal(hm.hist_file, cfg.HistoryManager.hist_file) |
|
182 | nt.assert_equal(hm.hist_file, cfg.HistoryManager.hist_file) | |
183 | finally: |
|
183 | finally: | |
184 | try: |
|
184 | try: | |
185 | os.remove(tfile.name) |
|
185 | os.remove(tfile.name) | |
186 | except OSError: |
|
186 | except OSError: | |
187 | # same catch as in testing.tools.TempFileMixin |
|
187 | # same catch as in testing.tools.TempFileMixin | |
188 | # On Windows, even though we close the file, we still can't |
|
188 | # On Windows, even though we close the file, we still can't | |
189 | # delete it. I have no clue why |
|
189 | # delete it. I have no clue why | |
190 | pass |
|
190 | pass | |
191 |
|
191 | |||
192 | def test_histmanager_disabled(): |
|
192 | def test_histmanager_disabled(): | |
193 | """Ensure that disabling the history manager doesn't create a database.""" |
|
193 | """Ensure that disabling the history manager doesn't create a database.""" | |
194 | cfg = Config() |
|
194 | cfg = Config() | |
195 | cfg.HistoryAccessor.enabled = False |
|
195 | cfg.HistoryAccessor.enabled = False | |
196 |
|
196 | |||
197 | ip = get_ipython() |
|
197 | ip = get_ipython() | |
198 | with TemporaryDirectory() as tmpdir: |
|
198 | with TemporaryDirectory() as tmpdir: | |
199 | hist_manager_ori = ip.history_manager |
|
199 | hist_manager_ori = ip.history_manager | |
200 | hist_file = os.path.join(tmpdir, 'history.sqlite') |
|
200 | hist_file = os.path.join(tmpdir, 'history.sqlite') | |
201 | cfg.HistoryManager.hist_file = hist_file |
|
201 | cfg.HistoryManager.hist_file = hist_file | |
202 | try: |
|
202 | try: | |
203 | ip.history_manager = HistoryManager(shell=ip, config=cfg) |
|
203 | ip.history_manager = HistoryManager(shell=ip, config=cfg) | |
204 | hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='β¬ΓΒΎΓ·Γ'"] |
|
204 | hist = [u'a=1', u'def f():\n test = 1\n return test', u"b='β¬ΓΒΎΓ·Γ'"] | |
205 | for i, h in enumerate(hist, start=1): |
|
205 | for i, h in enumerate(hist, start=1): | |
206 | ip.history_manager.store_inputs(i, h) |
|
206 | ip.history_manager.store_inputs(i, h) | |
207 | nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist) |
|
207 | nt.assert_equal(ip.history_manager.input_hist_raw, [''] + hist) | |
208 | ip.history_manager.reset() |
|
208 | ip.history_manager.reset() | |
209 | ip.history_manager.end_session() |
|
209 | ip.history_manager.end_session() | |
210 | finally: |
|
210 | finally: | |
211 | ip.history_manager = hist_manager_ori |
|
211 | ip.history_manager = hist_manager_ori | |
212 |
|
212 | |||
213 | # hist_file should not be created |
|
213 | # hist_file should not be created | |
214 | nt.assert_false(os.path.exists(hist_file)) |
|
214 | nt.assert_false(os.path.exists(hist_file)) |
@@ -1,200 +1,200 b'' | |||||
1 | import errno |
|
1 | import errno | |
2 | import os |
|
2 | import os | |
3 | import shutil |
|
3 | import shutil | |
4 | import sys |
|
4 | import sys | |
5 | import tempfile |
|
5 | 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 |
|
9 | import nose.tools as nt | |
10 | from testpath import modified_env, assert_isdir, assert_isfile |
|
10 | from testpath import modified_env, assert_isdir, assert_isfile | |
11 |
|
11 | |||
12 | from IPython import paths |
|
12 | from IPython import paths | |
13 | from IPython.testing.decorators import skip_win32 |
|
13 | from IPython.testing.decorators import skip_win32 | |
14 | from IPython.utils.tempdir import TemporaryDirectory |
|
14 | from IPython.utils.tempdir import TemporaryDirectory | |
15 |
|
15 | |||
16 | TMP_TEST_DIR = os.path.realpath(tempfile.mkdtemp()) |
|
16 | TMP_TEST_DIR = os.path.realpath(tempfile.mkdtemp()) | |
17 | HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir") |
|
17 | HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir") | |
18 | XDG_TEST_DIR = os.path.join(HOME_TEST_DIR, "xdg_test_dir") |
|
18 | XDG_TEST_DIR = os.path.join(HOME_TEST_DIR, "xdg_test_dir") | |
19 | XDG_CACHE_DIR = os.path.join(HOME_TEST_DIR, "xdg_cache_dir") |
|
19 | XDG_CACHE_DIR = os.path.join(HOME_TEST_DIR, "xdg_cache_dir") | |
20 | IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython') |
|
20 | IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython') | |
21 |
|
21 | |||
22 | def setup(): |
|
22 | def setup_module(): | |
23 | """Setup testenvironment for the module: |
|
23 | """Setup testenvironment for the module: | |
24 |
|
24 | |||
25 | - Adds dummy home dir tree |
|
25 | - Adds dummy home dir tree | |
26 | """ |
|
26 | """ | |
27 | # Do not mask exceptions here. In particular, catching WindowsError is a |
|
27 | # Do not mask exceptions here. In particular, catching WindowsError is a | |
28 | # problem because that exception is only defined on Windows... |
|
28 | # problem because that exception is only defined on Windows... | |
29 | os.makedirs(IP_TEST_DIR) |
|
29 | os.makedirs(IP_TEST_DIR) | |
30 | os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython')) |
|
30 | os.makedirs(os.path.join(XDG_TEST_DIR, 'ipython')) | |
31 | os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython')) |
|
31 | os.makedirs(os.path.join(XDG_CACHE_DIR, 'ipython')) | |
32 |
|
32 | |||
33 |
|
33 | |||
34 | def teardown(): |
|
34 | def teardown_module(): | |
35 | """Teardown testenvironment for the module: |
|
35 | """Teardown testenvironment for the module: | |
36 |
|
36 | |||
37 | - Remove dummy home dir tree |
|
37 | - Remove dummy home dir tree | |
38 | """ |
|
38 | """ | |
39 | # Note: we remove the parent test dir, which is the root of all test |
|
39 | # Note: we remove the parent test dir, which is the root of all test | |
40 | # subdirs we may have created. Use shutil instead of os.removedirs, so |
|
40 | # subdirs we may have created. Use shutil instead of os.removedirs, so | |
41 | # that non-empty directories are all recursively removed. |
|
41 | # that non-empty directories are all recursively removed. | |
42 | shutil.rmtree(TMP_TEST_DIR) |
|
42 | shutil.rmtree(TMP_TEST_DIR) | |
43 |
|
43 | |||
44 | def patch_get_home_dir(dirpath): |
|
44 | def patch_get_home_dir(dirpath): | |
45 | return patch.object(paths, 'get_home_dir', return_value=dirpath) |
|
45 | return patch.object(paths, 'get_home_dir', return_value=dirpath) | |
46 |
|
46 | |||
47 |
|
47 | |||
48 | def test_get_ipython_dir_1(): |
|
48 | def test_get_ipython_dir_1(): | |
49 | """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions.""" |
|
49 | """test_get_ipython_dir_1, Testcase to see if we can call get_ipython_dir without Exceptions.""" | |
50 | env_ipdir = os.path.join("someplace", ".ipython") |
|
50 | env_ipdir = os.path.join("someplace", ".ipython") | |
51 | with patch.object(paths, '_writable_dir', return_value=True), \ |
|
51 | with patch.object(paths, '_writable_dir', return_value=True), \ | |
52 | modified_env({'IPYTHONDIR': env_ipdir}): |
|
52 | modified_env({'IPYTHONDIR': env_ipdir}): | |
53 | ipdir = paths.get_ipython_dir() |
|
53 | ipdir = paths.get_ipython_dir() | |
54 |
|
54 | |||
55 | nt.assert_equal(ipdir, env_ipdir) |
|
55 | nt.assert_equal(ipdir, env_ipdir) | |
56 |
|
56 | |||
57 | def test_get_ipython_dir_2(): |
|
57 | def test_get_ipython_dir_2(): | |
58 | """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions.""" |
|
58 | """test_get_ipython_dir_2, Testcase to see if we can call get_ipython_dir without Exceptions.""" | |
59 | with patch_get_home_dir('someplace'), \ |
|
59 | with patch_get_home_dir('someplace'), \ | |
60 | patch.object(paths, 'get_xdg_dir', return_value=None), \ |
|
60 | patch.object(paths, 'get_xdg_dir', return_value=None), \ | |
61 | patch.object(paths, '_writable_dir', return_value=True), \ |
|
61 | patch.object(paths, '_writable_dir', return_value=True), \ | |
62 | patch('os.name', "posix"), \ |
|
62 | patch('os.name', "posix"), \ | |
63 | modified_env({'IPYTHON_DIR': None, |
|
63 | modified_env({'IPYTHON_DIR': None, | |
64 | 'IPYTHONDIR': None, |
|
64 | 'IPYTHONDIR': None, | |
65 | 'XDG_CONFIG_HOME': None |
|
65 | 'XDG_CONFIG_HOME': None | |
66 | }): |
|
66 | }): | |
67 | ipdir = paths.get_ipython_dir() |
|
67 | ipdir = paths.get_ipython_dir() | |
68 |
|
68 | |||
69 | nt.assert_equal(ipdir, os.path.join("someplace", ".ipython")) |
|
69 | nt.assert_equal(ipdir, os.path.join("someplace", ".ipython")) | |
70 |
|
70 | |||
71 | def test_get_ipython_dir_3(): |
|
71 | def test_get_ipython_dir_3(): | |
72 | """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist.""" |
|
72 | """test_get_ipython_dir_3, move XDG if defined, and .ipython doesn't exist.""" | |
73 | tmphome = TemporaryDirectory() |
|
73 | tmphome = TemporaryDirectory() | |
74 | try: |
|
74 | try: | |
75 | with patch_get_home_dir(tmphome.name), \ |
|
75 | with patch_get_home_dir(tmphome.name), \ | |
76 | patch('os.name', 'posix'), \ |
|
76 | patch('os.name', 'posix'), \ | |
77 | modified_env({ |
|
77 | modified_env({ | |
78 | 'IPYTHON_DIR': None, |
|
78 | 'IPYTHON_DIR': None, | |
79 | 'IPYTHONDIR': None, |
|
79 | 'IPYTHONDIR': None, | |
80 | 'XDG_CONFIG_HOME': XDG_TEST_DIR, |
|
80 | 'XDG_CONFIG_HOME': XDG_TEST_DIR, | |
81 | }), warnings.catch_warnings(record=True) as w: |
|
81 | }), warnings.catch_warnings(record=True) as w: | |
82 | ipdir = paths.get_ipython_dir() |
|
82 | ipdir = paths.get_ipython_dir() | |
83 |
|
83 | |||
84 | nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython")) |
|
84 | nt.assert_equal(ipdir, os.path.join(tmphome.name, ".ipython")) | |
85 | if sys.platform != 'darwin': |
|
85 | if sys.platform != 'darwin': | |
86 | nt.assert_equal(len(w), 1) |
|
86 | nt.assert_equal(len(w), 1) | |
87 | nt.assert_in('Moving', str(w[0])) |
|
87 | nt.assert_in('Moving', str(w[0])) | |
88 | finally: |
|
88 | finally: | |
89 | tmphome.cleanup() |
|
89 | tmphome.cleanup() | |
90 |
|
90 | |||
91 | def test_get_ipython_dir_4(): |
|
91 | def test_get_ipython_dir_4(): | |
92 | """test_get_ipython_dir_4, warn if XDG and home both exist.""" |
|
92 | """test_get_ipython_dir_4, warn if XDG and home both exist.""" | |
93 | with patch_get_home_dir(HOME_TEST_DIR), \ |
|
93 | with patch_get_home_dir(HOME_TEST_DIR), \ | |
94 | patch('os.name', 'posix'): |
|
94 | patch('os.name', 'posix'): | |
95 | try: |
|
95 | try: | |
96 | os.mkdir(os.path.join(XDG_TEST_DIR, 'ipython')) |
|
96 | os.mkdir(os.path.join(XDG_TEST_DIR, 'ipython')) | |
97 | except OSError as e: |
|
97 | except OSError as e: | |
98 | if e.errno != errno.EEXIST: |
|
98 | if e.errno != errno.EEXIST: | |
99 | raise |
|
99 | raise | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | with modified_env({ |
|
102 | with modified_env({ | |
103 | 'IPYTHON_DIR': None, |
|
103 | 'IPYTHON_DIR': None, | |
104 | 'IPYTHONDIR': None, |
|
104 | 'IPYTHONDIR': None, | |
105 | 'XDG_CONFIG_HOME': XDG_TEST_DIR, |
|
105 | 'XDG_CONFIG_HOME': XDG_TEST_DIR, | |
106 | }), warnings.catch_warnings(record=True) as w: |
|
106 | }), warnings.catch_warnings(record=True) as w: | |
107 | ipdir = paths.get_ipython_dir() |
|
107 | ipdir = paths.get_ipython_dir() | |
108 |
|
108 | |||
109 | nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython")) |
|
109 | nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, ".ipython")) | |
110 | if sys.platform != 'darwin': |
|
110 | if sys.platform != 'darwin': | |
111 | nt.assert_equal(len(w), 1) |
|
111 | nt.assert_equal(len(w), 1) | |
112 | nt.assert_in('Ignoring', str(w[0])) |
|
112 | nt.assert_in('Ignoring', str(w[0])) | |
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.""" | |
116 | with patch_get_home_dir(HOME_TEST_DIR), \ |
|
116 | with patch_get_home_dir(HOME_TEST_DIR), \ | |
117 | patch('os.name', 'posix'): |
|
117 | patch('os.name', 'posix'): | |
118 | try: |
|
118 | try: | |
119 | os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython')) |
|
119 | os.rmdir(os.path.join(XDG_TEST_DIR, 'ipython')) | |
120 | except OSError as e: |
|
120 | except OSError as e: | |
121 | if e.errno != errno.ENOENT: |
|
121 | if e.errno != errno.ENOENT: | |
122 | raise |
|
122 | raise | |
123 |
|
123 | |||
124 | with modified_env({ |
|
124 | with modified_env({ | |
125 | 'IPYTHON_DIR': None, |
|
125 | 'IPYTHON_DIR': None, | |
126 | 'IPYTHONDIR': None, |
|
126 | 'IPYTHONDIR': None, | |
127 | 'XDG_CONFIG_HOME': XDG_TEST_DIR, |
|
127 | 'XDG_CONFIG_HOME': XDG_TEST_DIR, | |
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 | nt.assert_equal(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.""" | |
135 | xdg = os.path.join(HOME_TEST_DIR, 'somexdg') |
|
135 | xdg = os.path.join(HOME_TEST_DIR, 'somexdg') | |
136 | os.mkdir(xdg) |
|
136 | os.mkdir(xdg) | |
137 | shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython')) |
|
137 | shutil.rmtree(os.path.join(HOME_TEST_DIR, '.ipython')) | |
138 | print(paths._writable_dir) |
|
138 | print(paths._writable_dir) | |
139 | with patch_get_home_dir(HOME_TEST_DIR), \ |
|
139 | with patch_get_home_dir(HOME_TEST_DIR), \ | |
140 | patch.object(paths, 'get_xdg_dir', return_value=xdg), \ |
|
140 | patch.object(paths, 'get_xdg_dir', return_value=xdg), \ | |
141 | patch('os.name', 'posix'), \ |
|
141 | patch('os.name', 'posix'), \ | |
142 | modified_env({ |
|
142 | modified_env({ | |
143 | 'IPYTHON_DIR': None, |
|
143 | 'IPYTHON_DIR': None, | |
144 | 'IPYTHONDIR': None, |
|
144 | 'IPYTHONDIR': None, | |
145 | 'XDG_CONFIG_HOME': None, |
|
145 | 'XDG_CONFIG_HOME': None, | |
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 | nt.assert_equal(ipdir, os.path.join(HOME_TEST_DIR, '.ipython')) | |
150 | nt.assert_equal(len(w), 0) |
|
150 | nt.assert_equal(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""" | |
154 | home_dir = os.path.normpath(os.path.expanduser('~')) |
|
154 | home_dir = os.path.normpath(os.path.expanduser('~')) | |
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 | nt.assert_equal(ipdir, os.path.join(home_dir, 'somewhere')) | |
159 |
|
159 | |||
160 | @skip_win32 |
|
160 | @skip_win32 | |
161 | def test_get_ipython_dir_8(): |
|
161 | def test_get_ipython_dir_8(): | |
162 | """test_get_ipython_dir_8, test / home directory""" |
|
162 | """test_get_ipython_dir_8, test / home directory""" | |
163 | with patch.object(paths, '_writable_dir', lambda path: bool(path)), \ |
|
163 | with patch.object(paths, '_writable_dir', lambda path: bool(path)), \ | |
164 | patch.object(paths, 'get_xdg_dir', return_value=None), \ |
|
164 | patch.object(paths, 'get_xdg_dir', return_value=None), \ | |
165 | modified_env({ |
|
165 | modified_env({ | |
166 | 'IPYTHON_DIR': None, |
|
166 | 'IPYTHON_DIR': None, | |
167 | 'IPYTHONDIR': None, |
|
167 | 'IPYTHONDIR': None, | |
168 | 'HOME': '/', |
|
168 | 'HOME': '/', | |
169 | }): |
|
169 | }): | |
170 | nt.assert_equal(paths.get_ipython_dir(), '/.ipython') |
|
170 | nt.assert_equal(paths.get_ipython_dir(), '/.ipython') | |
171 |
|
171 | |||
172 |
|
172 | |||
173 | def test_get_ipython_cache_dir(): |
|
173 | def test_get_ipython_cache_dir(): | |
174 | with modified_env({'HOME': HOME_TEST_DIR}): |
|
174 | with modified_env({'HOME': HOME_TEST_DIR}): | |
175 | if os.name == 'posix' and sys.platform != 'darwin': |
|
175 | if os.name == 'posix' and sys.platform != 'darwin': | |
176 | # test default |
|
176 | # test default | |
177 | os.makedirs(os.path.join(HOME_TEST_DIR, ".cache")) |
|
177 | os.makedirs(os.path.join(HOME_TEST_DIR, ".cache")) | |
178 | with modified_env({'XDG_CACHE_HOME': None}): |
|
178 | with modified_env({'XDG_CACHE_HOME': None}): | |
179 | ipdir = paths.get_ipython_cache_dir() |
|
179 | ipdir = paths.get_ipython_cache_dir() | |
180 | nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"), |
|
180 | nt.assert_equal(os.path.join(HOME_TEST_DIR, ".cache", "ipython"), | |
181 | ipdir) |
|
181 | ipdir) | |
182 | assert_isdir(ipdir) |
|
182 | assert_isdir(ipdir) | |
183 |
|
183 | |||
184 | # test env override |
|
184 | # test env override | |
185 | with modified_env({"XDG_CACHE_HOME": XDG_CACHE_DIR}): |
|
185 | with modified_env({"XDG_CACHE_HOME": XDG_CACHE_DIR}): | |
186 | ipdir = paths.get_ipython_cache_dir() |
|
186 | ipdir = paths.get_ipython_cache_dir() | |
187 | assert_isdir(ipdir) |
|
187 | assert_isdir(ipdir) | |
188 | nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython")) |
|
188 | nt.assert_equal(ipdir, os.path.join(XDG_CACHE_DIR, "ipython")) | |
189 | else: |
|
189 | else: | |
190 | nt.assert_equal(paths.get_ipython_cache_dir(), |
|
190 | nt.assert_equal(paths.get_ipython_cache_dir(), | |
191 | paths.get_ipython_dir()) |
|
191 | paths.get_ipython_dir()) | |
192 |
|
192 | |||
193 | def test_get_ipython_package_dir(): |
|
193 | def test_get_ipython_package_dir(): | |
194 | ipdir = paths.get_ipython_package_dir() |
|
194 | ipdir = paths.get_ipython_package_dir() | |
195 | assert_isdir(ipdir) |
|
195 | assert_isdir(ipdir) | |
196 |
|
196 | |||
197 |
|
197 | |||
198 | def test_get_ipython_module_path(): |
|
198 | def test_get_ipython_module_path(): | |
199 | ipapp_path = paths.get_ipython_module_path('IPython.terminal.ipapp') |
|
199 | ipapp_path = paths.get_ipython_module_path('IPython.terminal.ipapp') | |
200 | assert_isfile(ipapp_path) |
|
200 | assert_isfile(ipapp_path) |
@@ -1,161 +1,161 b'' | |||||
1 | # coding: utf-8 |
|
1 | # coding: utf-8 | |
2 | """Tests for profile-related functions. |
|
2 | """Tests for profile-related functions. | |
3 |
|
3 | |||
4 | Currently only the startup-dir functionality is tested, but more tests should |
|
4 | Currently only the startup-dir functionality is tested, but more tests should | |
5 | be added for: |
|
5 | be added for: | |
6 |
|
6 | |||
7 | * ipython profile create |
|
7 | * ipython profile create | |
8 | * ipython profile list |
|
8 | * ipython profile list | |
9 | * ipython profile create --parallel |
|
9 | * ipython profile create --parallel | |
10 | * security dir permissions |
|
10 | * security dir permissions | |
11 |
|
11 | |||
12 | Authors |
|
12 | Authors | |
13 | ------- |
|
13 | ------- | |
14 |
|
14 | |||
15 | * MinRK |
|
15 | * MinRK | |
16 |
|
16 | |||
17 | """ |
|
17 | """ | |
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 | from unittest import TestCase |
|
28 | from unittest import TestCase | |
29 |
|
29 | |||
30 | import nose.tools as nt |
|
30 | import nose.tools as nt | |
31 |
|
31 | |||
32 | from IPython.core.profileapp import list_profiles_in, list_bundled_profiles |
|
32 | from IPython.core.profileapp import list_profiles_in, list_bundled_profiles | |
33 | from IPython.core.profiledir import ProfileDir |
|
33 | from IPython.core.profiledir import ProfileDir | |
34 |
|
34 | |||
35 | from IPython.testing import decorators as dec |
|
35 | from IPython.testing import decorators as dec | |
36 | from IPython.testing import tools as tt |
|
36 | from IPython.testing import tools as tt | |
37 | from IPython.utils.process import getoutput |
|
37 | from IPython.utils.process import getoutput | |
38 | from IPython.utils.tempdir import TemporaryDirectory |
|
38 | from IPython.utils.tempdir import TemporaryDirectory | |
39 |
|
39 | |||
40 | #----------------------------------------------------------------------------- |
|
40 | #----------------------------------------------------------------------------- | |
41 | # Globals |
|
41 | # Globals | |
42 | #----------------------------------------------------------------------------- |
|
42 | #----------------------------------------------------------------------------- | |
43 | TMP_TEST_DIR = tempfile.mkdtemp() |
|
43 | TMP_TEST_DIR = tempfile.mkdtemp() | |
44 | HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir") |
|
44 | HOME_TEST_DIR = os.path.join(TMP_TEST_DIR, "home_test_dir") | |
45 | IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython') |
|
45 | IP_TEST_DIR = os.path.join(HOME_TEST_DIR,'.ipython') | |
46 |
|
46 | |||
47 | # |
|
47 | # | |
48 | # Setup/teardown functions/decorators |
|
48 | # Setup/teardown functions/decorators | |
49 | # |
|
49 | # | |
50 |
|
50 | |||
51 | def setup(): |
|
51 | def setup_module(): | |
52 | """Setup test environment for the module: |
|
52 | """Setup test environment for the module: | |
53 |
|
53 | |||
54 | - Adds dummy home dir tree |
|
54 | - Adds dummy home dir tree | |
55 | """ |
|
55 | """ | |
56 | # Do not mask exceptions here. In particular, catching WindowsError is a |
|
56 | # Do not mask exceptions here. In particular, catching WindowsError is a | |
57 | # problem because that exception is only defined on Windows... |
|
57 | # problem because that exception is only defined on Windows... | |
58 | os.makedirs(IP_TEST_DIR) |
|
58 | os.makedirs(IP_TEST_DIR) | |
59 |
|
59 | |||
60 |
|
60 | |||
61 | def teardown(): |
|
61 | def teardown_module(): | |
62 | """Teardown test environment for the module: |
|
62 | """Teardown test environment for the module: | |
63 |
|
63 | |||
64 | - Remove dummy home dir tree |
|
64 | - Remove dummy home dir tree | |
65 | """ |
|
65 | """ | |
66 | # Note: we remove the parent test dir, which is the root of all test |
|
66 | # Note: we remove the parent test dir, which is the root of all test | |
67 | # subdirs we may have created. Use shutil instead of os.removedirs, so |
|
67 | # subdirs we may have created. Use shutil instead of os.removedirs, so | |
68 | # that non-empty directories are all recursively removed. |
|
68 | # that non-empty directories are all recursively removed. | |
69 | shutil.rmtree(TMP_TEST_DIR) |
|
69 | shutil.rmtree(TMP_TEST_DIR) | |
70 |
|
70 | |||
71 |
|
71 | |||
72 | #----------------------------------------------------------------------------- |
|
72 | #----------------------------------------------------------------------------- | |
73 | # Test functions |
|
73 | # Test functions | |
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 | def win32_without_pywin32(): |
|
75 | def win32_without_pywin32(): | |
76 | if sys.platform == 'win32': |
|
76 | if sys.platform == 'win32': | |
77 | try: |
|
77 | try: | |
78 | import pywin32 |
|
78 | import pywin32 | |
79 | except ImportError: |
|
79 | except ImportError: | |
80 | return True |
|
80 | return True | |
81 | return False |
|
81 | return False | |
82 |
|
82 | |||
83 |
|
83 | |||
84 | class ProfileStartupTest(TestCase): |
|
84 | class ProfileStartupTest(TestCase): | |
85 | def setUp(self): |
|
85 | def setUp(self): | |
86 | # create profile dir |
|
86 | # create profile dir | |
87 | self.pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, 'test') |
|
87 | self.pd = ProfileDir.create_profile_dir_by_name(IP_TEST_DIR, 'test') | |
88 | self.options = ['--ipython-dir', IP_TEST_DIR, '--profile', 'test'] |
|
88 | self.options = ['--ipython-dir', IP_TEST_DIR, '--profile', 'test'] | |
89 | self.fname = os.path.join(TMP_TEST_DIR, 'test.py') |
|
89 | self.fname = os.path.join(TMP_TEST_DIR, 'test.py') | |
90 |
|
90 | |||
91 | def tearDown(self): |
|
91 | def tearDown(self): | |
92 | # We must remove this profile right away so its presence doesn't |
|
92 | # We must remove this profile right away so its presence doesn't | |
93 | # confuse other tests. |
|
93 | # confuse other tests. | |
94 | shutil.rmtree(self.pd.location) |
|
94 | shutil.rmtree(self.pd.location) | |
95 |
|
95 | |||
96 | def init(self, startup_file, startup, test): |
|
96 | def init(self, startup_file, startup, test): | |
97 | # write startup python file |
|
97 | # write startup python file | |
98 | with open(os.path.join(self.pd.startup_dir, startup_file), 'w') as f: |
|
98 | with open(os.path.join(self.pd.startup_dir, startup_file), 'w') as f: | |
99 | f.write(startup) |
|
99 | f.write(startup) | |
100 | # write simple test file, to check that the startup file was run |
|
100 | # write simple test file, to check that the startup file was run | |
101 | with open(self.fname, 'w') as f: |
|
101 | with open(self.fname, 'w') as f: | |
102 | f.write(test) |
|
102 | f.write(test) | |
103 |
|
103 | |||
104 | def validate(self, output): |
|
104 | def validate(self, output): | |
105 | tt.ipexec_validate(self.fname, output, '', options=self.options) |
|
105 | tt.ipexec_validate(self.fname, output, '', options=self.options) | |
106 |
|
106 | |||
107 | @dec.skipif(win32_without_pywin32(), "Test requires pywin32 on Windows") |
|
107 | @dec.skipif(win32_without_pywin32(), "Test requires pywin32 on Windows") | |
108 | def test_startup_py(self): |
|
108 | def test_startup_py(self): | |
109 | self.init('00-start.py', 'zzz=123\n', 'print(zzz)\n') |
|
109 | self.init('00-start.py', 'zzz=123\n', 'print(zzz)\n') | |
110 | self.validate('123') |
|
110 | self.validate('123') | |
111 |
|
111 | |||
112 | @dec.skipif(win32_without_pywin32(), "Test requires pywin32 on Windows") |
|
112 | @dec.skipif(win32_without_pywin32(), "Test requires pywin32 on Windows") | |
113 | def test_startup_ipy(self): |
|
113 | def test_startup_ipy(self): | |
114 | self.init('00-start.ipy', '%xmode plain\n', '') |
|
114 | self.init('00-start.ipy', '%xmode plain\n', '') | |
115 | self.validate('Exception reporting mode: Plain') |
|
115 | self.validate('Exception reporting mode: Plain') | |
116 |
|
116 | |||
117 |
|
117 | |||
118 | def test_list_profiles_in(): |
|
118 | def test_list_profiles_in(): | |
119 | # No need to remove these directories and files, as they will get nuked in |
|
119 | # No need to remove these directories and files, as they will get nuked in | |
120 | # the module-level teardown. |
|
120 | # the module-level teardown. | |
121 | td = tempfile.mkdtemp(dir=TMP_TEST_DIR) |
|
121 | td = tempfile.mkdtemp(dir=TMP_TEST_DIR) | |
122 | for name in ('profile_foo', 'profile_hello', 'not_a_profile'): |
|
122 | for name in ('profile_foo', 'profile_hello', 'not_a_profile'): | |
123 | os.mkdir(os.path.join(td, name)) |
|
123 | os.mkdir(os.path.join(td, name)) | |
124 | if dec.unicode_paths: |
|
124 | if dec.unicode_paths: | |
125 | os.mkdir(os.path.join(td, u'profile_ΓΌnicode')) |
|
125 | os.mkdir(os.path.join(td, u'profile_ΓΌnicode')) | |
126 |
|
126 | |||
127 | with open(os.path.join(td, 'profile_file'), 'w') as f: |
|
127 | with open(os.path.join(td, 'profile_file'), 'w') as f: | |
128 | f.write("I am not a profile directory") |
|
128 | f.write("I am not a profile directory") | |
129 | profiles = list_profiles_in(td) |
|
129 | profiles = list_profiles_in(td) | |
130 |
|
130 | |||
131 | # unicode normalization can turn u'ΓΌnicode' into u'u\0308nicode', |
|
131 | # unicode normalization can turn u'ΓΌnicode' into u'u\0308nicode', | |
132 | # so only check for *nicode, and that creating a ProfileDir from the |
|
132 | # so only check for *nicode, and that creating a ProfileDir from the | |
133 | # name remains valid |
|
133 | # name remains valid | |
134 | found_unicode = False |
|
134 | found_unicode = False | |
135 | for p in list(profiles): |
|
135 | for p in list(profiles): | |
136 | if p.endswith('nicode'): |
|
136 | if p.endswith('nicode'): | |
137 | pd = ProfileDir.find_profile_dir_by_name(td, p) |
|
137 | pd = ProfileDir.find_profile_dir_by_name(td, p) | |
138 | profiles.remove(p) |
|
138 | profiles.remove(p) | |
139 | found_unicode = True |
|
139 | found_unicode = True | |
140 | break |
|
140 | break | |
141 | if dec.unicode_paths: |
|
141 | if dec.unicode_paths: | |
142 | nt.assert_true(found_unicode) |
|
142 | nt.assert_true(found_unicode) | |
143 | nt.assert_equal(set(profiles), {'foo', 'hello'}) |
|
143 | nt.assert_equal(set(profiles), {'foo', 'hello'}) | |
144 |
|
144 | |||
145 |
|
145 | |||
146 | def test_list_bundled_profiles(): |
|
146 | def test_list_bundled_profiles(): | |
147 | # This variable will need to be updated when a new profile gets bundled |
|
147 | # This variable will need to be updated when a new profile gets bundled | |
148 | bundled = sorted(list_bundled_profiles()) |
|
148 | bundled = sorted(list_bundled_profiles()) | |
149 | nt.assert_equal(bundled, []) |
|
149 | nt.assert_equal(bundled, []) | |
150 |
|
150 | |||
151 |
|
151 | |||
152 | def test_profile_create_ipython_dir(): |
|
152 | def test_profile_create_ipython_dir(): | |
153 | """ipython profile create respects --ipython-dir""" |
|
153 | """ipython profile create respects --ipython-dir""" | |
154 | with TemporaryDirectory() as td: |
|
154 | with TemporaryDirectory() as td: | |
155 | getoutput([sys.executable, '-m', 'IPython', 'profile', 'create', |
|
155 | getoutput([sys.executable, '-m', 'IPython', 'profile', 'create', | |
156 | 'foo', '--ipython-dir=%s' % td]) |
|
156 | 'foo', '--ipython-dir=%s' % td]) | |
157 | profile_dir = os.path.join(td, 'profile_foo') |
|
157 | profile_dir = os.path.join(td, 'profile_foo') | |
158 | assert os.path.exists(profile_dir) |
|
158 | assert os.path.exists(profile_dir) | |
159 | ipython_config = os.path.join(profile_dir, 'ipython_config.py') |
|
159 | ipython_config = os.path.join(profile_dir, 'ipython_config.py') | |
160 | assert os.path.exists(ipython_config) |
|
160 | assert os.path.exists(ipython_config) | |
161 |
|
161 |
@@ -1,114 +1,114 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Tests for IPython.utils.module_paths.py""" |
|
2 | """Tests for IPython.utils.module_paths.py""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2008-2011 The IPython Development Team |
|
5 | # Copyright (C) 2008-2011 The IPython Development Team | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | # Distributed under the terms of the BSD License. The full license is in | |
8 | # the file COPYING, distributed as part of this software. |
|
8 | # the file COPYING, distributed as part of this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 |
|
14 | |||
15 |
|
15 | |||
16 | import os |
|
16 | import os | |
17 | import shutil |
|
17 | import shutil | |
18 | import sys |
|
18 | import sys | |
19 | import tempfile |
|
19 | import tempfile | |
20 |
|
20 | |||
21 | from os.path import join, abspath, split |
|
21 | from os.path import join, abspath, split | |
22 |
|
22 | |||
23 | from IPython.testing.tools import make_tempfile |
|
23 | from IPython.testing.tools import make_tempfile | |
24 |
|
24 | |||
25 | import IPython.utils.module_paths as mp |
|
25 | import IPython.utils.module_paths as mp | |
26 |
|
26 | |||
27 | import nose.tools as nt |
|
27 | import nose.tools as nt | |
28 |
|
28 | |||
29 | env = os.environ |
|
29 | env = os.environ | |
30 | TEST_FILE_PATH = split(abspath(__file__))[0] |
|
30 | TEST_FILE_PATH = split(abspath(__file__))[0] | |
31 |
|
31 | |||
32 | TMP_TEST_DIR = tempfile.mkdtemp(suffix='with.dot') |
|
32 | TMP_TEST_DIR = tempfile.mkdtemp(suffix='with.dot') | |
33 | # |
|
33 | # | |
34 | # Setup/teardown functions/decorators |
|
34 | # Setup/teardown functions/decorators | |
35 | # |
|
35 | # | |
36 |
|
36 | |||
37 | old_syspath = sys.path |
|
37 | old_syspath = sys.path | |
38 |
|
38 | |||
39 | def make_empty_file(fname): |
|
39 | def make_empty_file(fname): | |
40 | open(fname, 'w').close() |
|
40 | open(fname, 'w').close() | |
41 |
|
41 | |||
42 |
|
42 | |||
43 | def setup(): |
|
43 | def setup_module(): | |
44 | """Setup testenvironment for the module: |
|
44 | """Setup testenvironment for the module: | |
45 |
|
45 | |||
46 | """ |
|
46 | """ | |
47 | # Do not mask exceptions here. In particular, catching WindowsError is a |
|
47 | # Do not mask exceptions here. In particular, catching WindowsError is a | |
48 | # problem because that exception is only defined on Windows... |
|
48 | # problem because that exception is only defined on Windows... | |
49 | os.makedirs(join(TMP_TEST_DIR, "xmod")) |
|
49 | os.makedirs(join(TMP_TEST_DIR, "xmod")) | |
50 | os.makedirs(join(TMP_TEST_DIR, "nomod")) |
|
50 | os.makedirs(join(TMP_TEST_DIR, "nomod")) | |
51 | make_empty_file(join(TMP_TEST_DIR, "xmod/__init__.py")) |
|
51 | make_empty_file(join(TMP_TEST_DIR, "xmod/__init__.py")) | |
52 | make_empty_file(join(TMP_TEST_DIR, "xmod/sub.py")) |
|
52 | make_empty_file(join(TMP_TEST_DIR, "xmod/sub.py")) | |
53 | make_empty_file(join(TMP_TEST_DIR, "pack.py")) |
|
53 | make_empty_file(join(TMP_TEST_DIR, "pack.py")) | |
54 | make_empty_file(join(TMP_TEST_DIR, "packpyc.pyc")) |
|
54 | make_empty_file(join(TMP_TEST_DIR, "packpyc.pyc")) | |
55 | sys.path = [TMP_TEST_DIR] |
|
55 | sys.path = [TMP_TEST_DIR] | |
56 |
|
56 | |||
57 | def teardown(): |
|
57 | def teardown_module(): | |
58 | """Teardown testenvironment for the module: |
|
58 | """Teardown testenvironment for the module: | |
59 |
|
59 | |||
60 | - Remove tempdir |
|
60 | - Remove tempdir | |
61 | - restore sys.path |
|
61 | - restore sys.path | |
62 | """ |
|
62 | """ | |
63 | # Note: we remove the parent test dir, which is the root of all test |
|
63 | # Note: we remove the parent test dir, which is the root of all test | |
64 | # subdirs we may have created. Use shutil instead of os.removedirs, so |
|
64 | # subdirs we may have created. Use shutil instead of os.removedirs, so | |
65 | # that non-empty directories are all recursively removed. |
|
65 | # that non-empty directories are all recursively removed. | |
66 | shutil.rmtree(TMP_TEST_DIR) |
|
66 | shutil.rmtree(TMP_TEST_DIR) | |
67 | sys.path = old_syspath |
|
67 | sys.path = old_syspath | |
68 |
|
68 | |||
69 | def test_tempdir(): |
|
69 | def test_tempdir(): | |
70 | """ |
|
70 | """ | |
71 | Ensure the test are done with a temporary file that have a dot somewhere. |
|
71 | Ensure the test are done with a temporary file that have a dot somewhere. | |
72 | """ |
|
72 | """ | |
73 | nt.assert_in('.',TMP_TEST_DIR) |
|
73 | nt.assert_in('.',TMP_TEST_DIR) | |
74 |
|
74 | |||
75 |
|
75 | |||
76 | def test_find_mod_1(): |
|
76 | def test_find_mod_1(): | |
77 | """ |
|
77 | """ | |
78 | Search for a directory's file path. |
|
78 | Search for a directory's file path. | |
79 | Expected output: a path to that directory's __init__.py file. |
|
79 | Expected output: a path to that directory's __init__.py file. | |
80 | """ |
|
80 | """ | |
81 | modpath = join(TMP_TEST_DIR, "xmod", "__init__.py") |
|
81 | modpath = join(TMP_TEST_DIR, "xmod", "__init__.py") | |
82 | nt.assert_equal(mp.find_mod("xmod"), modpath) |
|
82 | nt.assert_equal(mp.find_mod("xmod"), modpath) | |
83 |
|
83 | |||
84 | def test_find_mod_2(): |
|
84 | def test_find_mod_2(): | |
85 | """ |
|
85 | """ | |
86 | Search for a directory's file path. |
|
86 | Search for a directory's file path. | |
87 | Expected output: a path to that directory's __init__.py file. |
|
87 | Expected output: a path to that directory's __init__.py file. | |
88 | TODO: Confirm why this is a duplicate test. |
|
88 | TODO: Confirm why this is a duplicate test. | |
89 | """ |
|
89 | """ | |
90 | modpath = join(TMP_TEST_DIR, "xmod", "__init__.py") |
|
90 | modpath = join(TMP_TEST_DIR, "xmod", "__init__.py") | |
91 | nt.assert_equal(mp.find_mod("xmod"), modpath) |
|
91 | nt.assert_equal(mp.find_mod("xmod"), modpath) | |
92 |
|
92 | |||
93 | def test_find_mod_3(): |
|
93 | def test_find_mod_3(): | |
94 | """ |
|
94 | """ | |
95 | Search for a directory + a filename without its .py extension |
|
95 | Search for a directory + a filename without its .py extension | |
96 | Expected output: full path with .py extension. |
|
96 | Expected output: full path with .py extension. | |
97 | """ |
|
97 | """ | |
98 | modpath = join(TMP_TEST_DIR, "xmod", "sub.py") |
|
98 | modpath = join(TMP_TEST_DIR, "xmod", "sub.py") | |
99 | nt.assert_equal(mp.find_mod("xmod.sub"), modpath) |
|
99 | nt.assert_equal(mp.find_mod("xmod.sub"), modpath) | |
100 |
|
100 | |||
101 | def test_find_mod_4(): |
|
101 | def test_find_mod_4(): | |
102 | """ |
|
102 | """ | |
103 | Search for a filename without its .py extension |
|
103 | Search for a filename without its .py extension | |
104 | Expected output: full path with .py extension |
|
104 | Expected output: full path with .py extension | |
105 | """ |
|
105 | """ | |
106 | modpath = join(TMP_TEST_DIR, "pack.py") |
|
106 | modpath = join(TMP_TEST_DIR, "pack.py") | |
107 | nt.assert_equal(mp.find_mod("pack"), modpath) |
|
107 | nt.assert_equal(mp.find_mod("pack"), modpath) | |
108 |
|
108 | |||
109 | def test_find_mod_5(): |
|
109 | def test_find_mod_5(): | |
110 | """ |
|
110 | """ | |
111 | Search for a filename with a .pyc extension |
|
111 | Search for a filename with a .pyc extension | |
112 | Expected output: TODO: do we exclude or include .pyc files? |
|
112 | Expected output: TODO: do we exclude or include .pyc files? | |
113 | """ |
|
113 | """ | |
114 | nt.assert_equal(mp.find_mod("packpyc"), None) |
|
114 | nt.assert_equal(mp.find_mod("packpyc"), None) |
@@ -1,481 +1,481 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Tests for IPython.utils.path.py""" |
|
2 | """Tests for IPython.utils.path.py""" | |
3 |
|
3 | |||
4 | # Copyright (c) IPython Development Team. |
|
4 | # Copyright (c) IPython Development Team. | |
5 | # Distributed under the terms of the Modified BSD License. |
|
5 | # Distributed under the terms of the Modified BSD License. | |
6 |
|
6 | |||
7 | import os |
|
7 | import os | |
8 | import shutil |
|
8 | import shutil | |
9 | import sys |
|
9 | import sys | |
10 | import tempfile |
|
10 | import tempfile | |
11 | import unittest |
|
11 | import unittest | |
12 | from contextlib import contextmanager |
|
12 | from contextlib import contextmanager | |
13 | from unittest.mock import patch |
|
13 | from unittest.mock import patch | |
14 | from os.path import join, abspath |
|
14 | 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 nose.tools as nt | |
19 |
|
19 | |||
20 | import IPython |
|
20 | import IPython | |
21 | from IPython import paths |
|
21 | from IPython import paths | |
22 | from IPython.testing import decorators as dec |
|
22 | from IPython.testing import decorators as dec | |
23 | from IPython.testing.decorators import (skip_if_not_win32, skip_win32, |
|
23 | from IPython.testing.decorators import (skip_if_not_win32, skip_win32, | |
24 | onlyif_unicode_paths,) |
|
24 | onlyif_unicode_paths,) | |
25 | from IPython.testing.tools import make_tempfile, AssertPrints |
|
25 | from IPython.testing.tools import make_tempfile, AssertPrints | |
26 | from IPython.utils import path |
|
26 | from IPython.utils import path | |
27 | from IPython.utils.tempdir import TemporaryDirectory |
|
27 | from IPython.utils.tempdir import TemporaryDirectory | |
28 |
|
28 | |||
29 | # Platform-dependent imports |
|
29 | # Platform-dependent imports | |
30 | try: |
|
30 | try: | |
31 | import winreg as wreg |
|
31 | import winreg as wreg | |
32 | except ImportError: |
|
32 | except ImportError: | |
33 | #Fake _winreg module on non-windows platforms |
|
33 | #Fake _winreg module on non-windows platforms | |
34 | import types |
|
34 | import types | |
35 | wr_name = "winreg" |
|
35 | wr_name = "winreg" | |
36 | sys.modules[wr_name] = types.ModuleType(wr_name) |
|
36 | sys.modules[wr_name] = types.ModuleType(wr_name) | |
37 | try: |
|
37 | try: | |
38 | import winreg as wreg |
|
38 | import winreg as wreg | |
39 | except ImportError: |
|
39 | except ImportError: | |
40 | import _winreg as wreg |
|
40 | import _winreg as wreg | |
41 | #Add entries that needs to be stubbed by the testing code |
|
41 | #Add entries that needs to be stubbed by the testing code | |
42 | (wreg.OpenKey, wreg.QueryValueEx,) = (None, None) |
|
42 | (wreg.OpenKey, wreg.QueryValueEx,) = (None, None) | |
43 |
|
43 | |||
44 | #----------------------------------------------------------------------------- |
|
44 | #----------------------------------------------------------------------------- | |
45 | # Globals |
|
45 | # Globals | |
46 | #----------------------------------------------------------------------------- |
|
46 | #----------------------------------------------------------------------------- | |
47 | env = os.environ |
|
47 | env = os.environ | |
48 | TMP_TEST_DIR = tempfile.mkdtemp() |
|
48 | TMP_TEST_DIR = tempfile.mkdtemp() | |
49 | HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir") |
|
49 | HOME_TEST_DIR = join(TMP_TEST_DIR, "home_test_dir") | |
50 | # |
|
50 | # | |
51 | # Setup/teardown functions/decorators |
|
51 | # Setup/teardown functions/decorators | |
52 | # |
|
52 | # | |
53 |
|
53 | |||
54 | def setup(): |
|
54 | def setup_module(): | |
55 | """Setup testenvironment for the module: |
|
55 | """Setup testenvironment for the module: | |
56 |
|
56 | |||
57 | - Adds dummy home dir tree |
|
57 | - Adds dummy home dir tree | |
58 | """ |
|
58 | """ | |
59 | # Do not mask exceptions here. In particular, catching WindowsError is a |
|
59 | # Do not mask exceptions here. In particular, catching WindowsError is a | |
60 | # problem because that exception is only defined on Windows... |
|
60 | # problem because that exception is only defined on Windows... | |
61 | os.makedirs(os.path.join(HOME_TEST_DIR, 'ipython')) |
|
61 | os.makedirs(os.path.join(HOME_TEST_DIR, 'ipython')) | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | def teardown(): |
|
64 | def teardown_module(): | |
65 | """Teardown testenvironment for the module: |
|
65 | """Teardown testenvironment for the module: | |
66 |
|
66 | |||
67 | - Remove dummy home dir tree |
|
67 | - Remove dummy home dir tree | |
68 | """ |
|
68 | """ | |
69 | # Note: we remove the parent test dir, which is the root of all test |
|
69 | # Note: we remove the parent test dir, which is the root of all test | |
70 | # subdirs we may have created. Use shutil instead of os.removedirs, so |
|
70 | # subdirs we may have created. Use shutil instead of os.removedirs, so | |
71 | # that non-empty directories are all recursively removed. |
|
71 | # that non-empty directories are all recursively removed. | |
72 | shutil.rmtree(TMP_TEST_DIR) |
|
72 | shutil.rmtree(TMP_TEST_DIR) | |
73 |
|
73 | |||
74 |
|
74 | |||
75 | def setup_environment(): |
|
75 | def setup_environment(): | |
76 | """Setup testenvironment for some functions that are tested |
|
76 | """Setup testenvironment for some functions that are tested | |
77 | in this module. In particular this functions stores attributes |
|
77 | in this module. In particular this functions stores attributes | |
78 | and other things that we need to stub in some test functions. |
|
78 | and other things that we need to stub in some test functions. | |
79 | This needs to be done on a function level and not module level because |
|
79 | This needs to be done on a function level and not module level because | |
80 | each testfunction needs a pristine environment. |
|
80 | each testfunction needs a pristine environment. | |
81 | """ |
|
81 | """ | |
82 | global oldstuff, platformstuff |
|
82 | global oldstuff, platformstuff | |
83 | oldstuff = (env.copy(), os.name, sys.platform, path.get_home_dir, IPython.__file__, os.getcwd()) |
|
83 | oldstuff = (env.copy(), os.name, sys.platform, path.get_home_dir, IPython.__file__, os.getcwd()) | |
84 |
|
84 | |||
85 | def teardown_environment(): |
|
85 | def teardown_environment(): | |
86 | """Restore things that were remembered by the setup_environment function |
|
86 | """Restore things that were remembered by the setup_environment function | |
87 | """ |
|
87 | """ | |
88 | (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff |
|
88 | (oldenv, os.name, sys.platform, path.get_home_dir, IPython.__file__, old_wd) = oldstuff | |
89 | os.chdir(old_wd) |
|
89 | os.chdir(old_wd) | |
90 | reload(path) |
|
90 | reload(path) | |
91 |
|
91 | |||
92 | for key in list(env): |
|
92 | for key in list(env): | |
93 | if key not in oldenv: |
|
93 | if key not in oldenv: | |
94 | del env[key] |
|
94 | del env[key] | |
95 | env.update(oldenv) |
|
95 | env.update(oldenv) | |
96 | if hasattr(sys, 'frozen'): |
|
96 | if hasattr(sys, 'frozen'): | |
97 | del sys.frozen |
|
97 | del sys.frozen | |
98 |
|
98 | |||
99 | # Build decorator that uses the setup_environment/setup_environment |
|
99 | # Build decorator that uses the setup_environment/setup_environment | |
100 | with_environment = with_setup(setup_environment, teardown_environment) |
|
100 | with_environment = with_setup(setup_environment, teardown_environment) | |
101 |
|
101 | |||
102 | @skip_if_not_win32 |
|
102 | @skip_if_not_win32 | |
103 | @with_environment |
|
103 | @with_environment | |
104 | def test_get_home_dir_1(): |
|
104 | def test_get_home_dir_1(): | |
105 | """Testcase for py2exe logic, un-compressed lib |
|
105 | """Testcase for py2exe logic, un-compressed lib | |
106 | """ |
|
106 | """ | |
107 | unfrozen = path.get_home_dir() |
|
107 | unfrozen = path.get_home_dir() | |
108 | sys.frozen = True |
|
108 | sys.frozen = True | |
109 |
|
109 | |||
110 | #fake filename for IPython.__init__ |
|
110 | #fake filename for IPython.__init__ | |
111 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py")) |
|
111 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Lib/IPython/__init__.py")) | |
112 |
|
112 | |||
113 | home_dir = path.get_home_dir() |
|
113 | home_dir = path.get_home_dir() | |
114 | nt.assert_equal(home_dir, unfrozen) |
|
114 | nt.assert_equal(home_dir, unfrozen) | |
115 |
|
115 | |||
116 |
|
116 | |||
117 | @skip_if_not_win32 |
|
117 | @skip_if_not_win32 | |
118 | @with_environment |
|
118 | @with_environment | |
119 | def test_get_home_dir_2(): |
|
119 | def test_get_home_dir_2(): | |
120 | """Testcase for py2exe logic, compressed lib |
|
120 | """Testcase for py2exe logic, compressed lib | |
121 | """ |
|
121 | """ | |
122 | unfrozen = path.get_home_dir() |
|
122 | unfrozen = path.get_home_dir() | |
123 | sys.frozen = True |
|
123 | sys.frozen = True | |
124 | #fake filename for IPython.__init__ |
|
124 | #fake filename for IPython.__init__ | |
125 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower() |
|
125 | IPython.__file__ = abspath(join(HOME_TEST_DIR, "Library.zip/IPython/__init__.py")).lower() | |
126 |
|
126 | |||
127 | home_dir = path.get_home_dir(True) |
|
127 | home_dir = path.get_home_dir(True) | |
128 | nt.assert_equal(home_dir, unfrozen) |
|
128 | nt.assert_equal(home_dir, unfrozen) | |
129 |
|
129 | |||
130 |
|
130 | |||
131 | @with_environment |
|
131 | @with_environment | |
132 | def test_get_home_dir_3(): |
|
132 | def test_get_home_dir_3(): | |
133 | """get_home_dir() uses $HOME if set""" |
|
133 | """get_home_dir() uses $HOME if set""" | |
134 | env["HOME"] = HOME_TEST_DIR |
|
134 | env["HOME"] = HOME_TEST_DIR | |
135 | home_dir = path.get_home_dir(True) |
|
135 | home_dir = path.get_home_dir(True) | |
136 | # get_home_dir expands symlinks |
|
136 | # get_home_dir expands symlinks | |
137 | nt.assert_equal(home_dir, os.path.realpath(env["HOME"])) |
|
137 | nt.assert_equal(home_dir, os.path.realpath(env["HOME"])) | |
138 |
|
138 | |||
139 |
|
139 | |||
140 | @with_environment |
|
140 | @with_environment | |
141 | def test_get_home_dir_4(): |
|
141 | def test_get_home_dir_4(): | |
142 | """get_home_dir() still works if $HOME is not set""" |
|
142 | """get_home_dir() still works if $HOME is not set""" | |
143 |
|
143 | |||
144 | if 'HOME' in env: del env['HOME'] |
|
144 | if 'HOME' in env: del env['HOME'] | |
145 | # this should still succeed, but we don't care what the answer is |
|
145 | # this should still succeed, but we don't care what the answer is | |
146 | home = path.get_home_dir(False) |
|
146 | home = path.get_home_dir(False) | |
147 |
|
147 | |||
148 | @with_environment |
|
148 | @with_environment | |
149 | def test_get_home_dir_5(): |
|
149 | def test_get_home_dir_5(): | |
150 | """raise HomeDirError if $HOME is specified, but not a writable dir""" |
|
150 | """raise HomeDirError if $HOME is specified, but not a writable dir""" | |
151 | env['HOME'] = abspath(HOME_TEST_DIR+'garbage') |
|
151 | env['HOME'] = abspath(HOME_TEST_DIR+'garbage') | |
152 | # set os.name = posix, to prevent My Documents fallback on Windows |
|
152 | # set os.name = posix, to prevent My Documents fallback on Windows | |
153 | os.name = 'posix' |
|
153 | os.name = 'posix' | |
154 | nt.assert_raises(path.HomeDirError, path.get_home_dir, True) |
|
154 | nt.assert_raises(path.HomeDirError, path.get_home_dir, True) | |
155 |
|
155 | |||
156 | # Should we stub wreg fully so we can run the test on all platforms? |
|
156 | # Should we stub wreg fully so we can run the test on all platforms? | |
157 | @skip_if_not_win32 |
|
157 | @skip_if_not_win32 | |
158 | @with_environment |
|
158 | @with_environment | |
159 | def test_get_home_dir_8(): |
|
159 | def test_get_home_dir_8(): | |
160 | """Using registry hack for 'My Documents', os=='nt' |
|
160 | """Using registry hack for 'My Documents', os=='nt' | |
161 |
|
161 | |||
162 | HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing. |
|
162 | HOMESHARE, HOMEDRIVE, HOMEPATH, USERPROFILE and others are missing. | |
163 | """ |
|
163 | """ | |
164 | os.name = 'nt' |
|
164 | os.name = 'nt' | |
165 | # Remove from stub environment all keys that may be set |
|
165 | # Remove from stub environment all keys that may be set | |
166 | for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']: |
|
166 | for key in ['HOME', 'HOMESHARE', 'HOMEDRIVE', 'HOMEPATH', 'USERPROFILE']: | |
167 | env.pop(key, None) |
|
167 | env.pop(key, None) | |
168 |
|
168 | |||
169 | class key: |
|
169 | class key: | |
170 | def Close(self): |
|
170 | def Close(self): | |
171 | pass |
|
171 | pass | |
172 |
|
172 | |||
173 | with patch.object(wreg, 'OpenKey', return_value=key()), \ |
|
173 | with patch.object(wreg, 'OpenKey', return_value=key()), \ | |
174 | patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]): |
|
174 | patch.object(wreg, 'QueryValueEx', return_value=[abspath(HOME_TEST_DIR)]): | |
175 | home_dir = path.get_home_dir() |
|
175 | home_dir = path.get_home_dir() | |
176 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) |
|
176 | nt.assert_equal(home_dir, abspath(HOME_TEST_DIR)) | |
177 |
|
177 | |||
178 | @with_environment |
|
178 | @with_environment | |
179 | def test_get_xdg_dir_0(): |
|
179 | def test_get_xdg_dir_0(): | |
180 | """test_get_xdg_dir_0, check xdg_dir""" |
|
180 | """test_get_xdg_dir_0, check xdg_dir""" | |
181 | reload(path) |
|
181 | reload(path) | |
182 | path._writable_dir = lambda path: True |
|
182 | path._writable_dir = lambda path: True | |
183 | path.get_home_dir = lambda : 'somewhere' |
|
183 | path.get_home_dir = lambda : 'somewhere' | |
184 | os.name = "posix" |
|
184 | os.name = "posix" | |
185 | sys.platform = "linux2" |
|
185 | sys.platform = "linux2" | |
186 | env.pop('IPYTHON_DIR', None) |
|
186 | env.pop('IPYTHON_DIR', None) | |
187 | env.pop('IPYTHONDIR', None) |
|
187 | env.pop('IPYTHONDIR', None) | |
188 | env.pop('XDG_CONFIG_HOME', None) |
|
188 | env.pop('XDG_CONFIG_HOME', None) | |
189 |
|
189 | |||
190 | nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config')) |
|
190 | nt.assert_equal(path.get_xdg_dir(), os.path.join('somewhere', '.config')) | |
191 |
|
191 | |||
192 |
|
192 | |||
193 | @with_environment |
|
193 | @with_environment | |
194 | def test_get_xdg_dir_1(): |
|
194 | def test_get_xdg_dir_1(): | |
195 | """test_get_xdg_dir_1, check nonexistent xdg_dir""" |
|
195 | """test_get_xdg_dir_1, check nonexistent xdg_dir""" | |
196 | reload(path) |
|
196 | reload(path) | |
197 | path.get_home_dir = lambda : HOME_TEST_DIR |
|
197 | path.get_home_dir = lambda : HOME_TEST_DIR | |
198 | os.name = "posix" |
|
198 | os.name = "posix" | |
199 | sys.platform = "linux2" |
|
199 | sys.platform = "linux2" | |
200 | env.pop('IPYTHON_DIR', None) |
|
200 | env.pop('IPYTHON_DIR', None) | |
201 | env.pop('IPYTHONDIR', None) |
|
201 | env.pop('IPYTHONDIR', None) | |
202 | env.pop('XDG_CONFIG_HOME', None) |
|
202 | env.pop('XDG_CONFIG_HOME', None) | |
203 | nt.assert_equal(path.get_xdg_dir(), None) |
|
203 | nt.assert_equal(path.get_xdg_dir(), None) | |
204 |
|
204 | |||
205 | @with_environment |
|
205 | @with_environment | |
206 | def test_get_xdg_dir_2(): |
|
206 | def test_get_xdg_dir_2(): | |
207 | """test_get_xdg_dir_2, check xdg_dir default to ~/.config""" |
|
207 | """test_get_xdg_dir_2, check xdg_dir default to ~/.config""" | |
208 | reload(path) |
|
208 | reload(path) | |
209 | path.get_home_dir = lambda : HOME_TEST_DIR |
|
209 | path.get_home_dir = lambda : HOME_TEST_DIR | |
210 | os.name = "posix" |
|
210 | os.name = "posix" | |
211 | sys.platform = "linux2" |
|
211 | sys.platform = "linux2" | |
212 | env.pop('IPYTHON_DIR', None) |
|
212 | env.pop('IPYTHON_DIR', None) | |
213 | env.pop('IPYTHONDIR', None) |
|
213 | env.pop('IPYTHONDIR', None) | |
214 | env.pop('XDG_CONFIG_HOME', None) |
|
214 | env.pop('XDG_CONFIG_HOME', None) | |
215 | cfgdir=os.path.join(path.get_home_dir(), '.config') |
|
215 | cfgdir=os.path.join(path.get_home_dir(), '.config') | |
216 | if not os.path.exists(cfgdir): |
|
216 | if not os.path.exists(cfgdir): | |
217 | os.makedirs(cfgdir) |
|
217 | os.makedirs(cfgdir) | |
218 |
|
218 | |||
219 | nt.assert_equal(path.get_xdg_dir(), cfgdir) |
|
219 | nt.assert_equal(path.get_xdg_dir(), cfgdir) | |
220 |
|
220 | |||
221 | @with_environment |
|
221 | @with_environment | |
222 | def test_get_xdg_dir_3(): |
|
222 | def test_get_xdg_dir_3(): | |
223 | """test_get_xdg_dir_3, check xdg_dir not used on OS X""" |
|
223 | """test_get_xdg_dir_3, check xdg_dir not used on OS X""" | |
224 | reload(path) |
|
224 | reload(path) | |
225 | path.get_home_dir = lambda : HOME_TEST_DIR |
|
225 | path.get_home_dir = lambda : HOME_TEST_DIR | |
226 | os.name = "posix" |
|
226 | os.name = "posix" | |
227 | sys.platform = "darwin" |
|
227 | sys.platform = "darwin" | |
228 | env.pop('IPYTHON_DIR', None) |
|
228 | env.pop('IPYTHON_DIR', None) | |
229 | env.pop('IPYTHONDIR', None) |
|
229 | env.pop('IPYTHONDIR', None) | |
230 | env.pop('XDG_CONFIG_HOME', None) |
|
230 | env.pop('XDG_CONFIG_HOME', None) | |
231 | cfgdir=os.path.join(path.get_home_dir(), '.config') |
|
231 | cfgdir=os.path.join(path.get_home_dir(), '.config') | |
232 | if not os.path.exists(cfgdir): |
|
232 | if not os.path.exists(cfgdir): | |
233 | os.makedirs(cfgdir) |
|
233 | os.makedirs(cfgdir) | |
234 |
|
234 | |||
235 | nt.assert_equal(path.get_xdg_dir(), None) |
|
235 | nt.assert_equal(path.get_xdg_dir(), None) | |
236 |
|
236 | |||
237 | def test_filefind(): |
|
237 | def test_filefind(): | |
238 | """Various tests for filefind""" |
|
238 | """Various tests for filefind""" | |
239 | f = tempfile.NamedTemporaryFile() |
|
239 | f = tempfile.NamedTemporaryFile() | |
240 | # print 'fname:',f.name |
|
240 | # print 'fname:',f.name | |
241 | alt_dirs = paths.get_ipython_dir() |
|
241 | alt_dirs = paths.get_ipython_dir() | |
242 | t = path.filefind(f.name, alt_dirs) |
|
242 | t = path.filefind(f.name, alt_dirs) | |
243 | # print 'found:',t |
|
243 | # print 'found:',t | |
244 |
|
244 | |||
245 |
|
245 | |||
246 | @dec.skip_if_not_win32 |
|
246 | @dec.skip_if_not_win32 | |
247 | def test_get_long_path_name_win32(): |
|
247 | def test_get_long_path_name_win32(): | |
248 | with TemporaryDirectory() as tmpdir: |
|
248 | with TemporaryDirectory() as tmpdir: | |
249 |
|
249 | |||
250 | # Make a long path. Expands the path of tmpdir prematurely as it may already have a long |
|
250 | # Make a long path. Expands the path of tmpdir prematurely as it may already have a long | |
251 | # path component, so ensure we include the long form of it |
|
251 | # path component, so ensure we include the long form of it | |
252 | long_path = os.path.join(path.get_long_path_name(tmpdir), 'this is my long path name') |
|
252 | long_path = os.path.join(path.get_long_path_name(tmpdir), 'this is my long path name') | |
253 | os.makedirs(long_path) |
|
253 | os.makedirs(long_path) | |
254 |
|
254 | |||
255 | # Test to see if the short path evaluates correctly. |
|
255 | # Test to see if the short path evaluates correctly. | |
256 | short_path = os.path.join(tmpdir, 'THISIS~1') |
|
256 | short_path = os.path.join(tmpdir, 'THISIS~1') | |
257 | evaluated_path = path.get_long_path_name(short_path) |
|
257 | evaluated_path = path.get_long_path_name(short_path) | |
258 | nt.assert_equal(evaluated_path.lower(), long_path.lower()) |
|
258 | nt.assert_equal(evaluated_path.lower(), long_path.lower()) | |
259 |
|
259 | |||
260 |
|
260 | |||
261 | @dec.skip_win32 |
|
261 | @dec.skip_win32 | |
262 | def test_get_long_path_name(): |
|
262 | def test_get_long_path_name(): | |
263 | p = path.get_long_path_name('/usr/local') |
|
263 | p = path.get_long_path_name('/usr/local') | |
264 | nt.assert_equal(p,'/usr/local') |
|
264 | nt.assert_equal(p,'/usr/local') | |
265 |
|
265 | |||
266 | @dec.skip_win32 # can't create not-user-writable dir on win |
|
266 | @dec.skip_win32 # can't create not-user-writable dir on win | |
267 | @with_environment |
|
267 | @with_environment | |
268 | def test_not_writable_ipdir(): |
|
268 | def test_not_writable_ipdir(): | |
269 | tmpdir = tempfile.mkdtemp() |
|
269 | tmpdir = tempfile.mkdtemp() | |
270 | os.name = "posix" |
|
270 | os.name = "posix" | |
271 | env.pop('IPYTHON_DIR', None) |
|
271 | env.pop('IPYTHON_DIR', None) | |
272 | env.pop('IPYTHONDIR', None) |
|
272 | env.pop('IPYTHONDIR', None) | |
273 | env.pop('XDG_CONFIG_HOME', None) |
|
273 | env.pop('XDG_CONFIG_HOME', None) | |
274 | env['HOME'] = tmpdir |
|
274 | env['HOME'] = tmpdir | |
275 | ipdir = os.path.join(tmpdir, '.ipython') |
|
275 | ipdir = os.path.join(tmpdir, '.ipython') | |
276 | os.mkdir(ipdir, 0o555) |
|
276 | os.mkdir(ipdir, 0o555) | |
277 | try: |
|
277 | try: | |
278 | open(os.path.join(ipdir, "_foo_"), 'w').close() |
|
278 | open(os.path.join(ipdir, "_foo_"), 'w').close() | |
279 | except IOError: |
|
279 | except IOError: | |
280 | pass |
|
280 | pass | |
281 | else: |
|
281 | else: | |
282 | # I can still write to an unwritable dir, |
|
282 | # I can still write to an unwritable dir, | |
283 | # assume I'm root and skip the test |
|
283 | # assume I'm root and skip the test | |
284 | raise SkipTest("I can't create directories that I can't write to") |
|
284 | raise SkipTest("I can't create directories that I can't write to") | |
285 | with AssertPrints('is not a writable location', channel='stderr'): |
|
285 | with AssertPrints('is not a writable location', channel='stderr'): | |
286 | ipdir = paths.get_ipython_dir() |
|
286 | ipdir = paths.get_ipython_dir() | |
287 | env.pop('IPYTHON_DIR', None) |
|
287 | env.pop('IPYTHON_DIR', None) | |
288 |
|
288 | |||
289 | @with_environment |
|
289 | @with_environment | |
290 | def test_get_py_filename(): |
|
290 | def test_get_py_filename(): | |
291 | os.chdir(TMP_TEST_DIR) |
|
291 | os.chdir(TMP_TEST_DIR) | |
292 | with make_tempfile('foo.py'): |
|
292 | with make_tempfile('foo.py'): | |
293 | nt.assert_equal(path.get_py_filename('foo.py'), 'foo.py') |
|
293 | nt.assert_equal(path.get_py_filename('foo.py'), 'foo.py') | |
294 | nt.assert_equal(path.get_py_filename('foo'), 'foo.py') |
|
294 | nt.assert_equal(path.get_py_filename('foo'), 'foo.py') | |
295 | with make_tempfile('foo'): |
|
295 | with make_tempfile('foo'): | |
296 | nt.assert_equal(path.get_py_filename('foo'), 'foo') |
|
296 | nt.assert_equal(path.get_py_filename('foo'), 'foo') | |
297 | nt.assert_raises(IOError, path.get_py_filename, 'foo.py') |
|
297 | nt.assert_raises(IOError, path.get_py_filename, 'foo.py') | |
298 | nt.assert_raises(IOError, path.get_py_filename, 'foo') |
|
298 | nt.assert_raises(IOError, path.get_py_filename, 'foo') | |
299 | nt.assert_raises(IOError, path.get_py_filename, 'foo.py') |
|
299 | nt.assert_raises(IOError, path.get_py_filename, 'foo.py') | |
300 | true_fn = 'foo with spaces.py' |
|
300 | true_fn = 'foo with spaces.py' | |
301 | with make_tempfile(true_fn): |
|
301 | with make_tempfile(true_fn): | |
302 | nt.assert_equal(path.get_py_filename('foo with spaces'), true_fn) |
|
302 | nt.assert_equal(path.get_py_filename('foo with spaces'), true_fn) | |
303 | nt.assert_equal(path.get_py_filename('foo with spaces.py'), true_fn) |
|
303 | nt.assert_equal(path.get_py_filename('foo with spaces.py'), true_fn) | |
304 | nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"') |
|
304 | nt.assert_raises(IOError, path.get_py_filename, '"foo with spaces.py"') | |
305 | nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'") |
|
305 | nt.assert_raises(IOError, path.get_py_filename, "'foo with spaces.py'") | |
306 |
|
306 | |||
307 | @onlyif_unicode_paths |
|
307 | @onlyif_unicode_paths | |
308 | def test_unicode_in_filename(): |
|
308 | def test_unicode_in_filename(): | |
309 | """When a file doesn't exist, the exception raised should be safe to call |
|
309 | """When a file doesn't exist, the exception raised should be safe to call | |
310 | str() on - i.e. in Python 2 it must only have ASCII characters. |
|
310 | str() on - i.e. in Python 2 it must only have ASCII characters. | |
311 |
|
311 | |||
312 | https://github.com/ipython/ipython/issues/875 |
|
312 | https://github.com/ipython/ipython/issues/875 | |
313 | """ |
|
313 | """ | |
314 | try: |
|
314 | try: | |
315 | # these calls should not throw unicode encode exceptions |
|
315 | # these calls should not throw unicode encode exceptions | |
316 | path.get_py_filename('fooéè.py', force_win32=False) |
|
316 | path.get_py_filename('fooéè.py', force_win32=False) | |
317 | except IOError as ex: |
|
317 | except IOError as ex: | |
318 | str(ex) |
|
318 | str(ex) | |
319 |
|
319 | |||
320 |
|
320 | |||
321 | class TestShellGlob(unittest.TestCase): |
|
321 | class TestShellGlob(unittest.TestCase): | |
322 |
|
322 | |||
323 | @classmethod |
|
323 | @classmethod | |
324 | def setUpClass(cls): |
|
324 | def setUpClass(cls): | |
325 | cls.filenames_start_with_a = ['a0', 'a1', 'a2'] |
|
325 | cls.filenames_start_with_a = ['a0', 'a1', 'a2'] | |
326 | cls.filenames_end_with_b = ['0b', '1b', '2b'] |
|
326 | cls.filenames_end_with_b = ['0b', '1b', '2b'] | |
327 | cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b |
|
327 | cls.filenames = cls.filenames_start_with_a + cls.filenames_end_with_b | |
328 | cls.tempdir = TemporaryDirectory() |
|
328 | cls.tempdir = TemporaryDirectory() | |
329 | td = cls.tempdir.name |
|
329 | td = cls.tempdir.name | |
330 |
|
330 | |||
331 | with cls.in_tempdir(): |
|
331 | with cls.in_tempdir(): | |
332 | # Create empty files |
|
332 | # Create empty files | |
333 | for fname in cls.filenames: |
|
333 | for fname in cls.filenames: | |
334 | open(os.path.join(td, fname), 'w').close() |
|
334 | open(os.path.join(td, fname), 'w').close() | |
335 |
|
335 | |||
336 | @classmethod |
|
336 | @classmethod | |
337 | def tearDownClass(cls): |
|
337 | def tearDownClass(cls): | |
338 | cls.tempdir.cleanup() |
|
338 | cls.tempdir.cleanup() | |
339 |
|
339 | |||
340 | @classmethod |
|
340 | @classmethod | |
341 | @contextmanager |
|
341 | @contextmanager | |
342 | def in_tempdir(cls): |
|
342 | def in_tempdir(cls): | |
343 | save = os.getcwd() |
|
343 | save = os.getcwd() | |
344 | try: |
|
344 | try: | |
345 | os.chdir(cls.tempdir.name) |
|
345 | os.chdir(cls.tempdir.name) | |
346 | yield |
|
346 | yield | |
347 | finally: |
|
347 | finally: | |
348 | os.chdir(save) |
|
348 | os.chdir(save) | |
349 |
|
349 | |||
350 | def check_match(self, patterns, matches): |
|
350 | def check_match(self, patterns, matches): | |
351 | with self.in_tempdir(): |
|
351 | with self.in_tempdir(): | |
352 | # glob returns unordered list. that's why sorted is required. |
|
352 | # glob returns unordered list. that's why sorted is required. | |
353 | nt.assert_equal(sorted(path.shellglob(patterns)), |
|
353 | nt.assert_equal(sorted(path.shellglob(patterns)), | |
354 | sorted(matches)) |
|
354 | sorted(matches)) | |
355 |
|
355 | |||
356 | def common_cases(self): |
|
356 | def common_cases(self): | |
357 | return [ |
|
357 | return [ | |
358 | (['*'], self.filenames), |
|
358 | (['*'], self.filenames), | |
359 | (['a*'], self.filenames_start_with_a), |
|
359 | (['a*'], self.filenames_start_with_a), | |
360 | (['*c'], ['*c']), |
|
360 | (['*c'], ['*c']), | |
361 | (['*', 'a*', '*b', '*c'], self.filenames |
|
361 | (['*', 'a*', '*b', '*c'], self.filenames | |
362 | + self.filenames_start_with_a |
|
362 | + self.filenames_start_with_a | |
363 | + self.filenames_end_with_b |
|
363 | + self.filenames_end_with_b | |
364 | + ['*c']), |
|
364 | + ['*c']), | |
365 | (['a[012]'], self.filenames_start_with_a), |
|
365 | (['a[012]'], self.filenames_start_with_a), | |
366 | ] |
|
366 | ] | |
367 |
|
367 | |||
368 | @skip_win32 |
|
368 | @skip_win32 | |
369 | def test_match_posix(self): |
|
369 | def test_match_posix(self): | |
370 | for (patterns, matches) in self.common_cases() + [ |
|
370 | for (patterns, matches) in self.common_cases() + [ | |
371 | ([r'\*'], ['*']), |
|
371 | ([r'\*'], ['*']), | |
372 | ([r'a\*', 'a*'], ['a*'] + self.filenames_start_with_a), |
|
372 | ([r'a\*', 'a*'], ['a*'] + self.filenames_start_with_a), | |
373 | ([r'a\[012]'], ['a[012]']), |
|
373 | ([r'a\[012]'], ['a[012]']), | |
374 | ]: |
|
374 | ]: | |
375 | yield (self.check_match, patterns, matches) |
|
375 | yield (self.check_match, patterns, matches) | |
376 |
|
376 | |||
377 | @skip_if_not_win32 |
|
377 | @skip_if_not_win32 | |
378 | def test_match_windows(self): |
|
378 | def test_match_windows(self): | |
379 | for (patterns, matches) in self.common_cases() + [ |
|
379 | for (patterns, matches) in self.common_cases() + [ | |
380 | # In windows, backslash is interpreted as path |
|
380 | # In windows, backslash is interpreted as path | |
381 | # separator. Therefore, you can't escape glob |
|
381 | # separator. Therefore, you can't escape glob | |
382 | # using it. |
|
382 | # using it. | |
383 | ([r'a\*', 'a*'], [r'a\*'] + self.filenames_start_with_a), |
|
383 | ([r'a\*', 'a*'], [r'a\*'] + self.filenames_start_with_a), | |
384 | ([r'a\[012]'], [r'a\[012]']), |
|
384 | ([r'a\[012]'], [r'a\[012]']), | |
385 | ]: |
|
385 | ]: | |
386 | yield (self.check_match, patterns, matches) |
|
386 | yield (self.check_match, patterns, matches) | |
387 |
|
387 | |||
388 |
|
388 | |||
389 | def test_unescape_glob(): |
|
389 | def test_unescape_glob(): | |
390 | nt.assert_equal(path.unescape_glob(r'\*\[\!\]\?'), '*[!]?') |
|
390 | nt.assert_equal(path.unescape_glob(r'\*\[\!\]\?'), '*[!]?') | |
391 | nt.assert_equal(path.unescape_glob(r'\\*'), r'\*') |
|
391 | nt.assert_equal(path.unescape_glob(r'\\*'), r'\*') | |
392 | nt.assert_equal(path.unescape_glob(r'\\\*'), r'\*') |
|
392 | nt.assert_equal(path.unescape_glob(r'\\\*'), r'\*') | |
393 | nt.assert_equal(path.unescape_glob(r'\\a'), r'\a') |
|
393 | nt.assert_equal(path.unescape_glob(r'\\a'), r'\a') | |
394 | nt.assert_equal(path.unescape_glob(r'\a'), r'\a') |
|
394 | nt.assert_equal(path.unescape_glob(r'\a'), r'\a') | |
395 |
|
395 | |||
396 |
|
396 | |||
397 | @onlyif_unicode_paths |
|
397 | @onlyif_unicode_paths | |
398 | def test_ensure_dir_exists(): |
|
398 | def test_ensure_dir_exists(): | |
399 | with TemporaryDirectory() as td: |
|
399 | with TemporaryDirectory() as td: | |
400 | d = os.path.join(td, 'βir') |
|
400 | d = os.path.join(td, 'βir') | |
401 | path.ensure_dir_exists(d) # create it |
|
401 | path.ensure_dir_exists(d) # create it | |
402 | assert os.path.isdir(d) |
|
402 | assert os.path.isdir(d) | |
403 | path.ensure_dir_exists(d) # no-op |
|
403 | path.ensure_dir_exists(d) # no-op | |
404 | f = os.path.join(td, 'Ζile') |
|
404 | f = os.path.join(td, 'Ζile') | |
405 | open(f, 'w').close() # touch |
|
405 | open(f, 'w').close() # touch | |
406 | with nt.assert_raises(IOError): |
|
406 | with nt.assert_raises(IOError): | |
407 | path.ensure_dir_exists(f) |
|
407 | path.ensure_dir_exists(f) | |
408 |
|
408 | |||
409 | class TestLinkOrCopy(object): |
|
409 | class TestLinkOrCopy(object): | |
410 | def setUp(self): |
|
410 | def setUp(self): | |
411 | self.tempdir = TemporaryDirectory() |
|
411 | self.tempdir = TemporaryDirectory() | |
412 | self.src = self.dst("src") |
|
412 | self.src = self.dst("src") | |
413 | with open(self.src, "w") as f: |
|
413 | with open(self.src, "w") as f: | |
414 | f.write("Hello, world!") |
|
414 | f.write("Hello, world!") | |
415 |
|
415 | |||
416 | def tearDown(self): |
|
416 | def tearDown(self): | |
417 | self.tempdir.cleanup() |
|
417 | self.tempdir.cleanup() | |
418 |
|
418 | |||
419 | def dst(self, *args): |
|
419 | def dst(self, *args): | |
420 | return os.path.join(self.tempdir.name, *args) |
|
420 | return os.path.join(self.tempdir.name, *args) | |
421 |
|
421 | |||
422 | def assert_inode_not_equal(self, a, b): |
|
422 | def assert_inode_not_equal(self, a, b): | |
423 | nt.assert_not_equal(os.stat(a).st_ino, os.stat(b).st_ino, |
|
423 | nt.assert_not_equal(os.stat(a).st_ino, os.stat(b).st_ino, | |
424 | "%r and %r do reference the same indoes" %(a, b)) |
|
424 | "%r and %r do reference the same indoes" %(a, b)) | |
425 |
|
425 | |||
426 | def assert_inode_equal(self, a, b): |
|
426 | def assert_inode_equal(self, a, b): | |
427 | nt.assert_equal(os.stat(a).st_ino, os.stat(b).st_ino, |
|
427 | nt.assert_equal(os.stat(a).st_ino, os.stat(b).st_ino, | |
428 | "%r and %r do not reference the same indoes" %(a, b)) |
|
428 | "%r and %r do not reference the same indoes" %(a, b)) | |
429 |
|
429 | |||
430 | def assert_content_equal(self, a, b): |
|
430 | def assert_content_equal(self, a, b): | |
431 | with open(a) as a_f: |
|
431 | with open(a) as a_f: | |
432 | with open(b) as b_f: |
|
432 | with open(b) as b_f: | |
433 | nt.assert_equal(a_f.read(), b_f.read()) |
|
433 | nt.assert_equal(a_f.read(), b_f.read()) | |
434 |
|
434 | |||
435 | @skip_win32 |
|
435 | @skip_win32 | |
436 | def test_link_successful(self): |
|
436 | def test_link_successful(self): | |
437 | dst = self.dst("target") |
|
437 | dst = self.dst("target") | |
438 | path.link_or_copy(self.src, dst) |
|
438 | path.link_or_copy(self.src, dst) | |
439 | self.assert_inode_equal(self.src, dst) |
|
439 | self.assert_inode_equal(self.src, dst) | |
440 |
|
440 | |||
441 | @skip_win32 |
|
441 | @skip_win32 | |
442 | def test_link_into_dir(self): |
|
442 | def test_link_into_dir(self): | |
443 | dst = self.dst("some_dir") |
|
443 | dst = self.dst("some_dir") | |
444 | os.mkdir(dst) |
|
444 | os.mkdir(dst) | |
445 | path.link_or_copy(self.src, dst) |
|
445 | path.link_or_copy(self.src, dst) | |
446 | expected_dst = self.dst("some_dir", os.path.basename(self.src)) |
|
446 | expected_dst = self.dst("some_dir", os.path.basename(self.src)) | |
447 | self.assert_inode_equal(self.src, expected_dst) |
|
447 | self.assert_inode_equal(self.src, expected_dst) | |
448 |
|
448 | |||
449 | @skip_win32 |
|
449 | @skip_win32 | |
450 | def test_target_exists(self): |
|
450 | def test_target_exists(self): | |
451 | dst = self.dst("target") |
|
451 | dst = self.dst("target") | |
452 | open(dst, "w").close() |
|
452 | open(dst, "w").close() | |
453 | path.link_or_copy(self.src, dst) |
|
453 | path.link_or_copy(self.src, dst) | |
454 | self.assert_inode_equal(self.src, dst) |
|
454 | self.assert_inode_equal(self.src, dst) | |
455 |
|
455 | |||
456 | @skip_win32 |
|
456 | @skip_win32 | |
457 | def test_no_link(self): |
|
457 | def test_no_link(self): | |
458 | real_link = os.link |
|
458 | real_link = os.link | |
459 | try: |
|
459 | try: | |
460 | del os.link |
|
460 | del os.link | |
461 | dst = self.dst("target") |
|
461 | dst = self.dst("target") | |
462 | path.link_or_copy(self.src, dst) |
|
462 | path.link_or_copy(self.src, dst) | |
463 | self.assert_content_equal(self.src, dst) |
|
463 | self.assert_content_equal(self.src, dst) | |
464 | self.assert_inode_not_equal(self.src, dst) |
|
464 | self.assert_inode_not_equal(self.src, dst) | |
465 | finally: |
|
465 | finally: | |
466 | os.link = real_link |
|
466 | os.link = real_link | |
467 |
|
467 | |||
468 | @skip_if_not_win32 |
|
468 | @skip_if_not_win32 | |
469 | def test_windows(self): |
|
469 | def test_windows(self): | |
470 | dst = self.dst("target") |
|
470 | dst = self.dst("target") | |
471 | path.link_or_copy(self.src, dst) |
|
471 | path.link_or_copy(self.src, dst) | |
472 | self.assert_content_equal(self.src, dst) |
|
472 | self.assert_content_equal(self.src, dst) | |
473 |
|
473 | |||
474 | def test_link_twice(self): |
|
474 | def test_link_twice(self): | |
475 | # Linking the same file twice shouldn't leave duplicates around. |
|
475 | # Linking the same file twice shouldn't leave duplicates around. | |
476 | # See https://github.com/ipython/ipython/issues/6450 |
|
476 | # See https://github.com/ipython/ipython/issues/6450 | |
477 | dst = self.dst('target') |
|
477 | dst = self.dst('target') | |
478 | path.link_or_copy(self.src, dst) |
|
478 | path.link_or_copy(self.src, dst) | |
479 | path.link_or_copy(self.src, dst) |
|
479 | path.link_or_copy(self.src, dst) | |
480 | self.assert_inode_equal(self.src, dst) |
|
480 | self.assert_inode_equal(self.src, dst) | |
481 | nt.assert_equal(sorted(os.listdir(self.tempdir.name)), ['src', 'target']) |
|
481 | nt.assert_equal(sorted(os.listdir(self.tempdir.name)), ['src', 'target']) |
General Comments 0
You need to be logged in to leave comments.
Login now