##// END OF EJS Templates
drop some 2.6 hacks
Matthias Bussonnier -
Show More
@@ -1,83 +1,78 b''
1 1 """Tests for two-process terminal frontend
2 2
3 3 Currently only has the most simple test possible, starting a console and running
4 4 a single command.
5 5
6 6 Authors:
7 7
8 8 * Min RK
9 9 """
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 import sys
16 16
17 17 from nose import SkipTest
18 18
19 19 import IPython.testing.tools as tt
20 20 from IPython.testing import decorators as dec
21 21
22 22 #-----------------------------------------------------------------------------
23 23 # Tests
24 24 #-----------------------------------------------------------------------------
25 25
26 26 @dec.skip_win32
27 27 def test_console_starts():
28 28 """test that `ipython console` starts a terminal"""
29 29 p, pexpect, t = start_console()
30 30 p.sendline('5')
31 31 idx = p.expect([r'Out\[\d+\]: 5', pexpect.EOF], timeout=t)
32 32 idx = p.expect([r'In \[\d+\]', pexpect.EOF], timeout=t)
33 33 stop_console(p, pexpect, t)
34 34
35 35 def test_help_output():
36 36 """ipython console --help-all works"""
37 37 tt.help_all_output_test('console')
38 38
39 39
40 40 def test_display_text():
41 41 "Ensure display protocol plain/text key is supported"
42 42 # equivalent of:
43 43 #
44 44 # x = %lsmagic
45 45 # from IPython.display import display; display(x);
46 46 p, pexpect, t = start_console()
47 47 p.sendline('x = %lsmagic')
48 48 idx = p.expect([r'In \[\d+\]', pexpect.EOF], timeout=t)
49 49 p.sendline('from IPython.display import display; display(x);')
50 50 p.expect([r'Available line magics:', pexpect.EOF], timeout=t)
51 51 stop_console(p, pexpect, t)
52 52
53 53 def stop_console(p, pexpect, t):
54 54 "Stop a running `ipython console` running via pexpect"
55 55 # send ctrl-D;ctrl-D to exit
56 56 p.sendeof()
57 57 p.sendeof()
58 58 p.expect([pexpect.EOF, pexpect.TIMEOUT], timeout=t)
59 59 if p.isalive():
60 60 p.terminate()
61 61
62 62
63 63 def start_console():
64 64 "Start `ipython console` using pexpect"
65 65 from IPython.external import pexpect
66 66
67 args = ['console', '--colors=NoColor']
68 # FIXME: remove workaround for 2.6 support
69 if sys.version_info[:2] > (2,6):
70 args = ['-m', 'IPython'] + args
71 cmd = sys.executable
72 else:
73 cmd = 'ipython'
67 args = ['-m', 'IPython', 'console', '--colors=NoColor']
68 cmd = sys.executable
74 69
75 70 try:
76 71 p = pexpect.spawn(cmd, args=args)
77 72 except IOError:
78 73 raise SkipTest("Couldn't find command %s" % cmd)
79 74
80 75 # timeout after one minute
81 76 t = 60
82 77 idx = p.expect([r'In \[\d+\]', pexpect.EOF], timeout=t)
83 78 return p, pexpect, t
@@ -1,247 +1,244 b''
1 1 # coding: utf-8
2 2 """Compatibility tricks for Python 3. Mainly to do with unicode."""
3 3 import functools
4 4 import os
5 5 import sys
6 6 import re
7 7 import types
8 8
9 9 from .encoding import DEFAULT_ENCODING
10 10
11 11 def no_code(x, encoding=None):
12 12 return x
13 13
14 14 def decode(s, encoding=None):
15 15 encoding = encoding or DEFAULT_ENCODING
16 16 return s.decode(encoding, "replace")
17 17
18 18 def encode(u, encoding=None):
19 19 encoding = encoding or DEFAULT_ENCODING
20 20 return u.encode(encoding, "replace")
21 21
22 22
23 23 def cast_unicode(s, encoding=None):
24 24 if isinstance(s, bytes):
25 25 return decode(s, encoding)
26 26 return s
27 27
28 28 def cast_bytes(s, encoding=None):
29 29 if not isinstance(s, bytes):
30 30 return encode(s, encoding)
31 31 return s
32 32
33 33 def _modify_str_or_docstring(str_change_func):
34 34 @functools.wraps(str_change_func)
35 35 def wrapper(func_or_str):
36 36 if isinstance(func_or_str, string_types):
37 37 func = None
38 38 doc = func_or_str
39 39 else:
40 40 func = func_or_str
41 41 doc = func.__doc__
42 42
43 43 doc = str_change_func(doc)
44 44
45 45 if func:
46 46 func.__doc__ = doc
47 47 return func
48 48 return doc
49 49 return wrapper
50 50
51 51 def safe_unicode(e):
52 52 """unicode(e) with various fallbacks. Used for exceptions, which may not be
53 53 safe to call unicode() on.
54 54 """
55 55 try:
56 56 return unicode_type(e)
57 57 except UnicodeError:
58 58 pass
59 59
60 60 try:
61 61 return str_to_unicode(str(e))
62 62 except UnicodeError:
63 63 pass
64 64
65 65 try:
66 66 return str_to_unicode(repr(e))
67 67 except UnicodeError:
68 68 pass
69 69
70 70 return u'Unrecoverably corrupt evalue'
71 71
72 72 if sys.version_info[0] >= 3:
73 73 PY3 = True
74 74
75 75 # keep reference to builtin_mod because the kernel overrides that value
76 76 # to forward requests to a frontend.
77 77 def input(prompt=''):
78 78 return builtin_mod.input(prompt)
79 79
80 80 builtin_mod_name = "builtins"
81 81 import builtins as builtin_mod
82 82
83 83 str_to_unicode = no_code
84 84 unicode_to_str = no_code
85 85 str_to_bytes = encode
86 86 bytes_to_str = decode
87 87 cast_bytes_py2 = no_code
88 88 cast_unicode_py2 = no_code
89 89
90 90 string_types = (str,)
91 91 unicode_type = str
92 92
93 93 def isidentifier(s, dotted=False):
94 94 if dotted:
95 95 return all(isidentifier(a) for a in s.split("."))
96 96 return s.isidentifier()
97 97
98 98 xrange = range
99 99 def iteritems(d): return iter(d.items())
100 100 def itervalues(d): return iter(d.values())
101 101 getcwd = os.getcwd
102 102
103 103 MethodType = types.MethodType
104 104
105 105 def execfile(fname, glob, loc=None):
106 106 loc = loc if (loc is not None) else glob
107 107 with open(fname, 'rb') as f:
108 108 exec(compile(f.read(), fname, 'exec'), glob, loc)
109 109
110 110 # Refactor print statements in doctests.
111 111 _print_statement_re = re.compile(r"\bprint (?P<expr>.*)$", re.MULTILINE)
112 112 def _print_statement_sub(match):
113 113 expr = match.groups('expr')
114 114 return "print(%s)" % expr
115 115
116 116 @_modify_str_or_docstring
117 117 def doctest_refactor_print(doc):
118 118 """Refactor 'print x' statements in a doctest to print(x) style. 2to3
119 119 unfortunately doesn't pick up on our doctests.
120 120
121 121 Can accept a string or a function, so it can be used as a decorator."""
122 122 return _print_statement_re.sub(_print_statement_sub, doc)
123 123
124 124 # Abstract u'abc' syntax:
125 125 @_modify_str_or_docstring
126 126 def u_format(s):
127 127 """"{u}'abc'" --> "'abc'" (Python 3)
128 128
129 129 Accepts a string or a function, so it can be used as a decorator."""
130 130 return s.format(u='')
131 131
132 132 def get_closure(f):
133 133 """Get a function's closure attribute"""
134 134 return f.__closure__
135 135
136 136 else:
137 137 PY3 = False
138 138
139 139 # keep reference to builtin_mod because the kernel overrides that value
140 140 # to forward requests to a frontend.
141 141 def input(prompt=''):
142 142 return builtin_mod.raw_input(prompt)
143 143
144 144 builtin_mod_name = "__builtin__"
145 145 import __builtin__ as builtin_mod
146 146
147 147 str_to_unicode = decode
148 148 unicode_to_str = encode
149 149 str_to_bytes = no_code
150 150 bytes_to_str = no_code
151 151 cast_bytes_py2 = cast_bytes
152 152 cast_unicode_py2 = cast_unicode
153 153
154 154 string_types = (str, unicode)
155 155 unicode_type = unicode
156 156
157 157 import re
158 158 _name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*$")
159 159 def isidentifier(s, dotted=False):
160 160 if dotted:
161 161 return all(isidentifier(a) for a in s.split("."))
162 162 return bool(_name_re.match(s))
163 163
164 164 xrange = xrange
165 165 def iteritems(d): return d.iteritems()
166 166 def itervalues(d): return d.itervalues()
167 167 getcwd = os.getcwdu
168 168
169 169 def MethodType(func, instance):
170 170 return types.MethodType(func, instance, type(instance))
171 171
172 172 def doctest_refactor_print(func_or_str):
173 173 return func_or_str
174 174
175 175 def get_closure(f):
176 176 """Get a function's closure attribute"""
177 177 return f.func_closure
178 178
179 179 # Abstract u'abc' syntax:
180 180 @_modify_str_or_docstring
181 181 def u_format(s):
182 182 """"{u}'abc'" --> "u'abc'" (Python 2)
183 183
184 184 Accepts a string or a function, so it can be used as a decorator."""
185 185 return s.format(u='u')
186 186
187 187 if sys.platform == 'win32':
188 188 def execfile(fname, glob=None, loc=None):
189 189 loc = loc if (loc is not None) else glob
190 # The rstrip() is necessary b/c trailing whitespace in files will
191 # cause an IndentationError in Python 2.6 (this was fixed in 2.7,
192 # but we still support 2.6). See issue 1027.
193 scripttext = builtin_mod.open(fname).read().rstrip() + '\n'
190 scripttext = builtin_mod.open(fname).read()+ '\n'
194 191 # compile converts unicode filename to str assuming
195 192 # ascii. Let's do the conversion before calling compile
196 193 if isinstance(fname, unicode):
197 194 filename = unicode_to_str(fname)
198 195 else:
199 196 filename = fname
200 197 exec(compile(scripttext, filename, 'exec'), glob, loc)
201 198 else:
202 199 def execfile(fname, *where):
203 200 if isinstance(fname, unicode):
204 201 filename = fname.encode(sys.getfilesystemencoding())
205 202 else:
206 203 filename = fname
207 204 builtin_mod.execfile(filename, *where)
208 205
209 206
210 207 def annotate(**kwargs):
211 208 """Python 3 compatible function annotation for Python 2."""
212 209 if not kwargs:
213 210 raise ValueError('annotations must be provided as keyword arguments')
214 211 def dec(f):
215 212 if hasattr(f, '__annotations__'):
216 213 for k, v in kwargs.items():
217 214 f.__annotations__[k] = v
218 215 else:
219 216 f.__annotations__ = kwargs
220 217 return f
221 218 return dec
222 219
223 220
224 221 # Parts below taken from six:
225 222 # Copyright (c) 2010-2013 Benjamin Peterson
226 223 #
227 224 # Permission is hereby granted, free of charge, to any person obtaining a copy
228 225 # of this software and associated documentation files (the "Software"), to deal
229 226 # in the Software without restriction, including without limitation the rights
230 227 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
231 228 # copies of the Software, and to permit persons to whom the Software is
232 229 # furnished to do so, subject to the following conditions:
233 230 #
234 231 # The above copyright notice and this permission notice shall be included in all
235 232 # copies or substantial portions of the Software.
236 233 #
237 234 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
238 235 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
239 236 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
240 237 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
241 238 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
242 239 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
243 240 # SOFTWARE.
244 241
245 242 def with_metaclass(meta, *bases):
246 243 """Create a base class with a metaclass."""
247 244 return meta("_NewBase", bases, {})
General Comments 0
You need to be logged in to leave comments. Login now