##// END OF EJS Templates
Sort and unique %config results
Sang Min Park -
Show More
@@ -1,157 +1,158 b''
1 """Implementation of configuration-related magic functions.
1 """Implementation of configuration-related magic functions.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012 The IPython Development Team.
4 # Copyright (c) 2012 The IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import re
16 import re
17
17
18 # Our own packages
18 # Our own packages
19 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
20 from IPython.core.magic import Magics, magics_class, line_magic
20 from IPython.core.magic import Magics, magics_class, line_magic
21 from logging import error
21 from logging import error
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Magic implementation classes
24 # Magic implementation classes
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26
26
27 reg = re.compile('^\w+\.\w+$')
27 reg = re.compile('^\w+\.\w+$')
28 @magics_class
28 @magics_class
29 class ConfigMagics(Magics):
29 class ConfigMagics(Magics):
30
30
31 def __init__(self, shell):
31 def __init__(self, shell):
32 super(ConfigMagics, self).__init__(shell)
32 super(ConfigMagics, self).__init__(shell)
33 self.configurables = []
33 self.configurables = []
34
34
35 @line_magic
35 @line_magic
36 def config(self, s):
36 def config(self, s):
37 """configure IPython
37 """configure IPython
38
38
39 %config Class[.trait=value]
39 %config Class[.trait=value]
40
40
41 This magic exposes most of the IPython config system. Any
41 This magic exposes most of the IPython config system. Any
42 Configurable class should be able to be configured with the simple
42 Configurable class should be able to be configured with the simple
43 line::
43 line::
44
44
45 %config Class.trait=value
45 %config Class.trait=value
46
46
47 Where `value` will be resolved in the user's namespace, if it is an
47 Where `value` will be resolved in the user's namespace, if it is an
48 expression or variable name.
48 expression or variable name.
49
49
50 Examples
50 Examples
51 --------
51 --------
52
52
53 To see what classes are available for config, pass no arguments::
53 To see what classes are available for config, pass no arguments::
54
54
55 In [1]: %config
55 In [1]: %config
56 Available objects for config:
56 Available objects for config:
57 TerminalInteractiveShell
57 TerminalInteractiveShell
58 HistoryManager
58 HistoryManager
59 PrefilterManager
59 PrefilterManager
60 AliasManager
60 AliasManager
61 IPCompleter
61 IPCompleter
62 DisplayFormatter
62 DisplayFormatter
63
63
64 To view what is configurable on a given class, just pass the class
64 To view what is configurable on a given class, just pass the class
65 name::
65 name::
66
66
67 In [2]: %config IPCompleter
67 In [2]: %config IPCompleter
68 IPCompleter options
68 IPCompleter options
69 -----------------
69 -----------------
70 IPCompleter.omit__names=<Enum>
70 IPCompleter.omit__names=<Enum>
71 Current: 2
71 Current: 2
72 Choices: (0, 1, 2)
72 Choices: (0, 1, 2)
73 Instruct the completer to omit private method names
73 Instruct the completer to omit private method names
74 Specifically, when completing on ``object.<tab>``.
74 Specifically, when completing on ``object.<tab>``.
75 When 2 [default]: all names that start with '_' will be excluded.
75 When 2 [default]: all names that start with '_' will be excluded.
76 When 1: all 'magic' names (``__foo__``) will be excluded.
76 When 1: all 'magic' names (``__foo__``) will be excluded.
77 When 0: nothing will be excluded.
77 When 0: nothing will be excluded.
78 IPCompleter.merge_completions=<CBool>
78 IPCompleter.merge_completions=<CBool>
79 Current: True
79 Current: True
80 Whether to merge completion results into a single list
80 Whether to merge completion results into a single list
81 If False, only the completion results from the first non-empty
81 If False, only the completion results from the first non-empty
82 completer will be returned.
82 completer will be returned.
83 IPCompleter.limit_to__all__=<CBool>
83 IPCompleter.limit_to__all__=<CBool>
84 Current: False
84 Current: False
85 Instruct the completer to use __all__ for the completion
85 Instruct the completer to use __all__ for the completion
86 Specifically, when completing on ``object.<tab>``.
86 Specifically, when completing on ``object.<tab>``.
87 When True: only those names in obj.__all__ will be included.
87 When True: only those names in obj.__all__ will be included.
88 When False [default]: the __all__ attribute is ignored
88 When False [default]: the __all__ attribute is ignored
89 IPCompleter.greedy=<CBool>
89 IPCompleter.greedy=<CBool>
90 Current: False
90 Current: False
91 Activate greedy completion
91 Activate greedy completion
92 This will enable completion on elements of lists, results of
92 This will enable completion on elements of lists, results of
93 function calls, etc., but can be unsafe because the code is
93 function calls, etc., but can be unsafe because the code is
94 actually evaluated on TAB.
94 actually evaluated on TAB.
95
95
96 but the real use is in setting values::
96 but the real use is in setting values::
97
97
98 In [3]: %config IPCompleter.greedy = True
98 In [3]: %config IPCompleter.greedy = True
99
99
100 and these values are read from the user_ns if they are variables::
100 and these values are read from the user_ns if they are variables::
101
101
102 In [4]: feeling_greedy=False
102 In [4]: feeling_greedy=False
103
103
104 In [5]: %config IPCompleter.greedy = feeling_greedy
104 In [5]: %config IPCompleter.greedy = feeling_greedy
105
105
106 """
106 """
107 from traitlets.config.loader import Config
107 from traitlets.config.loader import Config
108 # some IPython objects are Configurable, but do not yet have
108 # some IPython objects are Configurable, but do not yet have
109 # any configurable traits. Exclude them from the effects of
109 # any configurable traits. Exclude them from the effects of
110 # this magic, as their presence is just noise:
110 # this magic, as their presence is just noise:
111 configurables = [ c for c in self.shell.configurables
111 configurables = sorted(set([ c for c in self.shell.configurables
112 if c.__class__.class_traits(config=True) ]
112 if c.__class__.class_traits(config=True)
113 ]), key=lambda x: x.__class__.__name__)
113 classnames = [ c.__class__.__name__ for c in configurables ]
114 classnames = [ c.__class__.__name__ for c in configurables ]
114
115
115 line = s.strip()
116 line = s.strip()
116 if not line:
117 if not line:
117 # print available configurable names
118 # print available configurable names
118 print("Available objects for config:")
119 print("Available objects for config:")
119 for name in classnames:
120 for name in classnames:
120 print(" ", name)
121 print(" ", name)
121 return
122 return
122 elif line in classnames:
123 elif line in classnames:
123 # `%config TerminalInteractiveShell` will print trait info for
124 # `%config TerminalInteractiveShell` will print trait info for
124 # TerminalInteractiveShell
125 # TerminalInteractiveShell
125 c = configurables[classnames.index(line)]
126 c = configurables[classnames.index(line)]
126 cls = c.__class__
127 cls = c.__class__
127 help = cls.class_get_help(c)
128 help = cls.class_get_help(c)
128 # strip leading '--' from cl-args:
129 # strip leading '--' from cl-args:
129 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
130 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
130 print(help)
131 print(help)
131 return
132 return
132 elif reg.match(line):
133 elif reg.match(line):
133 cls, attr = line.split('.')
134 cls, attr = line.split('.')
134 return getattr(configurables[classnames.index(cls)],attr)
135 return getattr(configurables[classnames.index(cls)],attr)
135 elif '=' not in line:
136 elif '=' not in line:
136 msg = "Invalid config statement: %r, "\
137 msg = "Invalid config statement: %r, "\
137 "should be `Class.trait = value`."
138 "should be `Class.trait = value`."
138
139
139 ll = line.lower()
140 ll = line.lower()
140 for classname in classnames:
141 for classname in classnames:
141 if ll == classname.lower():
142 if ll == classname.lower():
142 msg = msg + '\nDid you mean %s (note the case)?' % classname
143 msg = msg + '\nDid you mean %s (note the case)?' % classname
143 break
144 break
144
145
145 raise UsageError( msg % line)
146 raise UsageError( msg % line)
146
147
147 # otherwise, assume we are setting configurables.
148 # otherwise, assume we are setting configurables.
148 # leave quotes on args when splitting, because we want
149 # leave quotes on args when splitting, because we want
149 # unquoted args to eval in user_ns
150 # unquoted args to eval in user_ns
150 cfg = Config()
151 cfg = Config()
151 exec("cfg."+line, locals(), self.shell.user_ns)
152 exec("cfg."+line, locals(), self.shell.user_ns)
152
153
153 for configurable in configurables:
154 for configurable in configurables:
154 try:
155 try:
155 configurable.update_config(cfg)
156 configurable.update_config(cfg)
156 except Exception as e:
157 except Exception as e:
157 error(e)
158 error(e)
@@ -1,979 +1,997 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for various magic functions.
2 """Tests for various magic functions.
3
3
4 Needs to be run by nose (to make ipython session available).
4 Needs to be run by nose (to make ipython session available).
5 """
5 """
6
6
7 import io
7 import io
8 import os
8 import os
9 import sys
9 import sys
10 import warnings
10 import warnings
11 from unittest import TestCase
11 from unittest import TestCase
12 from importlib import invalidate_caches
12 from importlib import invalidate_caches
13 from io import StringIO
13 from io import StringIO
14
14
15 import nose.tools as nt
15 import nose.tools as nt
16
16
17 from IPython import get_ipython
17 from IPython import get_ipython
18 from IPython.core import magic
18 from IPython.core import magic
19 from IPython.core.error import UsageError
19 from IPython.core.error import UsageError
20 from IPython.core.magic import (Magics, magics_class, line_magic,
20 from IPython.core.magic import (Magics, magics_class, line_magic,
21 cell_magic,
21 cell_magic,
22 register_line_magic, register_cell_magic)
22 register_line_magic, register_cell_magic)
23 from IPython.core.magics import execution, script, code
23 from IPython.core.magics import execution, script, code
24 from IPython.testing import decorators as dec
24 from IPython.testing import decorators as dec
25 from IPython.testing import tools as tt
25 from IPython.testing import tools as tt
26 from IPython.utils import py3compat
26 from IPython.utils import py3compat
27 from IPython.utils.io import capture_output
27 from IPython.utils.io import capture_output
28 from IPython.utils.tempdir import TemporaryDirectory
28 from IPython.utils.tempdir import TemporaryDirectory
29 from IPython.utils.process import find_cmd
29 from IPython.utils.process import find_cmd
30
30
31
31
32
32
33 _ip = get_ipython()
33 _ip = get_ipython()
34
34
35 @magic.magics_class
35 @magic.magics_class
36 class DummyMagics(magic.Magics): pass
36 class DummyMagics(magic.Magics): pass
37
37
38 def test_extract_code_ranges():
38 def test_extract_code_ranges():
39 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
39 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
40 expected = [(0, 1),
40 expected = [(0, 1),
41 (2, 3),
41 (2, 3),
42 (4, 6),
42 (4, 6),
43 (6, 9),
43 (6, 9),
44 (9, 14),
44 (9, 14),
45 (16, None),
45 (16, None),
46 (None, 9),
46 (None, 9),
47 (9, None),
47 (9, None),
48 (None, 13),
48 (None, 13),
49 (None, None)]
49 (None, None)]
50 actual = list(code.extract_code_ranges(instr))
50 actual = list(code.extract_code_ranges(instr))
51 nt.assert_equal(actual, expected)
51 nt.assert_equal(actual, expected)
52
52
53 def test_extract_symbols():
53 def test_extract_symbols():
54 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
54 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
55 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
55 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
56 expected = [([], ['a']),
56 expected = [([], ['a']),
57 (["def b():\n return 42\n"], []),
57 (["def b():\n return 42\n"], []),
58 (["class A: pass\n"], []),
58 (["class A: pass\n"], []),
59 (["class A: pass\n", "def b():\n return 42\n"], []),
59 (["class A: pass\n", "def b():\n return 42\n"], []),
60 (["class A: pass\n"], ['a']),
60 (["class A: pass\n"], ['a']),
61 ([], ['z'])]
61 ([], ['z'])]
62 for symbols, exp in zip(symbols_args, expected):
62 for symbols, exp in zip(symbols_args, expected):
63 nt.assert_equal(code.extract_symbols(source, symbols), exp)
63 nt.assert_equal(code.extract_symbols(source, symbols), exp)
64
64
65
65
66 def test_extract_symbols_raises_exception_with_non_python_code():
66 def test_extract_symbols_raises_exception_with_non_python_code():
67 source = ("=begin A Ruby program :)=end\n"
67 source = ("=begin A Ruby program :)=end\n"
68 "def hello\n"
68 "def hello\n"
69 "puts 'Hello world'\n"
69 "puts 'Hello world'\n"
70 "end")
70 "end")
71 with nt.assert_raises(SyntaxError):
71 with nt.assert_raises(SyntaxError):
72 code.extract_symbols(source, "hello")
72 code.extract_symbols(source, "hello")
73
73
74 def test_config():
74 def test_config():
75 """ test that config magic does not raise
75 """ test that config magic does not raise
76 can happen if Configurable init is moved too early into
76 can happen if Configurable init is moved too early into
77 Magics.__init__ as then a Config object will be registerd as a
77 Magics.__init__ as then a Config object will be registerd as a
78 magic.
78 magic.
79 """
79 """
80 ## should not raise.
80 ## should not raise.
81 _ip.magic('config')
81 _ip.magic('config')
82
82
83 def test_config_available_configs():
84 """ test that config magic prints available configs in unique and
85 sorted order. """
86 with capture_output() as captured:
87 _ip.magic('config')
88
89 stdout = captured.stdout
90 config_classes = stdout.strip().split('\n')[1:]
91 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
92
93 def test_config_print_class():
94 """ test that config with a classname prints the class's options. """
95 with capture_output() as captured:
96 _ip.magic('config TerminalInteractiveShell')
97
98 stdout = captured.stdout
99 nt.assert_in("TerminalInteractiveShell options", stdout)
100
83 def test_rehashx():
101 def test_rehashx():
84 # clear up everything
102 # clear up everything
85 _ip.alias_manager.clear_aliases()
103 _ip.alias_manager.clear_aliases()
86 del _ip.db['syscmdlist']
104 del _ip.db['syscmdlist']
87
105
88 _ip.magic('rehashx')
106 _ip.magic('rehashx')
89 # Practically ALL ipython development systems will have more than 10 aliases
107 # Practically ALL ipython development systems will have more than 10 aliases
90
108
91 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
109 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
92 for name, cmd in _ip.alias_manager.aliases:
110 for name, cmd in _ip.alias_manager.aliases:
93 # we must strip dots from alias names
111 # we must strip dots from alias names
94 nt.assert_not_in('.', name)
112 nt.assert_not_in('.', name)
95
113
96 # rehashx must fill up syscmdlist
114 # rehashx must fill up syscmdlist
97 scoms = _ip.db['syscmdlist']
115 scoms = _ip.db['syscmdlist']
98 nt.assert_true(len(scoms) > 10)
116 nt.assert_true(len(scoms) > 10)
99
117
100
118
101 def test_magic_parse_options():
119 def test_magic_parse_options():
102 """Test that we don't mangle paths when parsing magic options."""
120 """Test that we don't mangle paths when parsing magic options."""
103 ip = get_ipython()
121 ip = get_ipython()
104 path = 'c:\\x'
122 path = 'c:\\x'
105 m = DummyMagics(ip)
123 m = DummyMagics(ip)
106 opts = m.parse_options('-f %s' % path,'f:')[0]
124 opts = m.parse_options('-f %s' % path,'f:')[0]
107 # argv splitting is os-dependent
125 # argv splitting is os-dependent
108 if os.name == 'posix':
126 if os.name == 'posix':
109 expected = 'c:x'
127 expected = 'c:x'
110 else:
128 else:
111 expected = path
129 expected = path
112 nt.assert_equal(opts['f'], expected)
130 nt.assert_equal(opts['f'], expected)
113
131
114 def test_magic_parse_long_options():
132 def test_magic_parse_long_options():
115 """Magic.parse_options can handle --foo=bar long options"""
133 """Magic.parse_options can handle --foo=bar long options"""
116 ip = get_ipython()
134 ip = get_ipython()
117 m = DummyMagics(ip)
135 m = DummyMagics(ip)
118 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
136 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
119 nt.assert_in('foo', opts)
137 nt.assert_in('foo', opts)
120 nt.assert_in('bar', opts)
138 nt.assert_in('bar', opts)
121 nt.assert_equal(opts['bar'], "bubble")
139 nt.assert_equal(opts['bar'], "bubble")
122
140
123
141
124 @dec.skip_without('sqlite3')
142 @dec.skip_without('sqlite3')
125 def doctest_hist_f():
143 def doctest_hist_f():
126 """Test %hist -f with temporary filename.
144 """Test %hist -f with temporary filename.
127
145
128 In [9]: import tempfile
146 In [9]: import tempfile
129
147
130 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
148 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
131
149
132 In [11]: %hist -nl -f $tfile 3
150 In [11]: %hist -nl -f $tfile 3
133
151
134 In [13]: import os; os.unlink(tfile)
152 In [13]: import os; os.unlink(tfile)
135 """
153 """
136
154
137
155
138 @dec.skip_without('sqlite3')
156 @dec.skip_without('sqlite3')
139 def doctest_hist_r():
157 def doctest_hist_r():
140 """Test %hist -r
158 """Test %hist -r
141
159
142 XXX - This test is not recording the output correctly. For some reason, in
160 XXX - This test is not recording the output correctly. For some reason, in
143 testing mode the raw history isn't getting populated. No idea why.
161 testing mode the raw history isn't getting populated. No idea why.
144 Disabling the output checking for now, though at least we do run it.
162 Disabling the output checking for now, though at least we do run it.
145
163
146 In [1]: 'hist' in _ip.lsmagic()
164 In [1]: 'hist' in _ip.lsmagic()
147 Out[1]: True
165 Out[1]: True
148
166
149 In [2]: x=1
167 In [2]: x=1
150
168
151 In [3]: %hist -rl 2
169 In [3]: %hist -rl 2
152 x=1 # random
170 x=1 # random
153 %hist -r 2
171 %hist -r 2
154 """
172 """
155
173
156
174
157 @dec.skip_without('sqlite3')
175 @dec.skip_without('sqlite3')
158 def doctest_hist_op():
176 def doctest_hist_op():
159 """Test %hist -op
177 """Test %hist -op
160
178
161 In [1]: class b(float):
179 In [1]: class b(float):
162 ...: pass
180 ...: pass
163 ...:
181 ...:
164
182
165 In [2]: class s(object):
183 In [2]: class s(object):
166 ...: def __str__(self):
184 ...: def __str__(self):
167 ...: return 's'
185 ...: return 's'
168 ...:
186 ...:
169
187
170 In [3]:
188 In [3]:
171
189
172 In [4]: class r(b):
190 In [4]: class r(b):
173 ...: def __repr__(self):
191 ...: def __repr__(self):
174 ...: return 'r'
192 ...: return 'r'
175 ...:
193 ...:
176
194
177 In [5]: class sr(s,r): pass
195 In [5]: class sr(s,r): pass
178 ...:
196 ...:
179
197
180 In [6]:
198 In [6]:
181
199
182 In [7]: bb=b()
200 In [7]: bb=b()
183
201
184 In [8]: ss=s()
202 In [8]: ss=s()
185
203
186 In [9]: rr=r()
204 In [9]: rr=r()
187
205
188 In [10]: ssrr=sr()
206 In [10]: ssrr=sr()
189
207
190 In [11]: 4.5
208 In [11]: 4.5
191 Out[11]: 4.5
209 Out[11]: 4.5
192
210
193 In [12]: str(ss)
211 In [12]: str(ss)
194 Out[12]: 's'
212 Out[12]: 's'
195
213
196 In [13]:
214 In [13]:
197
215
198 In [14]: %hist -op
216 In [14]: %hist -op
199 >>> class b:
217 >>> class b:
200 ... pass
218 ... pass
201 ...
219 ...
202 >>> class s(b):
220 >>> class s(b):
203 ... def __str__(self):
221 ... def __str__(self):
204 ... return 's'
222 ... return 's'
205 ...
223 ...
206 >>>
224 >>>
207 >>> class r(b):
225 >>> class r(b):
208 ... def __repr__(self):
226 ... def __repr__(self):
209 ... return 'r'
227 ... return 'r'
210 ...
228 ...
211 >>> class sr(s,r): pass
229 >>> class sr(s,r): pass
212 >>>
230 >>>
213 >>> bb=b()
231 >>> bb=b()
214 >>> ss=s()
232 >>> ss=s()
215 >>> rr=r()
233 >>> rr=r()
216 >>> ssrr=sr()
234 >>> ssrr=sr()
217 >>> 4.5
235 >>> 4.5
218 4.5
236 4.5
219 >>> str(ss)
237 >>> str(ss)
220 's'
238 's'
221 >>>
239 >>>
222 """
240 """
223
241
224 def test_hist_pof():
242 def test_hist_pof():
225 ip = get_ipython()
243 ip = get_ipython()
226 ip.run_cell(u"1+2", store_history=True)
244 ip.run_cell(u"1+2", store_history=True)
227 #raise Exception(ip.history_manager.session_number)
245 #raise Exception(ip.history_manager.session_number)
228 #raise Exception(list(ip.history_manager._get_range_session()))
246 #raise Exception(list(ip.history_manager._get_range_session()))
229 with TemporaryDirectory() as td:
247 with TemporaryDirectory() as td:
230 tf = os.path.join(td, 'hist.py')
248 tf = os.path.join(td, 'hist.py')
231 ip.run_line_magic('history', '-pof %s' % tf)
249 ip.run_line_magic('history', '-pof %s' % tf)
232 assert os.path.isfile(tf)
250 assert os.path.isfile(tf)
233
251
234
252
235 @dec.skip_without('sqlite3')
253 @dec.skip_without('sqlite3')
236 def test_macro():
254 def test_macro():
237 ip = get_ipython()
255 ip = get_ipython()
238 ip.history_manager.reset() # Clear any existing history.
256 ip.history_manager.reset() # Clear any existing history.
239 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
257 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
240 for i, cmd in enumerate(cmds, start=1):
258 for i, cmd in enumerate(cmds, start=1):
241 ip.history_manager.store_inputs(i, cmd)
259 ip.history_manager.store_inputs(i, cmd)
242 ip.magic("macro test 1-3")
260 ip.magic("macro test 1-3")
243 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
261 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
244
262
245 # List macros
263 # List macros
246 nt.assert_in("test", ip.magic("macro"))
264 nt.assert_in("test", ip.magic("macro"))
247
265
248
266
249 @dec.skip_without('sqlite3')
267 @dec.skip_without('sqlite3')
250 def test_macro_run():
268 def test_macro_run():
251 """Test that we can run a multi-line macro successfully."""
269 """Test that we can run a multi-line macro successfully."""
252 ip = get_ipython()
270 ip = get_ipython()
253 ip.history_manager.reset()
271 ip.history_manager.reset()
254 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
272 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
255 "%macro test 2-3"]
273 "%macro test 2-3"]
256 for cmd in cmds:
274 for cmd in cmds:
257 ip.run_cell(cmd, store_history=True)
275 ip.run_cell(cmd, store_history=True)
258 nt.assert_equal(ip.user_ns["test"].value,
276 nt.assert_equal(ip.user_ns["test"].value,
259 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
277 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
260 with tt.AssertPrints("12"):
278 with tt.AssertPrints("12"):
261 ip.run_cell("test")
279 ip.run_cell("test")
262 with tt.AssertPrints("13"):
280 with tt.AssertPrints("13"):
263 ip.run_cell("test")
281 ip.run_cell("test")
264
282
265
283
266 def test_magic_magic():
284 def test_magic_magic():
267 """Test %magic"""
285 """Test %magic"""
268 ip = get_ipython()
286 ip = get_ipython()
269 with capture_output() as captured:
287 with capture_output() as captured:
270 ip.magic("magic")
288 ip.magic("magic")
271
289
272 stdout = captured.stdout
290 stdout = captured.stdout
273 nt.assert_in('%magic', stdout)
291 nt.assert_in('%magic', stdout)
274 nt.assert_in('IPython', stdout)
292 nt.assert_in('IPython', stdout)
275 nt.assert_in('Available', stdout)
293 nt.assert_in('Available', stdout)
276
294
277
295
278 @dec.skipif_not_numpy
296 @dec.skipif_not_numpy
279 def test_numpy_reset_array_undec():
297 def test_numpy_reset_array_undec():
280 "Test '%reset array' functionality"
298 "Test '%reset array' functionality"
281 _ip.ex('import numpy as np')
299 _ip.ex('import numpy as np')
282 _ip.ex('a = np.empty(2)')
300 _ip.ex('a = np.empty(2)')
283 nt.assert_in('a', _ip.user_ns)
301 nt.assert_in('a', _ip.user_ns)
284 _ip.magic('reset -f array')
302 _ip.magic('reset -f array')
285 nt.assert_not_in('a', _ip.user_ns)
303 nt.assert_not_in('a', _ip.user_ns)
286
304
287 def test_reset_out():
305 def test_reset_out():
288 "Test '%reset out' magic"
306 "Test '%reset out' magic"
289 _ip.run_cell("parrot = 'dead'", store_history=True)
307 _ip.run_cell("parrot = 'dead'", store_history=True)
290 # test '%reset -f out', make an Out prompt
308 # test '%reset -f out', make an Out prompt
291 _ip.run_cell("parrot", store_history=True)
309 _ip.run_cell("parrot", store_history=True)
292 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
310 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
293 _ip.magic('reset -f out')
311 _ip.magic('reset -f out')
294 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
312 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
295 nt.assert_equal(len(_ip.user_ns['Out']), 0)
313 nt.assert_equal(len(_ip.user_ns['Out']), 0)
296
314
297 def test_reset_in():
315 def test_reset_in():
298 "Test '%reset in' magic"
316 "Test '%reset in' magic"
299 # test '%reset -f in'
317 # test '%reset -f in'
300 _ip.run_cell("parrot", store_history=True)
318 _ip.run_cell("parrot", store_history=True)
301 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
319 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
302 _ip.magic('%reset -f in')
320 _ip.magic('%reset -f in')
303 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
321 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
304 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
322 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
305
323
306 def test_reset_dhist():
324 def test_reset_dhist():
307 "Test '%reset dhist' magic"
325 "Test '%reset dhist' magic"
308 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
326 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
309 _ip.magic('cd ' + os.path.dirname(nt.__file__))
327 _ip.magic('cd ' + os.path.dirname(nt.__file__))
310 _ip.magic('cd -')
328 _ip.magic('cd -')
311 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
329 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
312 _ip.magic('reset -f dhist')
330 _ip.magic('reset -f dhist')
313 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
331 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
314 _ip.run_cell("_dh = [d for d in tmp]") #restore
332 _ip.run_cell("_dh = [d for d in tmp]") #restore
315
333
316 def test_reset_in_length():
334 def test_reset_in_length():
317 "Test that '%reset in' preserves In[] length"
335 "Test that '%reset in' preserves In[] length"
318 _ip.run_cell("print 'foo'")
336 _ip.run_cell("print 'foo'")
319 _ip.run_cell("reset -f in")
337 _ip.run_cell("reset -f in")
320 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
338 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
321
339
322 def test_tb_syntaxerror():
340 def test_tb_syntaxerror():
323 """test %tb after a SyntaxError"""
341 """test %tb after a SyntaxError"""
324 ip = get_ipython()
342 ip = get_ipython()
325 ip.run_cell("for")
343 ip.run_cell("for")
326
344
327 # trap and validate stdout
345 # trap and validate stdout
328 save_stdout = sys.stdout
346 save_stdout = sys.stdout
329 try:
347 try:
330 sys.stdout = StringIO()
348 sys.stdout = StringIO()
331 ip.run_cell("%tb")
349 ip.run_cell("%tb")
332 out = sys.stdout.getvalue()
350 out = sys.stdout.getvalue()
333 finally:
351 finally:
334 sys.stdout = save_stdout
352 sys.stdout = save_stdout
335 # trim output, and only check the last line
353 # trim output, and only check the last line
336 last_line = out.rstrip().splitlines()[-1].strip()
354 last_line = out.rstrip().splitlines()[-1].strip()
337 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
355 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
338
356
339
357
340 def test_time():
358 def test_time():
341 ip = get_ipython()
359 ip = get_ipython()
342
360
343 with tt.AssertPrints("Wall time: "):
361 with tt.AssertPrints("Wall time: "):
344 ip.run_cell("%time None")
362 ip.run_cell("%time None")
345
363
346 ip.run_cell("def f(kmjy):\n"
364 ip.run_cell("def f(kmjy):\n"
347 " %time print (2*kmjy)")
365 " %time print (2*kmjy)")
348
366
349 with tt.AssertPrints("Wall time: "):
367 with tt.AssertPrints("Wall time: "):
350 with tt.AssertPrints("hihi", suppress=False):
368 with tt.AssertPrints("hihi", suppress=False):
351 ip.run_cell("f('hi')")
369 ip.run_cell("f('hi')")
352
370
353
371
354 @dec.skip_win32
372 @dec.skip_win32
355 def test_time2():
373 def test_time2():
356 ip = get_ipython()
374 ip = get_ipython()
357
375
358 with tt.AssertPrints("CPU times: user "):
376 with tt.AssertPrints("CPU times: user "):
359 ip.run_cell("%time None")
377 ip.run_cell("%time None")
360
378
361 def test_time3():
379 def test_time3():
362 """Erroneous magic function calls, issue gh-3334"""
380 """Erroneous magic function calls, issue gh-3334"""
363 ip = get_ipython()
381 ip = get_ipython()
364 ip.user_ns.pop('run', None)
382 ip.user_ns.pop('run', None)
365
383
366 with tt.AssertNotPrints("not found", channel='stderr'):
384 with tt.AssertNotPrints("not found", channel='stderr'):
367 ip.run_cell("%%time\n"
385 ip.run_cell("%%time\n"
368 "run = 0\n"
386 "run = 0\n"
369 "run += 1")
387 "run += 1")
370
388
371 def test_doctest_mode():
389 def test_doctest_mode():
372 "Toggle doctest_mode twice, it should be a no-op and run without error"
390 "Toggle doctest_mode twice, it should be a no-op and run without error"
373 _ip.magic('doctest_mode')
391 _ip.magic('doctest_mode')
374 _ip.magic('doctest_mode')
392 _ip.magic('doctest_mode')
375
393
376
394
377 def test_parse_options():
395 def test_parse_options():
378 """Tests for basic options parsing in magics."""
396 """Tests for basic options parsing in magics."""
379 # These are only the most minimal of tests, more should be added later. At
397 # These are only the most minimal of tests, more should be added later. At
380 # the very least we check that basic text/unicode calls work OK.
398 # the very least we check that basic text/unicode calls work OK.
381 m = DummyMagics(_ip)
399 m = DummyMagics(_ip)
382 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
400 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
383 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
401 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
384
402
385
403
386 def test_dirops():
404 def test_dirops():
387 """Test various directory handling operations."""
405 """Test various directory handling operations."""
388 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
406 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
389 curpath = os.getcwd
407 curpath = os.getcwd
390 startdir = os.getcwd()
408 startdir = os.getcwd()
391 ipdir = os.path.realpath(_ip.ipython_dir)
409 ipdir = os.path.realpath(_ip.ipython_dir)
392 try:
410 try:
393 _ip.magic('cd "%s"' % ipdir)
411 _ip.magic('cd "%s"' % ipdir)
394 nt.assert_equal(curpath(), ipdir)
412 nt.assert_equal(curpath(), ipdir)
395 _ip.magic('cd -')
413 _ip.magic('cd -')
396 nt.assert_equal(curpath(), startdir)
414 nt.assert_equal(curpath(), startdir)
397 _ip.magic('pushd "%s"' % ipdir)
415 _ip.magic('pushd "%s"' % ipdir)
398 nt.assert_equal(curpath(), ipdir)
416 nt.assert_equal(curpath(), ipdir)
399 _ip.magic('popd')
417 _ip.magic('popd')
400 nt.assert_equal(curpath(), startdir)
418 nt.assert_equal(curpath(), startdir)
401 finally:
419 finally:
402 os.chdir(startdir)
420 os.chdir(startdir)
403
421
404
422
405 def test_xmode():
423 def test_xmode():
406 # Calling xmode three times should be a no-op
424 # Calling xmode three times should be a no-op
407 xmode = _ip.InteractiveTB.mode
425 xmode = _ip.InteractiveTB.mode
408 for i in range(3):
426 for i in range(3):
409 _ip.magic("xmode")
427 _ip.magic("xmode")
410 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
428 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
411
429
412 def test_reset_hard():
430 def test_reset_hard():
413 monitor = []
431 monitor = []
414 class A(object):
432 class A(object):
415 def __del__(self):
433 def __del__(self):
416 monitor.append(1)
434 monitor.append(1)
417 def __repr__(self):
435 def __repr__(self):
418 return "<A instance>"
436 return "<A instance>"
419
437
420 _ip.user_ns["a"] = A()
438 _ip.user_ns["a"] = A()
421 _ip.run_cell("a")
439 _ip.run_cell("a")
422
440
423 nt.assert_equal(monitor, [])
441 nt.assert_equal(monitor, [])
424 _ip.magic("reset -f")
442 _ip.magic("reset -f")
425 nt.assert_equal(monitor, [1])
443 nt.assert_equal(monitor, [1])
426
444
427 class TestXdel(tt.TempFileMixin):
445 class TestXdel(tt.TempFileMixin):
428 def test_xdel(self):
446 def test_xdel(self):
429 """Test that references from %run are cleared by xdel."""
447 """Test that references from %run are cleared by xdel."""
430 src = ("class A(object):\n"
448 src = ("class A(object):\n"
431 " monitor = []\n"
449 " monitor = []\n"
432 " def __del__(self):\n"
450 " def __del__(self):\n"
433 " self.monitor.append(1)\n"
451 " self.monitor.append(1)\n"
434 "a = A()\n")
452 "a = A()\n")
435 self.mktmp(src)
453 self.mktmp(src)
436 # %run creates some hidden references...
454 # %run creates some hidden references...
437 _ip.magic("run %s" % self.fname)
455 _ip.magic("run %s" % self.fname)
438 # ... as does the displayhook.
456 # ... as does the displayhook.
439 _ip.run_cell("a")
457 _ip.run_cell("a")
440
458
441 monitor = _ip.user_ns["A"].monitor
459 monitor = _ip.user_ns["A"].monitor
442 nt.assert_equal(monitor, [])
460 nt.assert_equal(monitor, [])
443
461
444 _ip.magic("xdel a")
462 _ip.magic("xdel a")
445
463
446 # Check that a's __del__ method has been called.
464 # Check that a's __del__ method has been called.
447 nt.assert_equal(monitor, [1])
465 nt.assert_equal(monitor, [1])
448
466
449 def doctest_who():
467 def doctest_who():
450 """doctest for %who
468 """doctest for %who
451
469
452 In [1]: %reset -f
470 In [1]: %reset -f
453
471
454 In [2]: alpha = 123
472 In [2]: alpha = 123
455
473
456 In [3]: beta = 'beta'
474 In [3]: beta = 'beta'
457
475
458 In [4]: %who int
476 In [4]: %who int
459 alpha
477 alpha
460
478
461 In [5]: %who str
479 In [5]: %who str
462 beta
480 beta
463
481
464 In [6]: %whos
482 In [6]: %whos
465 Variable Type Data/Info
483 Variable Type Data/Info
466 ----------------------------
484 ----------------------------
467 alpha int 123
485 alpha int 123
468 beta str beta
486 beta str beta
469
487
470 In [7]: %who_ls
488 In [7]: %who_ls
471 Out[7]: ['alpha', 'beta']
489 Out[7]: ['alpha', 'beta']
472 """
490 """
473
491
474 def test_whos():
492 def test_whos():
475 """Check that whos is protected against objects where repr() fails."""
493 """Check that whos is protected against objects where repr() fails."""
476 class A(object):
494 class A(object):
477 def __repr__(self):
495 def __repr__(self):
478 raise Exception()
496 raise Exception()
479 _ip.user_ns['a'] = A()
497 _ip.user_ns['a'] = A()
480 _ip.magic("whos")
498 _ip.magic("whos")
481
499
482 @py3compat.u_format
500 @py3compat.u_format
483 def doctest_precision():
501 def doctest_precision():
484 """doctest for %precision
502 """doctest for %precision
485
503
486 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
504 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
487
505
488 In [2]: %precision 5
506 In [2]: %precision 5
489 Out[2]: {u}'%.5f'
507 Out[2]: {u}'%.5f'
490
508
491 In [3]: f.float_format
509 In [3]: f.float_format
492 Out[3]: {u}'%.5f'
510 Out[3]: {u}'%.5f'
493
511
494 In [4]: %precision %e
512 In [4]: %precision %e
495 Out[4]: {u}'%e'
513 Out[4]: {u}'%e'
496
514
497 In [5]: f(3.1415927)
515 In [5]: f(3.1415927)
498 Out[5]: {u}'3.141593e+00'
516 Out[5]: {u}'3.141593e+00'
499 """
517 """
500
518
501 def test_psearch():
519 def test_psearch():
502 with tt.AssertPrints("dict.fromkeys"):
520 with tt.AssertPrints("dict.fromkeys"):
503 _ip.run_cell("dict.fr*?")
521 _ip.run_cell("dict.fr*?")
504
522
505 def test_timeit_shlex():
523 def test_timeit_shlex():
506 """test shlex issues with timeit (#1109)"""
524 """test shlex issues with timeit (#1109)"""
507 _ip.ex("def f(*a,**kw): pass")
525 _ip.ex("def f(*a,**kw): pass")
508 _ip.magic('timeit -n1 "this is a bug".count(" ")')
526 _ip.magic('timeit -n1 "this is a bug".count(" ")')
509 _ip.magic('timeit -r1 -n1 f(" ", 1)')
527 _ip.magic('timeit -r1 -n1 f(" ", 1)')
510 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
528 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
511 _ip.magic('timeit -r1 -n1 ("a " + "b")')
529 _ip.magic('timeit -r1 -n1 ("a " + "b")')
512 _ip.magic('timeit -r1 -n1 f("a " + "b")')
530 _ip.magic('timeit -r1 -n1 f("a " + "b")')
513 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
531 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
514
532
515
533
516 def test_timeit_arguments():
534 def test_timeit_arguments():
517 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
535 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
518 _ip.magic("timeit ('#')")
536 _ip.magic("timeit ('#')")
519
537
520
538
521 def test_timeit_special_syntax():
539 def test_timeit_special_syntax():
522 "Test %%timeit with IPython special syntax"
540 "Test %%timeit with IPython special syntax"
523 @register_line_magic
541 @register_line_magic
524 def lmagic(line):
542 def lmagic(line):
525 ip = get_ipython()
543 ip = get_ipython()
526 ip.user_ns['lmagic_out'] = line
544 ip.user_ns['lmagic_out'] = line
527
545
528 # line mode test
546 # line mode test
529 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
547 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
530 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
548 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
531 # cell mode test
549 # cell mode test
532 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
550 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
533 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
551 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
534
552
535 def test_timeit_return():
553 def test_timeit_return():
536 """
554 """
537 test wether timeit -o return object
555 test wether timeit -o return object
538 """
556 """
539
557
540 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
558 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
541 assert(res is not None)
559 assert(res is not None)
542
560
543 def test_timeit_quiet():
561 def test_timeit_quiet():
544 """
562 """
545 test quiet option of timeit magic
563 test quiet option of timeit magic
546 """
564 """
547 with tt.AssertNotPrints("loops"):
565 with tt.AssertNotPrints("loops"):
548 _ip.run_cell("%timeit -n1 -r1 -q 1")
566 _ip.run_cell("%timeit -n1 -r1 -q 1")
549
567
550 def test_timeit_return_quiet():
568 def test_timeit_return_quiet():
551 with tt.AssertNotPrints("loops"):
569 with tt.AssertNotPrints("loops"):
552 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
570 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
553 assert (res is not None)
571 assert (res is not None)
554
572
555 @dec.skipif(execution.profile is None)
573 @dec.skipif(execution.profile is None)
556 def test_prun_special_syntax():
574 def test_prun_special_syntax():
557 "Test %%prun with IPython special syntax"
575 "Test %%prun with IPython special syntax"
558 @register_line_magic
576 @register_line_magic
559 def lmagic(line):
577 def lmagic(line):
560 ip = get_ipython()
578 ip = get_ipython()
561 ip.user_ns['lmagic_out'] = line
579 ip.user_ns['lmagic_out'] = line
562
580
563 # line mode test
581 # line mode test
564 _ip.run_line_magic('prun', '-q %lmagic my line')
582 _ip.run_line_magic('prun', '-q %lmagic my line')
565 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
583 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
566 # cell mode test
584 # cell mode test
567 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
585 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
568 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
586 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
569
587
570 @dec.skipif(execution.profile is None)
588 @dec.skipif(execution.profile is None)
571 def test_prun_quotes():
589 def test_prun_quotes():
572 "Test that prun does not clobber string escapes (GH #1302)"
590 "Test that prun does not clobber string escapes (GH #1302)"
573 _ip.magic(r"prun -q x = '\t'")
591 _ip.magic(r"prun -q x = '\t'")
574 nt.assert_equal(_ip.user_ns['x'], '\t')
592 nt.assert_equal(_ip.user_ns['x'], '\t')
575
593
576 def test_extension():
594 def test_extension():
577 # Debugging information for failures of this test
595 # Debugging information for failures of this test
578 print('sys.path:')
596 print('sys.path:')
579 for p in sys.path:
597 for p in sys.path:
580 print(' ', p)
598 print(' ', p)
581 print('CWD', os.getcwd())
599 print('CWD', os.getcwd())
582
600
583 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
601 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
584 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
602 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
585 sys.path.insert(0, daft_path)
603 sys.path.insert(0, daft_path)
586 try:
604 try:
587 _ip.user_ns.pop('arq', None)
605 _ip.user_ns.pop('arq', None)
588 invalidate_caches() # Clear import caches
606 invalidate_caches() # Clear import caches
589 _ip.magic("load_ext daft_extension")
607 _ip.magic("load_ext daft_extension")
590 nt.assert_equal(_ip.user_ns['arq'], 185)
608 nt.assert_equal(_ip.user_ns['arq'], 185)
591 _ip.magic("unload_ext daft_extension")
609 _ip.magic("unload_ext daft_extension")
592 assert 'arq' not in _ip.user_ns
610 assert 'arq' not in _ip.user_ns
593 finally:
611 finally:
594 sys.path.remove(daft_path)
612 sys.path.remove(daft_path)
595
613
596
614
597 def test_notebook_export_json():
615 def test_notebook_export_json():
598 _ip = get_ipython()
616 _ip = get_ipython()
599 _ip.history_manager.reset() # Clear any existing history.
617 _ip.history_manager.reset() # Clear any existing history.
600 cmds = [u"a=1", u"def b():\n return a**2", u"print('noΓ«l, Γ©tΓ©', b())"]
618 cmds = [u"a=1", u"def b():\n return a**2", u"print('noΓ«l, Γ©tΓ©', b())"]
601 for i, cmd in enumerate(cmds, start=1):
619 for i, cmd in enumerate(cmds, start=1):
602 _ip.history_manager.store_inputs(i, cmd)
620 _ip.history_manager.store_inputs(i, cmd)
603 with TemporaryDirectory() as td:
621 with TemporaryDirectory() as td:
604 outfile = os.path.join(td, "nb.ipynb")
622 outfile = os.path.join(td, "nb.ipynb")
605 _ip.magic("notebook -e %s" % outfile)
623 _ip.magic("notebook -e %s" % outfile)
606
624
607
625
608 class TestEnv(TestCase):
626 class TestEnv(TestCase):
609
627
610 def test_env(self):
628 def test_env(self):
611 env = _ip.magic("env")
629 env = _ip.magic("env")
612 self.assertTrue(isinstance(env, dict))
630 self.assertTrue(isinstance(env, dict))
613
631
614 def test_env_get_set_simple(self):
632 def test_env_get_set_simple(self):
615 env = _ip.magic("env var val1")
633 env = _ip.magic("env var val1")
616 self.assertEqual(env, None)
634 self.assertEqual(env, None)
617 self.assertEqual(os.environ['var'], 'val1')
635 self.assertEqual(os.environ['var'], 'val1')
618 self.assertEqual(_ip.magic("env var"), 'val1')
636 self.assertEqual(_ip.magic("env var"), 'val1')
619 env = _ip.magic("env var=val2")
637 env = _ip.magic("env var=val2")
620 self.assertEqual(env, None)
638 self.assertEqual(env, None)
621 self.assertEqual(os.environ['var'], 'val2')
639 self.assertEqual(os.environ['var'], 'val2')
622
640
623 def test_env_get_set_complex(self):
641 def test_env_get_set_complex(self):
624 env = _ip.magic("env var 'val1 '' 'val2")
642 env = _ip.magic("env var 'val1 '' 'val2")
625 self.assertEqual(env, None)
643 self.assertEqual(env, None)
626 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
644 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
627 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
645 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
628 env = _ip.magic('env var=val2 val3="val4')
646 env = _ip.magic('env var=val2 val3="val4')
629 self.assertEqual(env, None)
647 self.assertEqual(env, None)
630 self.assertEqual(os.environ['var'], 'val2 val3="val4')
648 self.assertEqual(os.environ['var'], 'val2 val3="val4')
631
649
632 def test_env_set_bad_input(self):
650 def test_env_set_bad_input(self):
633 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
651 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
634
652
635 def test_env_set_whitespace(self):
653 def test_env_set_whitespace(self):
636 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
654 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
637
655
638
656
639 class CellMagicTestCase(TestCase):
657 class CellMagicTestCase(TestCase):
640
658
641 def check_ident(self, magic):
659 def check_ident(self, magic):
642 # Manually called, we get the result
660 # Manually called, we get the result
643 out = _ip.run_cell_magic(magic, 'a', 'b')
661 out = _ip.run_cell_magic(magic, 'a', 'b')
644 nt.assert_equal(out, ('a','b'))
662 nt.assert_equal(out, ('a','b'))
645 # Via run_cell, it goes into the user's namespace via displayhook
663 # Via run_cell, it goes into the user's namespace via displayhook
646 _ip.run_cell('%%' + magic +' c\nd')
664 _ip.run_cell('%%' + magic +' c\nd')
647 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
665 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
648
666
649 def test_cell_magic_func_deco(self):
667 def test_cell_magic_func_deco(self):
650 "Cell magic using simple decorator"
668 "Cell magic using simple decorator"
651 @register_cell_magic
669 @register_cell_magic
652 def cellm(line, cell):
670 def cellm(line, cell):
653 return line, cell
671 return line, cell
654
672
655 self.check_ident('cellm')
673 self.check_ident('cellm')
656
674
657 def test_cell_magic_reg(self):
675 def test_cell_magic_reg(self):
658 "Cell magic manually registered"
676 "Cell magic manually registered"
659 def cellm(line, cell):
677 def cellm(line, cell):
660 return line, cell
678 return line, cell
661
679
662 _ip.register_magic_function(cellm, 'cell', 'cellm2')
680 _ip.register_magic_function(cellm, 'cell', 'cellm2')
663 self.check_ident('cellm2')
681 self.check_ident('cellm2')
664
682
665 def test_cell_magic_class(self):
683 def test_cell_magic_class(self):
666 "Cell magics declared via a class"
684 "Cell magics declared via a class"
667 @magics_class
685 @magics_class
668 class MyMagics(Magics):
686 class MyMagics(Magics):
669
687
670 @cell_magic
688 @cell_magic
671 def cellm3(self, line, cell):
689 def cellm3(self, line, cell):
672 return line, cell
690 return line, cell
673
691
674 _ip.register_magics(MyMagics)
692 _ip.register_magics(MyMagics)
675 self.check_ident('cellm3')
693 self.check_ident('cellm3')
676
694
677 def test_cell_magic_class2(self):
695 def test_cell_magic_class2(self):
678 "Cell magics declared via a class, #2"
696 "Cell magics declared via a class, #2"
679 @magics_class
697 @magics_class
680 class MyMagics2(Magics):
698 class MyMagics2(Magics):
681
699
682 @cell_magic('cellm4')
700 @cell_magic('cellm4')
683 def cellm33(self, line, cell):
701 def cellm33(self, line, cell):
684 return line, cell
702 return line, cell
685
703
686 _ip.register_magics(MyMagics2)
704 _ip.register_magics(MyMagics2)
687 self.check_ident('cellm4')
705 self.check_ident('cellm4')
688 # Check that nothing is registered as 'cellm33'
706 # Check that nothing is registered as 'cellm33'
689 c33 = _ip.find_cell_magic('cellm33')
707 c33 = _ip.find_cell_magic('cellm33')
690 nt.assert_equal(c33, None)
708 nt.assert_equal(c33, None)
691
709
692 def test_file():
710 def test_file():
693 """Basic %%file"""
711 """Basic %%file"""
694 ip = get_ipython()
712 ip = get_ipython()
695 with TemporaryDirectory() as td:
713 with TemporaryDirectory() as td:
696 fname = os.path.join(td, 'file1')
714 fname = os.path.join(td, 'file1')
697 ip.run_cell_magic("file", fname, u'\n'.join([
715 ip.run_cell_magic("file", fname, u'\n'.join([
698 'line1',
716 'line1',
699 'line2',
717 'line2',
700 ]))
718 ]))
701 with open(fname) as f:
719 with open(fname) as f:
702 s = f.read()
720 s = f.read()
703 nt.assert_in('line1\n', s)
721 nt.assert_in('line1\n', s)
704 nt.assert_in('line2', s)
722 nt.assert_in('line2', s)
705
723
706 def test_file_var_expand():
724 def test_file_var_expand():
707 """%%file $filename"""
725 """%%file $filename"""
708 ip = get_ipython()
726 ip = get_ipython()
709 with TemporaryDirectory() as td:
727 with TemporaryDirectory() as td:
710 fname = os.path.join(td, 'file1')
728 fname = os.path.join(td, 'file1')
711 ip.user_ns['filename'] = fname
729 ip.user_ns['filename'] = fname
712 ip.run_cell_magic("file", '$filename', u'\n'.join([
730 ip.run_cell_magic("file", '$filename', u'\n'.join([
713 'line1',
731 'line1',
714 'line2',
732 'line2',
715 ]))
733 ]))
716 with open(fname) as f:
734 with open(fname) as f:
717 s = f.read()
735 s = f.read()
718 nt.assert_in('line1\n', s)
736 nt.assert_in('line1\n', s)
719 nt.assert_in('line2', s)
737 nt.assert_in('line2', s)
720
738
721 def test_file_unicode():
739 def test_file_unicode():
722 """%%file with unicode cell"""
740 """%%file with unicode cell"""
723 ip = get_ipython()
741 ip = get_ipython()
724 with TemporaryDirectory() as td:
742 with TemporaryDirectory() as td:
725 fname = os.path.join(td, 'file1')
743 fname = os.path.join(td, 'file1')
726 ip.run_cell_magic("file", fname, u'\n'.join([
744 ip.run_cell_magic("file", fname, u'\n'.join([
727 u'linΓ©1',
745 u'linΓ©1',
728 u'linΓ©2',
746 u'linΓ©2',
729 ]))
747 ]))
730 with io.open(fname, encoding='utf-8') as f:
748 with io.open(fname, encoding='utf-8') as f:
731 s = f.read()
749 s = f.read()
732 nt.assert_in(u'linΓ©1\n', s)
750 nt.assert_in(u'linΓ©1\n', s)
733 nt.assert_in(u'linΓ©2', s)
751 nt.assert_in(u'linΓ©2', s)
734
752
735 def test_file_amend():
753 def test_file_amend():
736 """%%file -a amends files"""
754 """%%file -a amends files"""
737 ip = get_ipython()
755 ip = get_ipython()
738 with TemporaryDirectory() as td:
756 with TemporaryDirectory() as td:
739 fname = os.path.join(td, 'file2')
757 fname = os.path.join(td, 'file2')
740 ip.run_cell_magic("file", fname, u'\n'.join([
758 ip.run_cell_magic("file", fname, u'\n'.join([
741 'line1',
759 'line1',
742 'line2',
760 'line2',
743 ]))
761 ]))
744 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
762 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
745 'line3',
763 'line3',
746 'line4',
764 'line4',
747 ]))
765 ]))
748 with open(fname) as f:
766 with open(fname) as f:
749 s = f.read()
767 s = f.read()
750 nt.assert_in('line1\n', s)
768 nt.assert_in('line1\n', s)
751 nt.assert_in('line3\n', s)
769 nt.assert_in('line3\n', s)
752
770
753
771
754 def test_script_config():
772 def test_script_config():
755 ip = get_ipython()
773 ip = get_ipython()
756 ip.config.ScriptMagics.script_magics = ['whoda']
774 ip.config.ScriptMagics.script_magics = ['whoda']
757 sm = script.ScriptMagics(shell=ip)
775 sm = script.ScriptMagics(shell=ip)
758 nt.assert_in('whoda', sm.magics['cell'])
776 nt.assert_in('whoda', sm.magics['cell'])
759
777
760 @dec.skip_win32
778 @dec.skip_win32
761 def test_script_out():
779 def test_script_out():
762 ip = get_ipython()
780 ip = get_ipython()
763 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
781 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
764 nt.assert_equal(ip.user_ns['output'], 'hi\n')
782 nt.assert_equal(ip.user_ns['output'], 'hi\n')
765
783
766 @dec.skip_win32
784 @dec.skip_win32
767 def test_script_err():
785 def test_script_err():
768 ip = get_ipython()
786 ip = get_ipython()
769 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
787 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
770 nt.assert_equal(ip.user_ns['error'], 'hello\n')
788 nt.assert_equal(ip.user_ns['error'], 'hello\n')
771
789
772 @dec.skip_win32
790 @dec.skip_win32
773 def test_script_out_err():
791 def test_script_out_err():
774 ip = get_ipython()
792 ip = get_ipython()
775 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
793 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
776 nt.assert_equal(ip.user_ns['output'], 'hi\n')
794 nt.assert_equal(ip.user_ns['output'], 'hi\n')
777 nt.assert_equal(ip.user_ns['error'], 'hello\n')
795 nt.assert_equal(ip.user_ns['error'], 'hello\n')
778
796
779 @dec.skip_win32
797 @dec.skip_win32
780 def test_script_bg_out():
798 def test_script_bg_out():
781 ip = get_ipython()
799 ip = get_ipython()
782 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
800 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
783 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
801 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
784
802
785 @dec.skip_win32
803 @dec.skip_win32
786 def test_script_bg_err():
804 def test_script_bg_err():
787 ip = get_ipython()
805 ip = get_ipython()
788 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
806 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
789 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
807 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
790
808
791 @dec.skip_win32
809 @dec.skip_win32
792 def test_script_bg_out_err():
810 def test_script_bg_out_err():
793 ip = get_ipython()
811 ip = get_ipython()
794 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
812 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
795 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
813 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
796 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
814 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
797
815
798 def test_script_defaults():
816 def test_script_defaults():
799 ip = get_ipython()
817 ip = get_ipython()
800 for cmd in ['sh', 'bash', 'perl', 'ruby']:
818 for cmd in ['sh', 'bash', 'perl', 'ruby']:
801 try:
819 try:
802 find_cmd(cmd)
820 find_cmd(cmd)
803 except Exception:
821 except Exception:
804 pass
822 pass
805 else:
823 else:
806 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
824 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
807
825
808
826
809 @magics_class
827 @magics_class
810 class FooFoo(Magics):
828 class FooFoo(Magics):
811 """class with both %foo and %%foo magics"""
829 """class with both %foo and %%foo magics"""
812 @line_magic('foo')
830 @line_magic('foo')
813 def line_foo(self, line):
831 def line_foo(self, line):
814 "I am line foo"
832 "I am line foo"
815 pass
833 pass
816
834
817 @cell_magic("foo")
835 @cell_magic("foo")
818 def cell_foo(self, line, cell):
836 def cell_foo(self, line, cell):
819 "I am cell foo, not line foo"
837 "I am cell foo, not line foo"
820 pass
838 pass
821
839
822 def test_line_cell_info():
840 def test_line_cell_info():
823 """%%foo and %foo magics are distinguishable to inspect"""
841 """%%foo and %foo magics are distinguishable to inspect"""
824 ip = get_ipython()
842 ip = get_ipython()
825 ip.magics_manager.register(FooFoo)
843 ip.magics_manager.register(FooFoo)
826 oinfo = ip.object_inspect('foo')
844 oinfo = ip.object_inspect('foo')
827 nt.assert_true(oinfo['found'])
845 nt.assert_true(oinfo['found'])
828 nt.assert_true(oinfo['ismagic'])
846 nt.assert_true(oinfo['ismagic'])
829
847
830 oinfo = ip.object_inspect('%%foo')
848 oinfo = ip.object_inspect('%%foo')
831 nt.assert_true(oinfo['found'])
849 nt.assert_true(oinfo['found'])
832 nt.assert_true(oinfo['ismagic'])
850 nt.assert_true(oinfo['ismagic'])
833 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
851 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
834
852
835 oinfo = ip.object_inspect('%foo')
853 oinfo = ip.object_inspect('%foo')
836 nt.assert_true(oinfo['found'])
854 nt.assert_true(oinfo['found'])
837 nt.assert_true(oinfo['ismagic'])
855 nt.assert_true(oinfo['ismagic'])
838 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
856 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
839
857
840 def test_multiple_magics():
858 def test_multiple_magics():
841 ip = get_ipython()
859 ip = get_ipython()
842 foo1 = FooFoo(ip)
860 foo1 = FooFoo(ip)
843 foo2 = FooFoo(ip)
861 foo2 = FooFoo(ip)
844 mm = ip.magics_manager
862 mm = ip.magics_manager
845 mm.register(foo1)
863 mm.register(foo1)
846 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
864 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
847 mm.register(foo2)
865 mm.register(foo2)
848 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
866 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
849
867
850 def test_alias_magic():
868 def test_alias_magic():
851 """Test %alias_magic."""
869 """Test %alias_magic."""
852 ip = get_ipython()
870 ip = get_ipython()
853 mm = ip.magics_manager
871 mm = ip.magics_manager
854
872
855 # Basic operation: both cell and line magics are created, if possible.
873 # Basic operation: both cell and line magics are created, if possible.
856 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
874 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
857 nt.assert_in('timeit_alias', mm.magics['line'])
875 nt.assert_in('timeit_alias', mm.magics['line'])
858 nt.assert_in('timeit_alias', mm.magics['cell'])
876 nt.assert_in('timeit_alias', mm.magics['cell'])
859
877
860 # --cell is specified, line magic not created.
878 # --cell is specified, line magic not created.
861 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
879 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
862 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
880 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
863 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
881 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
864
882
865 # Test that line alias is created successfully.
883 # Test that line alias is created successfully.
866 ip.run_line_magic('alias_magic', '--line env_alias env')
884 ip.run_line_magic('alias_magic', '--line env_alias env')
867 nt.assert_equal(ip.run_line_magic('env', ''),
885 nt.assert_equal(ip.run_line_magic('env', ''),
868 ip.run_line_magic('env_alias', ''))
886 ip.run_line_magic('env_alias', ''))
869
887
870 def test_save():
888 def test_save():
871 """Test %save."""
889 """Test %save."""
872 ip = get_ipython()
890 ip = get_ipython()
873 ip.history_manager.reset() # Clear any existing history.
891 ip.history_manager.reset() # Clear any existing history.
874 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
892 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
875 for i, cmd in enumerate(cmds, start=1):
893 for i, cmd in enumerate(cmds, start=1):
876 ip.history_manager.store_inputs(i, cmd)
894 ip.history_manager.store_inputs(i, cmd)
877 with TemporaryDirectory() as tmpdir:
895 with TemporaryDirectory() as tmpdir:
878 file = os.path.join(tmpdir, "testsave.py")
896 file = os.path.join(tmpdir, "testsave.py")
879 ip.run_line_magic("save", "%s 1-10" % file)
897 ip.run_line_magic("save", "%s 1-10" % file)
880 with open(file) as f:
898 with open(file) as f:
881 content = f.read()
899 content = f.read()
882 nt.assert_equal(content.count(cmds[0]), 1)
900 nt.assert_equal(content.count(cmds[0]), 1)
883 nt.assert_in('coding: utf-8', content)
901 nt.assert_in('coding: utf-8', content)
884 ip.run_line_magic("save", "-a %s 1-10" % file)
902 ip.run_line_magic("save", "-a %s 1-10" % file)
885 with open(file) as f:
903 with open(file) as f:
886 content = f.read()
904 content = f.read()
887 nt.assert_equal(content.count(cmds[0]), 2)
905 nt.assert_equal(content.count(cmds[0]), 2)
888 nt.assert_in('coding: utf-8', content)
906 nt.assert_in('coding: utf-8', content)
889
907
890
908
891 def test_store():
909 def test_store():
892 """Test %store."""
910 """Test %store."""
893 ip = get_ipython()
911 ip = get_ipython()
894 ip.run_line_magic('load_ext', 'storemagic')
912 ip.run_line_magic('load_ext', 'storemagic')
895
913
896 # make sure the storage is empty
914 # make sure the storage is empty
897 ip.run_line_magic('store', '-z')
915 ip.run_line_magic('store', '-z')
898 ip.user_ns['var'] = 42
916 ip.user_ns['var'] = 42
899 ip.run_line_magic('store', 'var')
917 ip.run_line_magic('store', 'var')
900 ip.user_ns['var'] = 39
918 ip.user_ns['var'] = 39
901 ip.run_line_magic('store', '-r')
919 ip.run_line_magic('store', '-r')
902 nt.assert_equal(ip.user_ns['var'], 42)
920 nt.assert_equal(ip.user_ns['var'], 42)
903
921
904 ip.run_line_magic('store', '-d var')
922 ip.run_line_magic('store', '-d var')
905 ip.user_ns['var'] = 39
923 ip.user_ns['var'] = 39
906 ip.run_line_magic('store' , '-r')
924 ip.run_line_magic('store' , '-r')
907 nt.assert_equal(ip.user_ns['var'], 39)
925 nt.assert_equal(ip.user_ns['var'], 39)
908
926
909
927
910 def _run_edit_test(arg_s, exp_filename=None,
928 def _run_edit_test(arg_s, exp_filename=None,
911 exp_lineno=-1,
929 exp_lineno=-1,
912 exp_contents=None,
930 exp_contents=None,
913 exp_is_temp=None):
931 exp_is_temp=None):
914 ip = get_ipython()
932 ip = get_ipython()
915 M = code.CodeMagics(ip)
933 M = code.CodeMagics(ip)
916 last_call = ['','']
934 last_call = ['','']
917 opts,args = M.parse_options(arg_s,'prxn:')
935 opts,args = M.parse_options(arg_s,'prxn:')
918 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
936 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
919
937
920 if exp_filename is not None:
938 if exp_filename is not None:
921 nt.assert_equal(exp_filename, filename)
939 nt.assert_equal(exp_filename, filename)
922 if exp_contents is not None:
940 if exp_contents is not None:
923 with io.open(filename, 'r', encoding='utf-8') as f:
941 with io.open(filename, 'r', encoding='utf-8') as f:
924 contents = f.read()
942 contents = f.read()
925 nt.assert_equal(exp_contents, contents)
943 nt.assert_equal(exp_contents, contents)
926 if exp_lineno != -1:
944 if exp_lineno != -1:
927 nt.assert_equal(exp_lineno, lineno)
945 nt.assert_equal(exp_lineno, lineno)
928 if exp_is_temp is not None:
946 if exp_is_temp is not None:
929 nt.assert_equal(exp_is_temp, is_temp)
947 nt.assert_equal(exp_is_temp, is_temp)
930
948
931
949
932 def test_edit_interactive():
950 def test_edit_interactive():
933 """%edit on interactively defined objects"""
951 """%edit on interactively defined objects"""
934 ip = get_ipython()
952 ip = get_ipython()
935 n = ip.execution_count
953 n = ip.execution_count
936 ip.run_cell(u"def foo(): return 1", store_history=True)
954 ip.run_cell(u"def foo(): return 1", store_history=True)
937
955
938 try:
956 try:
939 _run_edit_test("foo")
957 _run_edit_test("foo")
940 except code.InteractivelyDefined as e:
958 except code.InteractivelyDefined as e:
941 nt.assert_equal(e.index, n)
959 nt.assert_equal(e.index, n)
942 else:
960 else:
943 raise AssertionError("Should have raised InteractivelyDefined")
961 raise AssertionError("Should have raised InteractivelyDefined")
944
962
945
963
946 def test_edit_cell():
964 def test_edit_cell():
947 """%edit [cell id]"""
965 """%edit [cell id]"""
948 ip = get_ipython()
966 ip = get_ipython()
949
967
950 ip.run_cell(u"def foo(): return 1", store_history=True)
968 ip.run_cell(u"def foo(): return 1", store_history=True)
951
969
952 # test
970 # test
953 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
971 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
954
972
955 def test_bookmark():
973 def test_bookmark():
956 ip = get_ipython()
974 ip = get_ipython()
957 ip.run_line_magic('bookmark', 'bmname')
975 ip.run_line_magic('bookmark', 'bmname')
958 with tt.AssertPrints('bmname'):
976 with tt.AssertPrints('bmname'):
959 ip.run_line_magic('bookmark', '-l')
977 ip.run_line_magic('bookmark', '-l')
960 ip.run_line_magic('bookmark', '-d bmname')
978 ip.run_line_magic('bookmark', '-d bmname')
961
979
962 def test_ls_magic():
980 def test_ls_magic():
963 ip = get_ipython()
981 ip = get_ipython()
964 json_formatter = ip.display_formatter.formatters['application/json']
982 json_formatter = ip.display_formatter.formatters['application/json']
965 json_formatter.enabled = True
983 json_formatter.enabled = True
966 lsmagic = ip.magic('lsmagic')
984 lsmagic = ip.magic('lsmagic')
967 with warnings.catch_warnings(record=True) as w:
985 with warnings.catch_warnings(record=True) as w:
968 j = json_formatter(lsmagic)
986 j = json_formatter(lsmagic)
969 nt.assert_equal(sorted(j), ['cell', 'line'])
987 nt.assert_equal(sorted(j), ['cell', 'line'])
970 nt.assert_equal(w, []) # no warnings
988 nt.assert_equal(w, []) # no warnings
971
989
972 def test_strip_initial_indent():
990 def test_strip_initial_indent():
973 def sii(s):
991 def sii(s):
974 lines = s.splitlines()
992 lines = s.splitlines()
975 return '\n'.join(code.strip_initial_indent(lines))
993 return '\n'.join(code.strip_initial_indent(lines))
976
994
977 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
995 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
978 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
996 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
979 nt.assert_equal(sii("a\n b"), "a\n b")
997 nt.assert_equal(sii("a\n b"), "a\n b")
General Comments 0
You need to be logged in to leave comments. Login now