Debian Codegraph @

pypy/module/exceptions/test/test_exc.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2
3 from pypy.interpreter.gateway import interp2app_temp
4 from pypy.interpreter.error import OperationError
5
6
7 class AppTestExc(object):
8 def setup_class(cls):
9 cls.w_file = cls.space.wrap(__file__)
10
11 def test_baseexc(self):
12 assert str(BaseException()) == ''
13 assert repr(BaseException()) == 'BaseException()'
14 raises(AttributeError, getattr, BaseException(), 'message')
15 raises(AttributeError, getattr, BaseException(3), 'message')
16 assert repr(BaseException(3)) == 'BaseException(3)'
17 assert str(BaseException(3)) == '3'
18 assert BaseException().args == ()
19 assert BaseException(3).args == (3,)
20 assert BaseException(3, "x").args == (3, "x")
21 assert repr(BaseException(3, "x")) == "BaseException(3, 'x')"
22 assert str(BaseException(3, "x")) == "(3, 'x')"
23 raises(AttributeError, getattr, BaseException(3, "x"), 'message')
24 x = BaseException()
25 x.xyz = 3
26 assert x.xyz == 3
27 x.args = [42]
28 assert x.args == (42,)
29 assert str(x) == '42'
30 raises(TypeError, 'x[0] == 42')
31 x.message = "xyz"
32 assert x.message == "xyz"
33 del x.message
34 assert not hasattr(x, "message")
35
36 def test_kwargs(self):
37 class X(Exception):
38 def __init__(self, x=3):
39 self.x = x
40
41 x = X(x=8)
42 assert x.x == 8
43
44 def test_args(self):
45 class X(Exception):
46 def __init__(self, x=3):
47 self.x = x
48
49 assert X(8).args == (8,)
50 assert X(x=8).args == ()
51
52 def test_exc(self):
53 assert issubclass(Exception, BaseException)
54 assert isinstance(Exception(), Exception)
55 assert isinstance(Exception(), BaseException)
56 assert repr(Exception(3, "x")) == "Exception(3, 'x')"
57 assert str(IOError("foo", "bar")) == "[Errno foo] bar"
58 assert isinstance(IOError("foo", "bar"), IOError)
59 assert str(IOError(1, 2)) == "[Errno 1] 2"
60
61 def test_custom_class(self):
62 class MyException(Exception):
63 def __init__(self, x):
64 self.x = x
65
66 def __str__(self):
67 return self.x
68
69 assert issubclass(MyException, Exception)
70 assert issubclass(MyException, BaseException)
71 assert not issubclass(MyException, LookupError)
72 assert str(MyException("x")) == "x"
73
74 def test_unicode_translate_error(self):
75 ut = UnicodeTranslateError("x", 1, 5, "bah")
76 assert ut.object == 'x'
77 assert ut.start == 1
78 assert ut.end == 5
79 assert ut.reason == 'bah'
80 assert ut.args == ('x', 1, 5, 'bah')
81 ut.object = 'y'
82 assert ut.object == 'y'
83 assert str(ut) == "can't translate characters in position 1-4: bah"
84 ut.start = 4
85 ut.object = '012345'
86 assert str(ut) == "can't translate character '\\x34' in position 4: bah"
87 ut.object = []
88 assert ut.object == []
89
90 def test_key_error(self):
91 assert str(KeyError('s')) == "'s'"
92
93 def test_environment_error(self):
94 ee = EnvironmentError(3, "x", "y")
95 assert str(ee) == "[Errno 3] x: 'y'"
96 assert str(EnvironmentError(3, "x")) == "[Errno 3] x"
97 assert ee.errno == 3
98 assert ee.strerror == "x"
99 assert ee.filename == "y"
100 assert EnvironmentError(3, "x").filename is None
101 e = EnvironmentError(1, "hello", "world")
102 assert str(e) == "[Errno 1] hello: 'world'"
103
104 def test_windows_error(self):
105 try:
106 WindowsError
107 except NameError:
108 skip('WindowsError not present')
109 ee = WindowsError(None, "x", "y", 3)
110 assert type(ee) is FileNotFoundError
111 assert str(ee) == "[WinError 3] x: 'y'"
112 # winerror=3 (ERROR_PATH_NOT_FOUND) maps to errno=2 (ENOENT)
113 assert ee.winerror == 3
114 assert ee.errno == 2
115 assert str(WindowsError(3, "x")) == "[Errno 3] x"
116
117 def test_syntax_error(self):
118 s = SyntaxError()
119 assert s.msg is None
120 s = SyntaxError(3)
121 assert str(s) == '3'
122 assert str(SyntaxError("a", "b", 123)) == "a"
123 assert str(SyntaxError("a", (1, 2, 3, 4))) == "a (line 2)"
124 s = SyntaxError("a", (1, 2, 3, 4))
125 assert s.msg == "a"
126 assert s.filename == 1
127 assert s.offset == 3
128 assert s.text == 4
129 assert str(SyntaxError("msg", ("file.py", 2, 3, 4))) == "msg (file.py, line 2)"
130
131 s = SyntaxError("a", (1, 2, 3, 4, 5, 6))
132 assert s.msg == "a"
133 assert s.filename == 1
134 assert s.lineno == 2
135 assert s.offset == 3
136 assert s.text == 4
137 assert s.end_lineno == 5
138 assert s.end_offset == 6
139
140 def test_system_exit(self):
141 assert issubclass(SystemExit, BaseException)
142 assert SystemExit().code is None
143 assert SystemExit("x").code == "x"
144 assert SystemExit(1, 2).code == (1, 2)
145
146 def test_str_unicode(self):
147 e = ValueError('àèì')
148 assert str(e) == 'àèì'
149
150 def test_unicode_decode_error(self):
151 for mybytes in (b'y', bytearray(b'y')):
152 ud = UnicodeDecodeError("x", mybytes, 1, 5, "bah")
153 assert ud.encoding == 'x'
154 assert ud.object == b'y'
155 assert type(ud.object) is bytes
156 assert ud.start == 1
157 assert ud.end == 5
158 assert ud.reason == 'bah'
159 assert ud.args == ('x', b'y', 1, 5, 'bah')
160 assert type(ud.args[1]) is type(mybytes)
161 ud.object = b'z9'
162 assert ud.object == b'z9'
163 assert str(ud) == "'x' codec can't decode bytes in position 1-4: bah"
164 ud.end = 2
165 assert str(ud) == "'x' codec can't decode byte 0x39 in position 1: bah"
166
167 def test_unicode_encode_error(self):
168 ue = UnicodeEncodeError("x", "y", 1, 5, "bah")
169 assert ue.encoding == 'x'
170 assert ue.object == 'y'
171 assert ue.start == 1
172 assert ue.end == 5
173 assert ue.reason == 'bah'
174 assert ue.args == ('x', 'y', 1, 5, 'bah')
175 ue.object = 'z9'
176 assert ue.object == 'z9'
177 assert str(ue) == "'x' codec can't encode characters in position 1-4: bah"
178 ue.end = 2
179 assert str(ue) == "'x' codec can't encode character '\\x39' in position 1: bah"
180 ue.object = []
181 assert ue.object == []
182 raises(TypeError, UnicodeEncodeError, "x", b"y", 1, 5, "bah")
183
184 def test_multiple_inheritance(self):
185 class A(LookupError, ValueError):
186 pass
187 assert issubclass(A, A)
188 assert issubclass(A, Exception)
189 assert issubclass(A, LookupError)
190 assert issubclass(A, ValueError)
191 assert not issubclass(A, KeyError)
192 a = A()
193 assert isinstance(a, A)
194 assert isinstance(a, Exception)
195 assert isinstance(a, LookupError)
196 assert isinstance(a, ValueError)
197 assert not isinstance(a, KeyError)
198
199 try:
200 class B(UnicodeTranslateError, UnicodeEncodeError):
201 pass
202 except TypeError:
203 pass
204 else:
205 fail("bah")
206
207 class C(ValueError, IOError):
208 pass
209 c = C()
210 assert isinstance(ValueError(), ValueError)
211 assert isinstance(c, C)
212 assert isinstance(c, Exception)
213 assert isinstance(c, ValueError)
214 assert isinstance(c, IOError)
215 assert isinstance(c, EnvironmentError)
216 assert not isinstance(c, KeyError)
217
218 def test_doc_and_module(self):
219 import builtins
220 for name, e in builtins.__dict__.items():
221 if isinstance(e, type) and issubclass(e, BaseException):
222 if e not in (ExceptionGroup,):
223 assert e.__doc__, e
224 assert e.__module__ == 'builtins', e
225 assert 'run-time' in RuntimeError.__doc__
226
227 def test_reduce(self):
228 le = LookupError(1, 2, "a")
229 assert le.__reduce__() == (LookupError, (1, 2, "a"))
230 le.xyz = (1, 2)
231 assert le.__reduce__() == (LookupError, (1, 2, "a"), {"xyz": (1, 2)})
232 ee = EnvironmentError(1, 2, "a")
233 assert ee.__reduce__() == (PermissionError, (1, 2, "a"))
234 ee = ImportError("a", "b", "c", name="x", path="y")
235 assert ee.__reduce__() == (ImportError, ("a", "b", "c"), {"name": "x", "path": "y"})
236
237 def test_setstate(self):
238 fw = FutureWarning()
239 fw.__setstate__({"xyz": (1, 2)})
240 assert fw.xyz == (1, 2)
241 fw.__setstate__({'z': 1})
242 assert fw.z == 1
243 assert fw.xyz == (1, 2)
244
245 i = ImportError()
246 i.foo = "x"
247 i.__setstate__({"name": "x", "path": "y", "bar": 1})
248 assert i.foo == "x"
249 assert i.name == "x"
250 assert i.path == "y"
251 assert i.bar == 1
252
253 def test_unicode_error_uninitialized_str(self):
254 assert str(UnicodeEncodeError.__new__(UnicodeEncodeError)) == ""
255 assert str(UnicodeDecodeError.__new__(UnicodeDecodeError)) == ""
256 assert str(UnicodeTranslateError.__new__(UnicodeTranslateError)) == ""
257
258 def test_cause(self):
259 e1 = TypeError()
260 e2 = ValueError()
261 assert e1.__cause__ is None
262 e1.__cause__ = e2
263 assert e1.__cause__ is e2
264 e1.__cause__ = None
265 raises(TypeError, setattr, e1, '__cause__', 1)
266 raises((AttributeError, TypeError), delattr, e1, '__cause__')
267
268 def test_context(self):
269 e1 = TypeError()
270 e2 = ValueError()
271 assert e1.__context__ is None
272 e1.__context__ = e2
273 assert e1.__context__ is e2
274 e1.__context__ = None
275 raises(TypeError, setattr, e1, '__context__', 1)
276 raises((AttributeError, TypeError), delattr, e1, '__context__')
277
278 def test_traceback(self):
279 assert ValueError().with_traceback(None).__traceback__ is None
280 raises(TypeError, ValueError().with_traceback, 3)
281 try:
282 XXX
283 except NameError as e:
284 import sys
285 tb = sys.exc_info()[2]
286 assert e.with_traceback(tb) is e
287 assert e.__traceback__ is tb
288
289 def test_set_traceback(self):
290 e = Exception()
291 raises(TypeError, "e.__traceback__ = 42")
292
293 def test_errno_ENOTDIR(self):
294 # CPython issue #12802: "not a directory" errors are ENOTDIR
295 # even on Windows
296 import os
297 import errno
298 try:
299 os.listdir(self.file)
300 except OSError as e:
301 assert e.errno == errno.ENOTDIR
302 else:
303 assert False, "Expected OSError"
304
305 def test_nonascii_name(self):
306 """
307 class 日本(Exception):
308 pass
309 assert '日本' in repr(日本)
310 class 日本2(SyntaxError):
311 pass
312 assert '日本2' in repr(日本2)
313 """
314
315 def test_stopiteration(self):
316 assert StopIteration().value is None
317 assert StopIteration(42).value == 42
318 assert StopIteration(42, 5).value == 42
319
320 def test_importerror(self):
321 assert ImportError("message").name is None
322 assert ImportError("message").path is None
323 assert ImportError("message", name="x").name == "x"
324 assert ImportError("message", path="y").path == "y"
325 with raises(TypeError) as e:
326 ImportError(invalid="z")
327 assert "'invalid' is an invalid keyword argument for ImportError" in str(e.value)
328 assert ImportError("message").msg == "message"
329 assert ImportError("message").args == ("message", )
330 assert ImportError("message", "foo").msg is None
331 assert ImportError("message", "foo").args == ("message", "foo")
332
333 def test_importerror_reduce(self):
334 d = {'name': 'a',
335 'path': 'b',
336 }
337 s = ImportError('c', **d).__reduce__()
338 e = s[0](*s[1], **s[2])
339 for k, v in d.items():
340 assert getattr(e, k) == v
341
342 def test_modulenotfounderror(self):
343 assert ModuleNotFoundError("message").name is None
344 assert ModuleNotFoundError("message").path is None
345 assert ModuleNotFoundError("message", name="x").name == "x"
346 assert ModuleNotFoundError("message", path="y").path == "y"
347 raises(TypeError, ModuleNotFoundError, invalid="z")
348 assert repr(ModuleNotFoundError('test')) == "ModuleNotFoundError('test')"
349
350 def test_blockingioerror(self):
351 args = ("a", "b", "c", "d", "e")
352 for n in range(6):
353 e = BlockingIOError(*args[:n])
354 raises(AttributeError, getattr, e, 'characters_written')
355 e = BlockingIOError("a", "b", 3)
356 assert e.characters_written == 3
357 e.characters_written = 5
358 assert e.characters_written == 5
359 del e.characters_written
360 with raises(AttributeError):
361 e.characters_written
362
363 def test_errno_mapping(self):
364 # The OSError constructor maps errnos to subclasses
365 map_lines = """
366 +-- BlockingIOError EAGAIN, EALREADY, EWOULDBLOCK, EINPROGRESS
367 +-- ChildProcessError ECHILD
368 +-- ConnectionError
369 +-- BrokenPipeError EPIPE, ESHUTDOWN
370 +-- ConnectionAbortedError ECONNABORTED
371 +-- ConnectionRefusedError ECONNREFUSED
372 +-- ConnectionResetError ECONNRESET
373 +-- FileExistsError EEXIST
374 +-- FileNotFoundError ENOENT
375 +-- InterruptedError EINTR
376 +-- IsADirectoryError EISDIR
377 +-- NotADirectoryError ENOTDIR
378 +-- PermissionError EACCES, EPERM
379 +-- ProcessLookupError ESRCH
380 +-- TimeoutError ETIMEDOUT
381 """
382 import errno, builtins
383 map = {}
384 for line in map_lines.splitlines():
385 line = line.strip('+- ')
386 if not line:
387 continue
388 excname, _, errnames = line.partition(' ')
389 for errname in filter(None, errnames.strip().split(', ')):
390 map[getattr(errno, errname)] = getattr(builtins, excname)
391 e = OSError(errno.EEXIST, "Bad file descriptor")
392 assert type(e) is FileExistsError
393 # Exhaustive testing
394 for errcode, exc in map.items():
395 e = OSError(errcode, "Some message")
396 assert type(e) is exc
397 othercodes = set(errno.errorcode) - set(map)
398 for errcode in othercodes:
399 e = OSError(errcode, "Some message")
400 assert type(e) is OSError
401
402 def test_oserror_init_overriden(self):
403 class SubOSErrorWithInit(OSError):
404 def __init__(self, message, bar):
405 self.bar = bar
406 super().__init__(message)
407
408 e = SubOSErrorWithInit("some message", "baz")
409 assert e.bar == "baz"
410 assert e.args == ("some message",)
411
412 e = SubOSErrorWithInit("some message", bar="baz")
413 assert e.bar == "baz"
414 assert e.args == ("some message",)
415
416 def test_oserror_new_overriden(self):
417 class SubOSErrorWithNew(OSError):
418 def __new__(cls, message, baz):
419 self = super().__new__(cls, message)
420 self.baz = baz
421 return self
422
423 e = SubOSErrorWithNew("some message", "baz")
424 assert e.baz == "baz"
425 assert e.args == ("some message",)
426
427 e = SubOSErrorWithNew("some message", baz="baz")
428 assert e.baz == "baz"
429 assert e.args == ("some message",)
430 assert e.filename is None
431 assert e.filename2 is None
432
433 def test_oserror_3_args(self):
434 e = OSError(42, "bar", "baz")
435 assert e.args == (42, "bar")
436 assert e.filename == "baz"
437 assert e.filename2 is None
438 assert str(e) == "[Errno 42] bar: 'baz'"
439
440 def test_oserror_5_args(self):
441 # NB. argument 4 is only parsed on Windows
442 e = OSError(42, "bar", "baz", None, "bok")
443 assert e.args == (42, "bar")
444 assert e.filename == "baz"
445 assert e.filename2 == "bok"
446 assert str(e) == "[Errno 42] bar: 'baz' -> 'bok'"
447
448 def test_oserror_None(self):
449 assert str(OSError()) == ""
450 assert str(OSError(None)) == "None"
451 assert str(OSError(None, None)) == "[Errno None] None"
452 assert str(OSError(None, None, None, None)) == "[Errno None] None"
453
454 # Check the heuristic for print & exec covers significant cases
455 # As well as placing some limits on false positives
456 def test_former_statements_refer_to_builtins(self):
457 keywords = "print", "exec"
458 def exec_(s): exec(s)
459 # Cases where we want the custom error
460 cases = [
461 "{} foo",
462 "{} {{1:foo}}",
463 "if 1: {} foo",
464 "if 1: {} {{1:foo}}",
465 "if 1:\n {} foo",
466 "if 1:\n {} {{1:foo}}",
467 ]
468 for keyword in keywords:
469 custom_msg = "call to '{}'".format(keyword)
470 for case in cases:
471 source = case.format(keyword)
472 exc = raises(SyntaxError, exec_, source)
473 assert custom_msg in exc.value.msg
474 # XXX the following line passes on CPython but not on
475 # PyPy, but do we really care about this single special
476 # case?
477 #assert exc.value.args[0] == 'invalid syntax'
478
479 source = source.replace("foo", "(foo.)")
480 exc = raises(SyntaxError, exec_, source)
481 print('source "%s"' % source)
482 print('custom_msg "%s"' % custom_msg)
483 print('exc.value.msg "%s"' % exc.value.msg)
484 assert (custom_msg not in exc.value.msg) == (
485 ('print ' in source or 'exec ' in source))
486
487 def test_bug_print_heuristic_shadows_better_message(self):
488 def exec_(s): exec(s)
489 exc = raises(SyntaxError, exec_, "print [)")
490 assert "closing parenthesis ')' does not match opening parenthesis '['" in exc.value.msg
491
492 def test_print_suggestions(self):
493 def exec_(s): exec(s)
494 def check(s, error):
495 exc = raises(SyntaxError, exec_, s)
496 print(exc.value.msg)
497 assert exc.value.msg == error
498
499 check(
500 "print 1",
501 "Missing parentheses in call to 'print'. Did you mean print(1)?")
502 check(
503 "print 1, \t",
504 "Missing parentheses in call to 'print'. Did you mean print(1, end=\" \")?")
505 check(
506 "print 'a'\n;\t ",
507 "Missing parentheses in call to 'print'. Did you mean print('a')?")
508 check(
509 "print p;",
510 "Missing parentheses in call to 'print'. Did you mean print(p)?")
511 check("print %", "invalid syntax")
512 check("print 1 1",
513 "Missing parentheses in call to 'print'. Did you mean print(...)?")
514
515 def test_print_and_operators(self):
516 with raises(TypeError) as excinfo:
517 print >> 1, 5
518 assert 'Did you mean "print(<message>, file=<output_stream>)"?' in str(excinfo.value)
519 with raises(TypeError) as excinfo:
520 print -1
521 assert 'Did you mean "print(<-number>)"?' in str(excinfo.value)
522
523
524 def test_attribute_error_name_obj_attributes(self):
525 exc = AttributeError("'a' not found", name="a", obj=7)
526 assert exc.name == "a"
527 assert exc.obj == 7
528
529 def test_attribute_errorr_name_obj_attributes_are_filled(self):
530 class A:
531 pass
532 a = A()
533 with raises(AttributeError) as info:
534 a.blub
535 exc = info.value
536 assert exc.name == "blub"
537 assert exc.obj is a
538
539 def test_name_error_name_attribute(self):
540 exc = NameError("'a' not found", name="a")
541 assert exc.name == "a"
542
543 def test_name_error_name_attributes_are_filled(self):
544 class A:
545 pass
546 a = A()
547 with raises(NameError) as info:
548 blub
549 exc = info.value
550 assert exc.name == "blub"
551
552 def test_multiple_inheritance_bug(self):
553 class OptionError(AttributeError, KeyError):
554 pass # does not crash
555 assert issubclass(OptionError, Exception)
556 assert issubclass(OptionError, AttributeError)
557 assert issubclass(OptionError, KeyError)
558 assert issubclass(OptionError, LookupError)
559 OptionError() # check that instantiation works
560
561 def test_multiple_inheritance_bug2(self):
562 class E(EnvironmentError, KeyError): pass
563 assert KeyError.__str__(E(6)) == '6'
564 # harder
565 class E2(KeyError, EnvironmentError): pass
566 assert str(E2(6)) == '6'
567
568 def test_keyerror_subclass(self):
569 class E(KeyError):
570 pass
571 assert str(E(1)) == '1'
572
573 def test_encodingwarning(self):
574 assert isinstance(EncodingWarning('abc'), Warning)