##// END OF EJS Templates
fix tests that depended on unicode sys.argv
MinRK -
Show More
@@ -1,272 +1,271 b''
1 1 """Tests for the key interactiveshell module, where the main ipython class is defined.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Module imports
5 5 #-----------------------------------------------------------------------------
6 6
7 7 # stdlib
8 8 import os
9 9 import shutil
10 10 import tempfile
11 11
12 12 # third party
13 13 import nose.tools as nt
14 14
15 15 # our own packages
16 16 from IPython.testing import decorators as dec
17 17 from IPython.testing.globalipapp import get_ipython
18 18 from IPython.utils import py3compat
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Globals
22 22 #-----------------------------------------------------------------------------
23 23
24 24 # Get the public instance of IPython
25 25 ip = get_ipython()
26 26
27 27 #-----------------------------------------------------------------------------
28 28 # Test functions
29 29 #-----------------------------------------------------------------------------
30 30
31 31 @dec.parametric
32 32 def test_reset():
33 33 """reset must clear most namespaces."""
34 34 # The number of variables in the private user_ns_hidden is not zero, but it
35 35 # should be constant regardless of what we do
36 36 nvars_config_ns = len(ip.user_ns_hidden)
37 37
38 38 # Check that reset runs without error
39 39 ip.reset()
40 40
41 41 # Once we've reset it (to clear of any junk that might have been there from
42 42 # other tests, we can count how many variables are in the user's namespace
43 43 nvars_user_ns = len(ip.user_ns)
44 44
45 45 # Now add a few variables to user_ns, and check that reset clears them
46 46 ip.user_ns['x'] = 1
47 47 ip.user_ns['y'] = 1
48 48 ip.reset()
49 49
50 50 # Finally, check that all namespaces have only as many variables as we
51 51 # expect to find in them:
52 52 for ns in ip.ns_refs_table:
53 53 if ns is ip.user_ns:
54 54 nvars_expected = nvars_user_ns
55 55 elif ns is ip.user_ns_hidden:
56 56 nvars_expected = nvars_config_ns
57 57 else:
58 58 nvars_expected = 0
59 59
60 60 yield nt.assert_equals(len(ns), nvars_expected)
61 61
62 62
63 63 # Tests for reporting of exceptions in various modes, handling of SystemExit,
64 64 # and %tb functionality. This is really a mix of testing ultraTB and interactiveshell.
65 65
66 66 def doctest_tb_plain():
67 67 """
68 68 In [18]: xmode plain
69 69 Exception reporting mode: Plain
70 70
71 71 In [19]: run simpleerr.py
72 72 Traceback (most recent call last):
73 73 ...line 32, in <module>
74 74 bar(mode)
75 75 ...line 16, in bar
76 76 div0()
77 77 ...line 8, in div0
78 78 x/y
79 79 ZeroDivisionError: ...
80 80 """
81 81
82 82
83 83 def doctest_tb_context():
84 84 """
85 85 In [3]: xmode context
86 86 Exception reporting mode: Context
87 87
88 88 In [4]: run simpleerr.py
89 89 ---------------------------------------------------------------------------
90 90 ZeroDivisionError Traceback (most recent call last)
91 91 <BLANKLINE>
92 92 ... in <module>()
93 93 30 mode = 'div'
94 94 31
95 95 ---> 32 bar(mode)
96 96 <BLANKLINE>
97 97 ... in bar(mode)
98 98 14 "bar"
99 99 15 if mode=='div':
100 100 ---> 16 div0()
101 101 17 elif mode=='exit':
102 102 18 try:
103 103 <BLANKLINE>
104 104 ... in div0()
105 105 6 x = 1
106 106 7 y = 0
107 107 ----> 8 x/y
108 108 9
109 109 10 def sysexit(stat, mode):
110 110 <BLANKLINE>
111 111 ZeroDivisionError: ...
112 112 """
113 113
114 114
115 115 def doctest_tb_verbose():
116 116 """
117 117 In [5]: xmode verbose
118 118 Exception reporting mode: Verbose
119 119
120 120 In [6]: run simpleerr.py
121 121 ---------------------------------------------------------------------------
122 122 ZeroDivisionError Traceback (most recent call last)
123 123 <BLANKLINE>
124 124 ... in <module>()
125 125 30 mode = 'div'
126 126 31
127 127 ---> 32 bar(mode)
128 128 global bar = <function bar at ...>
129 129 global mode = 'div'
130 130 <BLANKLINE>
131 131 ... in bar(mode='div')
132 132 14 "bar"
133 133 15 if mode=='div':
134 134 ---> 16 div0()
135 135 global div0 = <function div0 at ...>
136 136 17 elif mode=='exit':
137 137 18 try:
138 138 <BLANKLINE>
139 139 ... in div0()
140 140 6 x = 1
141 141 7 y = 0
142 142 ----> 8 x/y
143 143 x = 1
144 144 y = 0
145 145 9
146 146 10 def sysexit(stat, mode):
147 147 <BLANKLINE>
148 148 ZeroDivisionError: ...
149 149 """
150 150
151 @py3compat.u_format
152 151 def doctest_tb_sysexit():
153 152 """
154 153 In [17]: %xmode plain
155 154 Exception reporting mode: Plain
156 155
157 156 In [18]: %run simpleerr.py exit
158 157 An exception has occurred, use %tb to see the full traceback.
159 SystemExit: (1, {u}'Mode = exit')
158 SystemExit: (1, 'Mode = exit')
160 159
161 160 In [19]: %run simpleerr.py exit 2
162 161 An exception has occurred, use %tb to see the full traceback.
163 SystemExit: (2, {u}'Mode = exit')
162 SystemExit: (2, 'Mode = exit')
164 163
165 164 In [20]: %tb
166 165 Traceback (most recent call last):
167 166 File ... in <module>
168 167 bar(mode)
169 168 File ... line 22, in bar
170 169 sysexit(stat, mode)
171 170 File ... line 11, in sysexit
172 171 raise SystemExit(stat, 'Mode = %s' % mode)
173 SystemExit: (2, {u}'Mode = exit')
172 SystemExit: (2, 'Mode = exit')
174 173
175 174 In [21]: %xmode context
176 175 Exception reporting mode: Context
177 176
178 177 In [22]: %tb
179 178 ---------------------------------------------------------------------------
180 179 SystemExit Traceback (most recent call last)
181 180 <BLANKLINE>
182 181 ...<module>()
183 182 30 mode = 'div'
184 183 31
185 184 ---> 32 bar(mode)
186 185 <BLANKLINE>
187 186 ...bar(mode)
188 187 20 except:
189 188 21 stat = 1
190 189 ---> 22 sysexit(stat, mode)
191 190 23 else:
192 191 24 raise ValueError('Unknown mode')
193 192 <BLANKLINE>
194 193 ...sysexit(stat, mode)
195 194 9
196 195 10 def sysexit(stat, mode):
197 196 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
198 197 12
199 198 13 def bar(mode):
200 199 <BLANKLINE>
201 SystemExit: (2, {u}'Mode = exit')
200 SystemExit: (2, 'Mode = exit')
202 201
203 202 In [23]: %xmode verbose
204 203 Exception reporting mode: Verbose
205 204
206 205 In [24]: %tb
207 206 ---------------------------------------------------------------------------
208 207 SystemExit Traceback (most recent call last)
209 208 <BLANKLINE>
210 209 ... in <module>()
211 210 30 mode = 'div'
212 211 31
213 212 ---> 32 bar(mode)
214 213 global bar = <function bar at ...>
215 global mode = {u}'exit'
214 global mode = 'exit'
216 215 <BLANKLINE>
217 ... in bar(mode={u}'exit')
216 ... in bar(mode='exit')
218 217 20 except:
219 218 21 stat = 1
220 219 ---> 22 sysexit(stat, mode)
221 220 global sysexit = <function sysexit at ...>
222 221 stat = 2
223 mode = {u}'exit'
222 mode = 'exit'
224 223 23 else:
225 224 24 raise ValueError('Unknown mode')
226 225 <BLANKLINE>
227 ... in sysexit(stat=2, mode={u}'exit')
226 ... in sysexit(stat=2, mode='exit')
228 227 9
229 228 10 def sysexit(stat, mode):
230 229 ---> 11 raise SystemExit(stat, 'Mode = %s' % mode)
231 230 global SystemExit = undefined
232 231 stat = 2
233 mode = {u}'exit'
232 mode = 'exit'
234 233 12
235 234 13 def bar(mode):
236 235 <BLANKLINE>
237 SystemExit: (2, {u}'Mode = exit')
236 SystemExit: (2, 'Mode = exit')
238 237 """
239 238
240 239
241 240 def test_run_cell():
242 241 import textwrap
243 242 ip.run_cell('a = 10\na+=1')
244 243 ip.run_cell('assert a == 11\nassert 1')
245 244
246 245 nt.assert_equals(ip.user_ns['a'], 11)
247 246 complex = textwrap.dedent("""
248 247 if 1:
249 248 print "hello"
250 249 if 1:
251 250 print "world"
252 251
253 252 if 2:
254 253 print "foo"
255 254
256 255 if 3:
257 256 print "bar"
258 257
259 258 if 4:
260 259 print "bar"
261 260
262 261 """)
263 262 # Simply verifies that this kind of input is run
264 263 ip.run_cell(complex)
265 264
266 265
267 266 def test_db():
268 267 """Test the internal database used for variable persistence."""
269 268 ip.db['__unittest_'] = 12
270 269 nt.assert_equals(ip.db['__unittest_'], 12)
271 270 del ip.db['__unittest_']
272 271 assert '__unittest_' not in ip.db
@@ -1,210 +1,210 b''
1 1 """Tests for code execution (%run and related), which is particularly tricky.
2 2
3 3 Because of how %run manages namespaces, and the fact that we are trying here to
4 4 verify subtle object deletion and reference counting issues, the %run tests
5 5 will be kept in this separate file. This makes it easier to aggregate in one
6 6 place the tricks needed to handle it; most other magics are much easier to test
7 7 and we do so in a common test_magic file.
8 8 """
9 9 from __future__ import absolute_import
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 import os
16 16 import sys
17 17 import tempfile
18 18
19 19 import nose.tools as nt
20 20 from nose import SkipTest
21 21
22 22 from IPython.testing import decorators as dec
23 23 from IPython.testing import tools as tt
24 24 from IPython.utils import py3compat
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Test functions begin
28 28 #-----------------------------------------------------------------------------
29 29
30 30 def doctest_refbug():
31 31 """Very nasty problem with references held by multiple runs of a script.
32 32 See: https://github.com/ipython/ipython/issues/141
33 33
34 34 In [1]: _ip.clear_main_mod_cache()
35 35 # random
36 36
37 37 In [2]: %run refbug
38 38
39 39 In [3]: call_f()
40 40 lowercased: hello
41 41
42 42 In [4]: %run refbug
43 43
44 44 In [5]: call_f()
45 45 lowercased: hello
46 46 lowercased: hello
47 47 """
48 48
49 49
50 50 def doctest_run_builtins():
51 51 r"""Check that %run doesn't damage __builtins__.
52 52
53 53 In [1]: import tempfile
54 54
55 55 In [2]: bid1 = id(__builtins__)
56 56
57 57 In [3]: fname = tempfile.mkstemp('.py')[1]
58 58
59 59 In [3]: f = open(fname,'w')
60 60
61 61 In [4]: dummy= f.write('pass\n')
62 62
63 63 In [5]: f.flush()
64 64
65 65 In [6]: t1 = type(__builtins__)
66 66
67 67 In [7]: %run $fname
68 68
69 69 In [7]: f.close()
70 70
71 71 In [8]: bid2 = id(__builtins__)
72 72
73 73 In [9]: t2 = type(__builtins__)
74 74
75 75 In [10]: t1 == t2
76 76 Out[10]: True
77 77
78 78 In [10]: bid1 == bid2
79 79 Out[10]: True
80 80
81 81 In [12]: try:
82 82 ....: os.unlink(fname)
83 83 ....: except:
84 84 ....: pass
85 85 ....:
86 86 """
87 87
88 88 @py3compat.doctest_refactor_print
89 89 def doctest_reset_del():
90 90 """Test that resetting doesn't cause errors in __del__ methods.
91 91
92 92 In [2]: class A(object):
93 93 ...: def __del__(self):
94 94 ...: print str("Hi")
95 95 ...:
96 96
97 97 In [3]: a = A()
98 98
99 99 In [4]: get_ipython().reset()
100 100 Hi
101 101
102 102 In [5]: 1+1
103 103 Out[5]: 2
104 104 """
105 105
106 106 # For some tests, it will be handy to organize them in a class with a common
107 107 # setup that makes a temp file
108 108
109 109 class TestMagicRunPass(tt.TempFileMixin):
110 110
111 111 def setup(self):
112 112 """Make a valid python temp file."""
113 113 self.mktmp('pass\n')
114 114
115 115 def run_tmpfile(self):
116 116 _ip = get_ipython()
117 117 # This fails on Windows if self.tmpfile.name has spaces or "~" in it.
118 118 # See below and ticket https://bugs.launchpad.net/bugs/366353
119 119 _ip.magic('run %s' % self.fname)
120 120
121 121 def test_builtins_id(self):
122 122 """Check that %run doesn't damage __builtins__ """
123 123 _ip = get_ipython()
124 124 # Test that the id of __builtins__ is not modified by %run
125 125 bid1 = id(_ip.user_ns['__builtins__'])
126 126 self.run_tmpfile()
127 127 bid2 = id(_ip.user_ns['__builtins__'])
128 128 tt.assert_equals(bid1, bid2)
129 129
130 130 def test_builtins_type(self):
131 131 """Check that the type of __builtins__ doesn't change with %run.
132 132
133 133 However, the above could pass if __builtins__ was already modified to
134 134 be a dict (it should be a module) by a previous use of %run. So we
135 135 also check explicitly that it really is a module:
136 136 """
137 137 _ip = get_ipython()
138 138 self.run_tmpfile()
139 139 tt.assert_equals(type(_ip.user_ns['__builtins__']),type(sys))
140 140
141 141 def test_prompts(self):
142 142 """Test that prompts correctly generate after %run"""
143 143 self.run_tmpfile()
144 144 _ip = get_ipython()
145 145 p2 = str(_ip.displayhook.prompt2).strip()
146 146 nt.assert_equals(p2[:3], '...')
147 147
148 148
149 149 class TestMagicRunSimple(tt.TempFileMixin):
150 150
151 151 def test_simpledef(self):
152 152 """Test that simple class definitions work."""
153 153 src = ("class foo: pass\n"
154 154 "def f(): return foo()")
155 155 self.mktmp(src)
156 156 _ip.magic('run %s' % self.fname)
157 157 _ip.run_cell('t = isinstance(f(), foo)')
158 158 nt.assert_true(_ip.user_ns['t'])
159 159
160 160 def test_obj_del(self):
161 161 """Test that object's __del__ methods are called on exit."""
162 162 if sys.platform == 'win32':
163 163 try:
164 164 import win32api
165 165 except ImportError:
166 166 raise SkipTest("Test requires pywin32")
167 167 src = ("class A(object):\n"
168 168 " def __del__(self):\n"
169 169 " print 'object A deleted'\n"
170 170 "a = A()\n")
171 171 self.mktmp(py3compat.doctest_refactor_print(src))
172 172 tt.ipexec_validate(self.fname, 'object A deleted')
173 173
174 174 @dec.skip_known_failure
175 175 def test_aggressive_namespace_cleanup(self):
176 176 """Test that namespace cleanup is not too aggressive GH-238
177 177
178 178 Returning from another run magic deletes the namespace"""
179 179 # see ticket https://github.com/ipython/ipython/issues/238
180 180 class secondtmp(tt.TempFileMixin): pass
181 181 empty = secondtmp()
182 182 empty.mktmp('')
183 183 src = ("ip = get_ipython()\n"
184 184 "for i in range(5):\n"
185 185 " try:\n"
186 186 " ip.magic('run %s')\n"
187 187 " except NameError, e:\n"
188 188 " print i;break\n" % empty.fname)
189 189 self.mktmp(py3compat.doctest_refactor_print(src))
190 190 _ip.magic('run %s' % self.fname)
191 191 _ip.run_cell('ip == get_ipython()')
192 192 tt.assert_equals(_ip.user_ns['i'], 5)
193 193
194 194 @dec.skip_win32
195 195 def test_tclass(self):
196 196 mydir = os.path.dirname(__file__)
197 197 tc = os.path.join(mydir, 'tclass')
198 198 src = ("%%run '%s' C-first\n"
199 199 "%%run '%s' C-second\n"
200 200 "%%run '%s' C-third\n") % (tc, tc, tc)
201 201 self.mktmp(src, '.ipy')
202 202 out = """\
203 ARGV 1-: [{u}'C-first']
204 ARGV 1-: [{u}'C-second']
203 ARGV 1-: ['C-first']
204 ARGV 1-: ['C-second']
205 205 tclass.py: deleting object: C-first
206 ARGV 1-: [{u}'C-third']
206 ARGV 1-: ['C-third']
207 207 tclass.py: deleting object: C-second
208 208 tclass.py: deleting object: C-third
209 209 """
210 tt.ipexec_validate(self.fname, py3compat.u_format(out))
210 tt.ipexec_validate(self.fname, out)
General Comments 0
You need to be logged in to leave comments. Login now