##// END OF EJS Templates
Make the example values in the default ipython_config.py the same as the default settings.
Thomas Kluyver -
Show More
@@ -1,161 +1,161 b''
1 # Get the config being loaded so we can set attributes on it
1 # Get the config being loaded so we can set attributes on it
2 c = get_config()
2 c = get_config()
3
3
4 #-----------------------------------------------------------------------------
4 #-----------------------------------------------------------------------------
5 # Global options
5 # Global options
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7
7
8 # c.Global.display_banner = True
8 # c.Global.display_banner = True
9
9
10 # c.Global.classic = False
10 # c.Global.classic = False
11
11
12 # c.Global.nosep = True
12 # c.Global.nosep = True
13
13
14 # Set this to determine the detail of what is logged at startup.
14 # Set this to determine the detail of what is logged at startup.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
15 # The default is 30 and possible values are 0,10,20,30,40,50.
16 # c.Global.log_level = 20
16 # c.Global.log_level = 20
17
17
18 # This should be a list of importable Python modules that have an
18 # This should be a list of importable Python modules that have an
19 # load_in_ipython(ip) method. This method gets called when the extension
19 # load_in_ipython(ip) method. This method gets called when the extension
20 # is loaded. You can put your extensions anywhere they can be imported
20 # is loaded. You can put your extensions anywhere they can be imported
21 # but we add the extensions subdir of the ipython directory to sys.path
21 # but we add the extensions subdir of the ipython directory to sys.path
22 # during extension loading, so you can put them there as well.
22 # during extension loading, so you can put them there as well.
23 # c.Global.extensions = [
23 # c.Global.extensions = [
24 # 'myextension'
24 # 'myextension'
25 # ]
25 # ]
26
26
27 # These lines are run in IPython in the user's namespace after extensions
27 # These lines are run in IPython in the user's namespace after extensions
28 # are loaded. They can contain full IPython syntax with magics etc.
28 # are loaded. They can contain full IPython syntax with magics etc.
29 # c.Global.exec_lines = [
29 # c.Global.exec_lines = [
30 # 'import numpy',
30 # 'import numpy',
31 # 'a = 10; b = 20',
31 # 'a = 10; b = 20',
32 # '1/0'
32 # '1/0'
33 # ]
33 # ]
34
34
35 # These files are run in IPython in the user's namespace. Files with a .py
35 # These files are run in IPython in the user's namespace. Files with a .py
36 # extension need to be pure Python. Files with a .ipy extension can have
36 # extension need to be pure Python. Files with a .ipy extension can have
37 # custom IPython syntax (like magics, etc.).
37 # custom IPython syntax (like magics, etc.).
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
38 # These files need to be in the cwd, the ipython_dir or be absolute paths.
39 # c.Global.exec_files = [
39 # c.Global.exec_files = [
40 # 'mycode.py',
40 # 'mycode.py',
41 # 'fancy.ipy'
41 # 'fancy.ipy'
42 # ]
42 # ]
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # InteractiveShell options
45 # InteractiveShell options
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 # c.InteractiveShell.autocall = 1
48 # c.InteractiveShell.autocall = 1
49
49
50 # c.TerminalInteractiveShell.autoedit_syntax = False
50 # c.TerminalInteractiveShell.autoedit_syntax = False
51
51
52 # c.InteractiveShell.autoindent = True
52 # c.InteractiveShell.autoindent = True
53
53
54 # c.InteractiveShell.automagic = False
54 # c.InteractiveShell.automagic = False
55
55
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
56 # c.TerminalTerminalInteractiveShell.banner1 = 'This if for overriding the default IPython banner'
57
57
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
58 # c.TerminalTerminalInteractiveShell.banner2 = "This is for extra banner text"
59
59
60 # c.InteractiveShell.cache_size = 1000
60 # c.InteractiveShell.cache_size = 1000
61
61
62 # c.InteractiveShell.colors = 'LightBG'
62 # c.InteractiveShell.colors = 'LightBG'
63
63
64 # c.InteractiveShell.color_info = True
64 # c.InteractiveShell.color_info = True
65
65
66 # c.TerminalInteractiveShell.confirm_exit = True
66 # c.TerminalInteractiveShell.confirm_exit = True
67
67
68 # c.InteractiveShell.deep_reload = False
68 # c.InteractiveShell.deep_reload = False
69
69
70 # c.TerminalInteractiveShell.editor = 'nano'
70 # c.TerminalInteractiveShell.editor = 'nano'
71
71
72 # c.InteractiveShell.logstart = True
72 # c.InteractiveShell.logstart = True
73
73
74 # c.InteractiveShell.logfile = u'ipython_log.py'
74 # c.InteractiveShell.logfile = u'ipython_log.py'
75
75
76 # c.InteractiveShell.logappend = u'mylog.py'
76 # c.InteractiveShell.logappend = u'mylog.py'
77
77
78 # c.InteractiveShell.object_info_string_level = 0
78 # c.InteractiveShell.object_info_string_level = 0
79
79
80 # c.TerminalInteractiveShell.pager = 'less'
80 # c.TerminalInteractiveShell.pager = 'less'
81
81
82 # c.InteractiveShell.pdb = False
82 # c.InteractiveShell.pdb = False
83
83
84 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
84 # c.InteractiveShell.prompt_in1 = 'In [\#]: '
85 # c.InteractiveShell.prompt_in2 = ' .\D.: '
85 # c.InteractiveShell.prompt_in2 = ' .\D.: '
86 # c.InteractiveShell.prompt_out = 'Out[\#]: '
86 # c.InteractiveShell.prompt_out = 'Out[\#]: '
87 # c.InteractiveShell.prompts_pad_left = True
87 # c.InteractiveShell.prompts_pad_left = True
88
88
89 # c.InteractiveShell.quiet = False
89 # c.InteractiveShell.quiet = False
90
90
91 # c.InteractiveShell.history_length = 10000
91 # c.InteractiveShell.history_length = 10000
92
92
93 # Readline
93 # Readline
94 # c.InteractiveShell.readline_use = True
94 # c.InteractiveShell.readline_use = True
95
95
96 # c.InteractiveShell.readline_parse_and_bind = [
96 # c.InteractiveShell.readline_parse_and_bind = [
97 # 'tab: complete',
97 # 'tab: complete',
98 # '"\C-l": possible-completions',
98 # '"\C-l": possible-completions',
99 # 'set show-all-if-ambiguous on',
99 # 'set show-all-if-ambiguous on',
100 # '"\C-o": tab-insert',
100 # '"\C-o": tab-insert',
101 # '"\M-i": " "',
101 # '"\M-i": " "',
102 # '"\M-o": "\d\d\d\d"',
102 # '"\M-o": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
103 # '"\M-I": "\d\d\d\d"',
104 # '"\C-r": reverse-search-history',
104 # '"\C-r": reverse-search-history',
105 # '"\C-s": forward-search-history',
105 # '"\C-s": forward-search-history',
106 # '"\C-p": history-search-backward',
106 # '"\C-p": history-search-backward',
107 # '"\C-n": history-search-forward',
107 # '"\C-n": history-search-forward',
108 # '"\e[A": history-search-backward',
108 # '"\e[A": history-search-backward',
109 # '"\e[B": history-search-forward',
109 # '"\e[B": history-search-forward',
110 # '"\C-k": kill-line',
110 # '"\C-k": kill-line',
111 # '"\C-u": unix-line-discard',
111 # '"\C-u": unix-line-discard',
112 # ]
112 # ]
113 # c.InteractiveShell.readline_remove_delims = '-/~'
113 # c.InteractiveShell.readline_remove_delims = '-/~'
114 # c.InteractiveShell.readline_merge_completions = True
114 # c.InteractiveShell.readline_merge_completions = True
115 # c.InteractiveShell.readline_omit__names = 0
115 # c.InteractiveShell.readline_omit__names = 0
116
116
117 # c.TerminalInteractiveShell.screen_length = 0
117 # c.TerminalInteractiveShell.screen_length = 0
118
118
119 # c.InteractiveShell.separate_in = '\n'
119 # c.InteractiveShell.separate_in = '\n'
120 # c.InteractiveShell.separate_out = ''
120 # c.InteractiveShell.separate_out = ''
121 # c.InteractiveShell.separate_out2 = ''
121 # c.InteractiveShell.separate_out2 = ''
122
122
123 # c.TerminalInteractiveShell.term_title = False
123 # c.TerminalInteractiveShell.term_title = False
124
124
125 # c.InteractiveShell.wildcards_case_sensitive = True
125 # c.InteractiveShell.wildcards_case_sensitive = True
126
126
127 # c.InteractiveShell.xmode = 'Context'
127 # c.InteractiveShell.xmode = 'Context'
128
128
129 #-----------------------------------------------------------------------------
129 #-----------------------------------------------------------------------------
130 # Formatter and display options
130 # Formatter and display options
131 #-----------------------------------------------------------------------------
131 #-----------------------------------------------------------------------------
132
132
133 # c.PlainTextFormatter.pprint = True
133 # c.PlainTextFormatter.pprint = True
134
134
135 #-----------------------------------------------------------------------------
135 #-----------------------------------------------------------------------------
136 # PrefilterManager options
136 # PrefilterManager options
137 #-----------------------------------------------------------------------------
137 #-----------------------------------------------------------------------------
138
138
139 # c.PrefilterManager.multi_line_specials = True
139 # c.PrefilterManager.multi_line_specials = True
140
140
141 #-----------------------------------------------------------------------------
141 #-----------------------------------------------------------------------------
142 # AliasManager options
142 # AliasManager options
143 #-----------------------------------------------------------------------------
143 #-----------------------------------------------------------------------------
144
144
145 # Do this to disable all defaults
145 # Do this to disable all defaults
146 # c.AliasManager.default_aliases = []
146 # c.AliasManager.default_aliases = []
147
147
148 # c.AliasManager.user_aliases = [
148 # c.AliasManager.user_aliases = [
149 # ('foo', 'echo Hi')
149 # ('foo', 'echo Hi')
150 # ]
150 # ]
151
151
152 #-----------------------------------------------------------------------------
152 #-----------------------------------------------------------------------------
153 # HistoryManager options
153 # HistoryManager options
154 #-----------------------------------------------------------------------------
154 #-----------------------------------------------------------------------------
155
155
156 # Enable logging output as well as input to the database.
156 # Enable logging output as well as input to the database.
157 # c.HistoryManager.db_log_output = True
157 # c.HistoryManager.db_log_output = False
158
158
159 # Only write to the database every 40 commands - this can save disk access (and
159 # Only write to the database every n commands - this can save disk
160 # hence power) over the default of writing on every command.
160 # access (and hence power) over the default of writing on every command.
161 # c.HistoryManager.db_cache_size = 40
161 # c.HistoryManager.db_cache_size = 0
@@ -1,419 +1,417 b''
1 """Tests for various magic functions.
1 """Tests for various magic functions.
2
2
3 Needs to be run by nose (to make ipython session available).
3 Needs to be run by nose (to make ipython session available).
4 """
4 """
5 from __future__ import absolute_import
5 from __future__ import absolute_import
6
6
7 #-----------------------------------------------------------------------------
7 #-----------------------------------------------------------------------------
8 # Imports
8 # Imports
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 import os
11 import os
12 import sys
12 import sys
13 import tempfile
13 import tempfile
14 import types
14 import types
15 from cStringIO import StringIO
15 from cStringIO import StringIO
16
16
17 import nose.tools as nt
17 import nose.tools as nt
18
18
19 from IPython.utils.path import get_long_path_name
19 from IPython.utils.path import get_long_path_name
20 from IPython.testing import decorators as dec
20 from IPython.testing import decorators as dec
21 from IPython.testing import tools as tt
21 from IPython.testing import tools as tt
22
22
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24 # Test functions begin
24 # Test functions begin
25 #-----------------------------------------------------------------------------
25 #-----------------------------------------------------------------------------
26 def test_rehashx():
26 def test_rehashx():
27 # clear up everything
27 # clear up everything
28 _ip = get_ipython()
28 _ip = get_ipython()
29 _ip.alias_manager.alias_table.clear()
29 _ip.alias_manager.alias_table.clear()
30 del _ip.db['syscmdlist']
30 del _ip.db['syscmdlist']
31
31
32 _ip.magic('rehashx')
32 _ip.magic('rehashx')
33 # Practically ALL ipython development systems will have more than 10 aliases
33 # Practically ALL ipython development systems will have more than 10 aliases
34
34
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
35 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
36 for key, val in _ip.alias_manager.alias_table.iteritems():
36 for key, val in _ip.alias_manager.alias_table.iteritems():
37 # we must strip dots from alias names
37 # we must strip dots from alias names
38 nt.assert_true('.' not in key)
38 nt.assert_true('.' not in key)
39
39
40 # rehashx must fill up syscmdlist
40 # rehashx must fill up syscmdlist
41 scoms = _ip.db['syscmdlist']
41 scoms = _ip.db['syscmdlist']
42 yield (nt.assert_true, len(scoms) > 10)
42 yield (nt.assert_true, len(scoms) > 10)
43
43
44
44
45 def test_magic_parse_options():
45 def test_magic_parse_options():
46 """Test that we don't mangle paths when parsing magic options."""
46 """Test that we don't mangle paths when parsing magic options."""
47 ip = get_ipython()
47 ip = get_ipython()
48 path = 'c:\\x'
48 path = 'c:\\x'
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
49 opts = ip.parse_options('-f %s' % path,'f:')[0]
50 # argv splitting is os-dependent
50 # argv splitting is os-dependent
51 if os.name == 'posix':
51 if os.name == 'posix':
52 expected = 'c:x'
52 expected = 'c:x'
53 else:
53 else:
54 expected = path
54 expected = path
55 nt.assert_equals(opts['f'], expected)
55 nt.assert_equals(opts['f'], expected)
56
56
57
57
58 def doctest_hist_f():
58 def doctest_hist_f():
59 """Test %hist -f with temporary filename.
59 """Test %hist -f with temporary filename.
60
60
61 In [9]: import tempfile
61 In [9]: import tempfile
62
62
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
63 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
64
64
65 In [11]: %hist -nl -f $tfile 3
65 In [11]: %hist -nl -f $tfile 3
66
66
67 In [13]: import os; os.unlink(tfile)
67 In [13]: import os; os.unlink(tfile)
68 """
68 """
69
69
70
70
71 def doctest_hist_r():
71 def doctest_hist_r():
72 """Test %hist -r
72 """Test %hist -r
73
73
74 XXX - This test is not recording the output correctly. For some reason, in
74 XXX - This test is not recording the output correctly. For some reason, in
75 testing mode the raw history isn't getting populated. No idea why.
75 testing mode the raw history isn't getting populated. No idea why.
76 Disabling the output checking for now, though at least we do run it.
76 Disabling the output checking for now, though at least we do run it.
77
77
78 In [1]: 'hist' in _ip.lsmagic()
78 In [1]: 'hist' in _ip.lsmagic()
79 Out[1]: True
79 Out[1]: True
80
80
81 In [2]: x=1
81 In [2]: x=1
82
82
83 In [3]: %hist -rl 2
83 In [3]: %hist -rl 2
84 x=1 # random
84 x=1 # random
85 %hist -r 2
85 %hist -r 2
86 """
86 """
87
87
88 def doctest_hist_op():
88 def doctest_hist_op():
89 """Test %hist -op
89 """Test %hist -op
90
90
91 In [1]: class b:
91 In [1]: class b:
92 ...: pass
92 ...: pass
93 ...:
93 ...:
94
94
95 In [2]: class s(b):
95 In [2]: class s(b):
96 ...: def __str__(self):
96 ...: def __str__(self):
97 ...: return 's'
97 ...: return 's'
98 ...:
98 ...:
99
99
100 In [3]:
100 In [3]:
101
101
102 In [4]: class r(b):
102 In [4]: class r(b):
103 ...: def __repr__(self):
103 ...: def __repr__(self):
104 ...: return 'r'
104 ...: return 'r'
105 ...:
105 ...:
106
106
107 In [5]: class sr(s,r): pass
107 In [5]: class sr(s,r): pass
108 ...:
108 ...:
109
109
110 In [6]:
110 In [6]:
111
111
112 In [7]: bb=b()
112 In [7]: bb=b()
113
113
114 In [8]: ss=s()
114 In [8]: ss=s()
115
115
116 In [9]: rr=r()
116 In [9]: rr=r()
117
117
118 In [10]: ssrr=sr()
118 In [10]: ssrr=sr()
119
119
120 In [11]: bb
120 In [11]: bb
121 Out[11]: <...b instance at ...>
121 Out[11]: <...b instance at ...>
122
122
123 In [12]: ss
123 In [12]: ss
124 Out[12]: <...s instance at ...>
124 Out[12]: <...s instance at ...>
125
125
126 In [13]:
126 In [13]:
127
127
128 In [14]: %hist -op
128 In [14]: %hist -op
129 >>> class b:
129 >>> class b:
130 ... pass
130 ... pass
131 ...
131 ...
132 >>> class s(b):
132 >>> class s(b):
133 ... def __str__(self):
133 ... def __str__(self):
134 ... return 's'
134 ... return 's'
135 ...
135 ...
136 >>>
136 >>>
137 >>> class r(b):
137 >>> class r(b):
138 ... def __repr__(self):
138 ... def __repr__(self):
139 ... return 'r'
139 ... return 'r'
140 ...
140 ...
141 >>> class sr(s,r): pass
141 >>> class sr(s,r): pass
142 >>>
142 >>>
143 >>> bb=b()
143 >>> bb=b()
144 >>> ss=s()
144 >>> ss=s()
145 >>> rr=r()
145 >>> rr=r()
146 >>> ssrr=sr()
146 >>> ssrr=sr()
147 >>> bb
147 >>> bb
148 <...b instance at ...>
148 <...b instance at ...>
149 >>> ss
149 >>> ss
150 <...s instance at ...>
150 <...s instance at ...>
151 >>>
151 >>>
152 """
152 """
153
153
154 def test_macro():
154 def test_macro():
155 ip = get_ipython()
155 ip = get_ipython()
156 ip.history_manager.reset() # Clear any existing history.
156 ip.history_manager.reset() # Clear any existing history.
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
157 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
158 for i, cmd in enumerate(cmds, start=1):
158 for i, cmd in enumerate(cmds, start=1):
159 ip.history_manager.store_inputs(i, cmd)
159 ip.history_manager.store_inputs(i, cmd)
160 ip.magic("macro test 1-3")
160 ip.magic("macro test 1-3")
161 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
161 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
162
162
163 # List macros.
163 # List macros.
164 assert "test" in ip.magic("macro")
164 assert "test" in ip.magic("macro")
165
165
166 # XXX This should be a doctest, but the doctest logic doesn't seem to do
167 # dynamic transformations (like expanding macros). Doing it like this for now.
168 def test_macro_run():
166 def test_macro_run():
169 """Test that we can run a multi-line macro successfully."""
167 """Test that we can run a multi-line macro successfully."""
170 ip = get_ipython()
168 ip = get_ipython()
171 ip.history_manager.reset()
169 ip.history_manager.reset()
172 cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"]
170 cmds = ["a=10", "a+=1", "print a", "%macro test 2-3"]
173 for cmd in cmds:
171 for cmd in cmds:
174 ip.run_cell(cmd)
172 ip.run_cell(cmd)
175 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n")
173 nt.assert_equal(ip.user_ns["test"].value, "a+=1\nprint a\n")
176 original_stdout = sys.stdout
174 original_stdout = sys.stdout
177 new_stdout = StringIO()
175 new_stdout = StringIO()
178 sys.stdout = new_stdout
176 sys.stdout = new_stdout
179 try:
177 try:
180 ip.run_cell("test")
178 ip.run_cell("test")
181 nt.assert_true("12" in new_stdout.getvalue())
179 nt.assert_true("12" in new_stdout.getvalue())
182 ip.run_cell("test")
180 ip.run_cell("test")
183 nt.assert_true("13" in new_stdout.getvalue())
181 nt.assert_true("13" in new_stdout.getvalue())
184 finally:
182 finally:
185 sys.stdout = original_stdout
183 sys.stdout = original_stdout
186 new_stdout.close()
184 new_stdout.close()
187
185
188
186
189 # XXX failing for now, until we get clearcmd out of quarantine. But we should
187 # XXX failing for now, until we get clearcmd out of quarantine. But we should
190 # fix this and revert the skip to happen only if numpy is not around.
188 # fix this and revert the skip to happen only if numpy is not around.
191 #@dec.skipif_not_numpy
189 #@dec.skipif_not_numpy
192 @dec.skip_known_failure
190 @dec.skip_known_failure
193 def test_numpy_clear_array_undec():
191 def test_numpy_clear_array_undec():
194 from IPython.extensions import clearcmd
192 from IPython.extensions import clearcmd
195
193
196 _ip.ex('import numpy as np')
194 _ip.ex('import numpy as np')
197 _ip.ex('a = np.empty(2)')
195 _ip.ex('a = np.empty(2)')
198 yield (nt.assert_true, 'a' in _ip.user_ns)
196 yield (nt.assert_true, 'a' in _ip.user_ns)
199 _ip.magic('clear array')
197 _ip.magic('clear array')
200 yield (nt.assert_false, 'a' in _ip.user_ns)
198 yield (nt.assert_false, 'a' in _ip.user_ns)
201
199
202
200
203 # Multiple tests for clipboard pasting
201 # Multiple tests for clipboard pasting
204 @dec.parametric
202 @dec.parametric
205 def test_paste():
203 def test_paste():
206 _ip = get_ipython()
204 _ip = get_ipython()
207 def paste(txt, flags='-q'):
205 def paste(txt, flags='-q'):
208 """Paste input text, by default in quiet mode"""
206 """Paste input text, by default in quiet mode"""
209 hooks.clipboard_get = lambda : txt
207 hooks.clipboard_get = lambda : txt
210 _ip.magic('paste '+flags)
208 _ip.magic('paste '+flags)
211
209
212 # Inject fake clipboard hook but save original so we can restore it later
210 # Inject fake clipboard hook but save original so we can restore it later
213 hooks = _ip.hooks
211 hooks = _ip.hooks
214 user_ns = _ip.user_ns
212 user_ns = _ip.user_ns
215 original_clip = hooks.clipboard_get
213 original_clip = hooks.clipboard_get
216
214
217 try:
215 try:
218 # This try/except with an emtpy except clause is here only because
216 # This try/except with an emtpy except clause is here only because
219 # try/yield/finally is invalid syntax in Python 2.4. This will be
217 # try/yield/finally is invalid syntax in Python 2.4. This will be
220 # removed when we drop 2.4-compatibility, and the emtpy except below
218 # removed when we drop 2.4-compatibility, and the emtpy except below
221 # will be changed to a finally.
219 # will be changed to a finally.
222
220
223 # Run tests with fake clipboard function
221 # Run tests with fake clipboard function
224 user_ns.pop('x', None)
222 user_ns.pop('x', None)
225 paste('x=1')
223 paste('x=1')
226 yield nt.assert_equal(user_ns['x'], 1)
224 yield nt.assert_equal(user_ns['x'], 1)
227
225
228 user_ns.pop('x', None)
226 user_ns.pop('x', None)
229 paste('>>> x=2')
227 paste('>>> x=2')
230 yield nt.assert_equal(user_ns['x'], 2)
228 yield nt.assert_equal(user_ns['x'], 2)
231
229
232 paste("""
230 paste("""
233 >>> x = [1,2,3]
231 >>> x = [1,2,3]
234 >>> y = []
232 >>> y = []
235 >>> for i in x:
233 >>> for i in x:
236 ... y.append(i**2)
234 ... y.append(i**2)
237 ...
235 ...
238 """)
236 """)
239 yield nt.assert_equal(user_ns['x'], [1,2,3])
237 yield nt.assert_equal(user_ns['x'], [1,2,3])
240 yield nt.assert_equal(user_ns['y'], [1,4,9])
238 yield nt.assert_equal(user_ns['y'], [1,4,9])
241
239
242 # Now, test that paste -r works
240 # Now, test that paste -r works
243 user_ns.pop('x', None)
241 user_ns.pop('x', None)
244 yield nt.assert_false('x' in user_ns)
242 yield nt.assert_false('x' in user_ns)
245 _ip.magic('paste -r')
243 _ip.magic('paste -r')
246 yield nt.assert_equal(user_ns['x'], [1,2,3])
244 yield nt.assert_equal(user_ns['x'], [1,2,3])
247
245
248 # Also test paste echoing, by temporarily faking the writer
246 # Also test paste echoing, by temporarily faking the writer
249 w = StringIO()
247 w = StringIO()
250 writer = _ip.write
248 writer = _ip.write
251 _ip.write = w.write
249 _ip.write = w.write
252 code = """
250 code = """
253 a = 100
251 a = 100
254 b = 200"""
252 b = 200"""
255 try:
253 try:
256 paste(code,'')
254 paste(code,'')
257 out = w.getvalue()
255 out = w.getvalue()
258 finally:
256 finally:
259 _ip.write = writer
257 _ip.write = writer
260 yield nt.assert_equal(user_ns['a'], 100)
258 yield nt.assert_equal(user_ns['a'], 100)
261 yield nt.assert_equal(user_ns['b'], 200)
259 yield nt.assert_equal(user_ns['b'], 200)
262 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
260 yield nt.assert_equal(out, code+"\n## -- End pasted text --\n")
263
261
264 finally:
262 finally:
265 # This should be in a finally clause, instead of the bare except above.
263 # This should be in a finally clause, instead of the bare except above.
266 # Restore original hook
264 # Restore original hook
267 hooks.clipboard_get = original_clip
265 hooks.clipboard_get = original_clip
268
266
269
267
270 def test_time():
268 def test_time():
271 _ip.magic('time None')
269 _ip.magic('time None')
272
270
273
271
274 def doctest_time():
272 def doctest_time():
275 """
273 """
276 In [10]: %time None
274 In [10]: %time None
277 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
275 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
278 Wall time: 0.00 s
276 Wall time: 0.00 s
279 """
277 """
280
278
281
279
282 def test_doctest_mode():
280 def test_doctest_mode():
283 "Toggle doctest_mode twice, it should be a no-op and run without error"
281 "Toggle doctest_mode twice, it should be a no-op and run without error"
284 _ip.magic('doctest_mode')
282 _ip.magic('doctest_mode')
285 _ip.magic('doctest_mode')
283 _ip.magic('doctest_mode')
286
284
287
285
288 def test_parse_options():
286 def test_parse_options():
289 """Tests for basic options parsing in magics."""
287 """Tests for basic options parsing in magics."""
290 # These are only the most minimal of tests, more should be added later. At
288 # These are only the most minimal of tests, more should be added later. At
291 # the very least we check that basic text/unicode calls work OK.
289 # the very least we check that basic text/unicode calls work OK.
292 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
290 nt.assert_equal(_ip.parse_options('foo', '')[1], 'foo')
293 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
291 nt.assert_equal(_ip.parse_options(u'foo', '')[1], u'foo')
294
292
295
293
296 def test_dirops():
294 def test_dirops():
297 """Test various directory handling operations."""
295 """Test various directory handling operations."""
298 curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
296 curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
299
297
300 startdir = os.getcwd()
298 startdir = os.getcwd()
301 ipdir = _ip.ipython_dir
299 ipdir = _ip.ipython_dir
302 try:
300 try:
303 _ip.magic('cd "%s"' % ipdir)
301 _ip.magic('cd "%s"' % ipdir)
304 nt.assert_equal(curpath(), ipdir)
302 nt.assert_equal(curpath(), ipdir)
305 _ip.magic('cd -')
303 _ip.magic('cd -')
306 nt.assert_equal(curpath(), startdir)
304 nt.assert_equal(curpath(), startdir)
307 _ip.magic('pushd "%s"' % ipdir)
305 _ip.magic('pushd "%s"' % ipdir)
308 nt.assert_equal(curpath(), ipdir)
306 nt.assert_equal(curpath(), ipdir)
309 _ip.magic('popd')
307 _ip.magic('popd')
310 nt.assert_equal(curpath(), startdir)
308 nt.assert_equal(curpath(), startdir)
311 finally:
309 finally:
312 os.chdir(startdir)
310 os.chdir(startdir)
313
311
314
312
315 def check_cpaste(code, should_fail=False):
313 def check_cpaste(code, should_fail=False):
316 """Execute code via 'cpaste' and ensure it was executed, unless
314 """Execute code via 'cpaste' and ensure it was executed, unless
317 should_fail is set.
315 should_fail is set.
318 """
316 """
319 _ip.user_ns['code_ran'] = False
317 _ip.user_ns['code_ran'] = False
320
318
321 src = StringIO()
319 src = StringIO()
322 src.write('\n')
320 src.write('\n')
323 src.write(code)
321 src.write(code)
324 src.write('\n--\n')
322 src.write('\n--\n')
325 src.seek(0)
323 src.seek(0)
326
324
327 stdin_save = sys.stdin
325 stdin_save = sys.stdin
328 sys.stdin = src
326 sys.stdin = src
329
327
330 try:
328 try:
331 _ip.magic('cpaste')
329 _ip.magic('cpaste')
332 except:
330 except:
333 if not should_fail:
331 if not should_fail:
334 raise AssertionError("Failure not expected : '%s'" %
332 raise AssertionError("Failure not expected : '%s'" %
335 code)
333 code)
336 else:
334 else:
337 assert _ip.user_ns['code_ran']
335 assert _ip.user_ns['code_ran']
338 if should_fail:
336 if should_fail:
339 raise AssertionError("Failure expected : '%s'" % code)
337 raise AssertionError("Failure expected : '%s'" % code)
340 finally:
338 finally:
341 sys.stdin = stdin_save
339 sys.stdin = stdin_save
342
340
343
341
344 def test_cpaste():
342 def test_cpaste():
345 """Test cpaste magic"""
343 """Test cpaste magic"""
346
344
347 def run():
345 def run():
348 """Marker function: sets a flag when executed.
346 """Marker function: sets a flag when executed.
349 """
347 """
350 _ip.user_ns['code_ran'] = True
348 _ip.user_ns['code_ran'] = True
351 return 'run' # return string so '+ run()' doesn't result in success
349 return 'run' # return string so '+ run()' doesn't result in success
352
350
353 tests = {'pass': ["> > > run()",
351 tests = {'pass': ["> > > run()",
354 ">>> > run()",
352 ">>> > run()",
355 "+++ run()",
353 "+++ run()",
356 "++ run()",
354 "++ run()",
357 " >>> run()"],
355 " >>> run()"],
358
356
359 'fail': ["+ + run()",
357 'fail': ["+ + run()",
360 " ++ run()"]}
358 " ++ run()"]}
361
359
362 _ip.user_ns['run'] = run
360 _ip.user_ns['run'] = run
363
361
364 for code in tests['pass']:
362 for code in tests['pass']:
365 check_cpaste(code)
363 check_cpaste(code)
366
364
367 for code in tests['fail']:
365 for code in tests['fail']:
368 check_cpaste(code, should_fail=True)
366 check_cpaste(code, should_fail=True)
369
367
370 def test_xmode():
368 def test_xmode():
371 # Calling xmode three times should be a no-op
369 # Calling xmode three times should be a no-op
372 xmode = _ip.InteractiveTB.mode
370 xmode = _ip.InteractiveTB.mode
373 for i in range(3):
371 for i in range(3):
374 _ip.magic("xmode")
372 _ip.magic("xmode")
375 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
373 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
376
374
377 def doctest_who():
375 def doctest_who():
378 """doctest for %who
376 """doctest for %who
379
377
380 In [1]: %reset -f
378 In [1]: %reset -f
381
379
382 In [2]: alpha = 123
380 In [2]: alpha = 123
383
381
384 In [3]: beta = 'beta'
382 In [3]: beta = 'beta'
385
383
386 In [4]: %who int
384 In [4]: %who int
387 alpha
385 alpha
388
386
389 In [5]: %who str
387 In [5]: %who str
390 beta
388 beta
391
389
392 In [6]: %whos
390 In [6]: %whos
393 Variable Type Data/Info
391 Variable Type Data/Info
394 ----------------------------
392 ----------------------------
395 alpha int 123
393 alpha int 123
396 beta str beta
394 beta str beta
397
395
398 In [7]: %who_ls
396 In [7]: %who_ls
399 Out[7]: ['alpha', 'beta']
397 Out[7]: ['alpha', 'beta']
400 """
398 """
401
399
402 def doctest_precision():
400 def doctest_precision():
403 """doctest for %precision
401 """doctest for %precision
404
402
405 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
403 In [1]: f = get_ipython().shell.display_formatter.formatters['text/plain']
406
404
407 In [2]: %precision 5
405 In [2]: %precision 5
408 Out[2]: '%.5f'
406 Out[2]: '%.5f'
409
407
410 In [3]: f.float_format
408 In [3]: f.float_format
411 Out[3]: '%.5f'
409 Out[3]: '%.5f'
412
410
413 In [4]: %precision %e
411 In [4]: %precision %e
414 Out[4]: '%e'
412 Out[4]: '%e'
415
413
416 In [5]: f(3.1415927)
414 In [5]: f(3.1415927)
417 Out[5]: '3.141593e+00'
415 Out[5]: '3.141593e+00'
418 """
416 """
419
417
General Comments 0
You need to be logged in to leave comments. Login now