1 | n/a | # Python test set -- built-in functions |
---|
2 | n/a | |
---|
3 | n/a | import ast |
---|
4 | n/a | import builtins |
---|
5 | n/a | import collections |
---|
6 | n/a | import decimal |
---|
7 | n/a | import fractions |
---|
8 | n/a | import io |
---|
9 | n/a | import locale |
---|
10 | n/a | import os |
---|
11 | n/a | import pickle |
---|
12 | n/a | import platform |
---|
13 | n/a | import random |
---|
14 | n/a | import re |
---|
15 | n/a | import sys |
---|
16 | n/a | import traceback |
---|
17 | n/a | import types |
---|
18 | n/a | import unittest |
---|
19 | n/a | import warnings |
---|
20 | n/a | from operator import neg |
---|
21 | n/a | from test.support import TESTFN, unlink, run_unittest, check_warnings |
---|
22 | n/a | from test.support.script_helper import assert_python_ok |
---|
23 | n/a | try: |
---|
24 | n/a | import pty, signal |
---|
25 | n/a | except ImportError: |
---|
26 | n/a | pty = signal = None |
---|
27 | n/a | |
---|
28 | n/a | |
---|
29 | n/a | class Squares: |
---|
30 | n/a | |
---|
31 | n/a | def __init__(self, max): |
---|
32 | n/a | self.max = max |
---|
33 | n/a | self.sofar = [] |
---|
34 | n/a | |
---|
35 | n/a | def __len__(self): return len(self.sofar) |
---|
36 | n/a | |
---|
37 | n/a | def __getitem__(self, i): |
---|
38 | n/a | if not 0 <= i < self.max: raise IndexError |
---|
39 | n/a | n = len(self.sofar) |
---|
40 | n/a | while n <= i: |
---|
41 | n/a | self.sofar.append(n*n) |
---|
42 | n/a | n += 1 |
---|
43 | n/a | return self.sofar[i] |
---|
44 | n/a | |
---|
45 | n/a | class StrSquares: |
---|
46 | n/a | |
---|
47 | n/a | def __init__(self, max): |
---|
48 | n/a | self.max = max |
---|
49 | n/a | self.sofar = [] |
---|
50 | n/a | |
---|
51 | n/a | def __len__(self): |
---|
52 | n/a | return len(self.sofar) |
---|
53 | n/a | |
---|
54 | n/a | def __getitem__(self, i): |
---|
55 | n/a | if not 0 <= i < self.max: |
---|
56 | n/a | raise IndexError |
---|
57 | n/a | n = len(self.sofar) |
---|
58 | n/a | while n <= i: |
---|
59 | n/a | self.sofar.append(str(n*n)) |
---|
60 | n/a | n += 1 |
---|
61 | n/a | return self.sofar[i] |
---|
62 | n/a | |
---|
63 | n/a | class BitBucket: |
---|
64 | n/a | def write(self, line): |
---|
65 | n/a | pass |
---|
66 | n/a | |
---|
67 | n/a | test_conv_no_sign = [ |
---|
68 | n/a | ('0', 0), |
---|
69 | n/a | ('1', 1), |
---|
70 | n/a | ('9', 9), |
---|
71 | n/a | ('10', 10), |
---|
72 | n/a | ('99', 99), |
---|
73 | n/a | ('100', 100), |
---|
74 | n/a | ('314', 314), |
---|
75 | n/a | (' 314', 314), |
---|
76 | n/a | ('314 ', 314), |
---|
77 | n/a | (' \t\t 314 \t\t ', 314), |
---|
78 | n/a | (repr(sys.maxsize), sys.maxsize), |
---|
79 | n/a | (' 1x', ValueError), |
---|
80 | n/a | (' 1 ', 1), |
---|
81 | n/a | (' 1\02 ', ValueError), |
---|
82 | n/a | ('', ValueError), |
---|
83 | n/a | (' ', ValueError), |
---|
84 | n/a | (' \t\t ', ValueError), |
---|
85 | n/a | (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), |
---|
86 | n/a | (chr(0x200), ValueError), |
---|
87 | n/a | ] |
---|
88 | n/a | |
---|
89 | n/a | test_conv_sign = [ |
---|
90 | n/a | ('0', 0), |
---|
91 | n/a | ('1', 1), |
---|
92 | n/a | ('9', 9), |
---|
93 | n/a | ('10', 10), |
---|
94 | n/a | ('99', 99), |
---|
95 | n/a | ('100', 100), |
---|
96 | n/a | ('314', 314), |
---|
97 | n/a | (' 314', ValueError), |
---|
98 | n/a | ('314 ', 314), |
---|
99 | n/a | (' \t\t 314 \t\t ', ValueError), |
---|
100 | n/a | (repr(sys.maxsize), sys.maxsize), |
---|
101 | n/a | (' 1x', ValueError), |
---|
102 | n/a | (' 1 ', ValueError), |
---|
103 | n/a | (' 1\02 ', ValueError), |
---|
104 | n/a | ('', ValueError), |
---|
105 | n/a | (' ', ValueError), |
---|
106 | n/a | (' \t\t ', ValueError), |
---|
107 | n/a | (str(br'\u0663\u0661\u0664 ','raw-unicode-escape'), 314), |
---|
108 | n/a | (chr(0x200), ValueError), |
---|
109 | n/a | ] |
---|
110 | n/a | |
---|
111 | n/a | class TestFailingBool: |
---|
112 | n/a | def __bool__(self): |
---|
113 | n/a | raise RuntimeError |
---|
114 | n/a | |
---|
115 | n/a | class TestFailingIter: |
---|
116 | n/a | def __iter__(self): |
---|
117 | n/a | raise RuntimeError |
---|
118 | n/a | |
---|
119 | n/a | def filter_char(arg): |
---|
120 | n/a | return ord(arg) > ord("d") |
---|
121 | n/a | |
---|
122 | n/a | def map_char(arg): |
---|
123 | n/a | return chr(ord(arg)+1) |
---|
124 | n/a | |
---|
125 | n/a | class BuiltinTest(unittest.TestCase): |
---|
126 | n/a | # Helper to check picklability |
---|
127 | n/a | def check_iter_pickle(self, it, seq, proto): |
---|
128 | n/a | itorg = it |
---|
129 | n/a | d = pickle.dumps(it, proto) |
---|
130 | n/a | it = pickle.loads(d) |
---|
131 | n/a | self.assertEqual(type(itorg), type(it)) |
---|
132 | n/a | self.assertEqual(list(it), seq) |
---|
133 | n/a | |
---|
134 | n/a | #test the iterator after dropping one from it |
---|
135 | n/a | it = pickle.loads(d) |
---|
136 | n/a | try: |
---|
137 | n/a | next(it) |
---|
138 | n/a | except StopIteration: |
---|
139 | n/a | return |
---|
140 | n/a | d = pickle.dumps(it, proto) |
---|
141 | n/a | it = pickle.loads(d) |
---|
142 | n/a | self.assertEqual(list(it), seq[1:]) |
---|
143 | n/a | |
---|
144 | n/a | def test_import(self): |
---|
145 | n/a | __import__('sys') |
---|
146 | n/a | __import__('time') |
---|
147 | n/a | __import__('string') |
---|
148 | n/a | __import__(name='sys') |
---|
149 | n/a | __import__(name='time', level=0) |
---|
150 | n/a | self.assertRaises(ImportError, __import__, 'spamspam') |
---|
151 | n/a | self.assertRaises(TypeError, __import__, 1, 2, 3, 4) |
---|
152 | n/a | self.assertRaises(ValueError, __import__, '') |
---|
153 | n/a | self.assertRaises(TypeError, __import__, 'sys', name='sys') |
---|
154 | n/a | |
---|
155 | n/a | def test_abs(self): |
---|
156 | n/a | # int |
---|
157 | n/a | self.assertEqual(abs(0), 0) |
---|
158 | n/a | self.assertEqual(abs(1234), 1234) |
---|
159 | n/a | self.assertEqual(abs(-1234), 1234) |
---|
160 | n/a | self.assertTrue(abs(-sys.maxsize-1) > 0) |
---|
161 | n/a | # float |
---|
162 | n/a | self.assertEqual(abs(0.0), 0.0) |
---|
163 | n/a | self.assertEqual(abs(3.14), 3.14) |
---|
164 | n/a | self.assertEqual(abs(-3.14), 3.14) |
---|
165 | n/a | # str |
---|
166 | n/a | self.assertRaises(TypeError, abs, 'a') |
---|
167 | n/a | # bool |
---|
168 | n/a | self.assertEqual(abs(True), 1) |
---|
169 | n/a | self.assertEqual(abs(False), 0) |
---|
170 | n/a | # other |
---|
171 | n/a | self.assertRaises(TypeError, abs) |
---|
172 | n/a | self.assertRaises(TypeError, abs, None) |
---|
173 | n/a | class AbsClass(object): |
---|
174 | n/a | def __abs__(self): |
---|
175 | n/a | return -5 |
---|
176 | n/a | self.assertEqual(abs(AbsClass()), -5) |
---|
177 | n/a | |
---|
178 | n/a | def test_all(self): |
---|
179 | n/a | self.assertEqual(all([2, 4, 6]), True) |
---|
180 | n/a | self.assertEqual(all([2, None, 6]), False) |
---|
181 | n/a | self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6]) |
---|
182 | n/a | self.assertRaises(RuntimeError, all, TestFailingIter()) |
---|
183 | n/a | self.assertRaises(TypeError, all, 10) # Non-iterable |
---|
184 | n/a | self.assertRaises(TypeError, all) # No args |
---|
185 | n/a | self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args |
---|
186 | n/a | self.assertEqual(all([]), True) # Empty iterator |
---|
187 | n/a | self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit |
---|
188 | n/a | S = [50, 60] |
---|
189 | n/a | self.assertEqual(all(x > 42 for x in S), True) |
---|
190 | n/a | S = [50, 40, 60] |
---|
191 | n/a | self.assertEqual(all(x > 42 for x in S), False) |
---|
192 | n/a | |
---|
193 | n/a | def test_any(self): |
---|
194 | n/a | self.assertEqual(any([None, None, None]), False) |
---|
195 | n/a | self.assertEqual(any([None, 4, None]), True) |
---|
196 | n/a | self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6]) |
---|
197 | n/a | self.assertRaises(RuntimeError, any, TestFailingIter()) |
---|
198 | n/a | self.assertRaises(TypeError, any, 10) # Non-iterable |
---|
199 | n/a | self.assertRaises(TypeError, any) # No args |
---|
200 | n/a | self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args |
---|
201 | n/a | self.assertEqual(any([]), False) # Empty iterator |
---|
202 | n/a | self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit |
---|
203 | n/a | S = [40, 60, 30] |
---|
204 | n/a | self.assertEqual(any(x > 42 for x in S), True) |
---|
205 | n/a | S = [10, 20, 30] |
---|
206 | n/a | self.assertEqual(any(x > 42 for x in S), False) |
---|
207 | n/a | |
---|
208 | n/a | def test_ascii(self): |
---|
209 | n/a | self.assertEqual(ascii(''), '\'\'') |
---|
210 | n/a | self.assertEqual(ascii(0), '0') |
---|
211 | n/a | self.assertEqual(ascii(()), '()') |
---|
212 | n/a | self.assertEqual(ascii([]), '[]') |
---|
213 | n/a | self.assertEqual(ascii({}), '{}') |
---|
214 | n/a | a = [] |
---|
215 | n/a | a.append(a) |
---|
216 | n/a | self.assertEqual(ascii(a), '[[...]]') |
---|
217 | n/a | a = {} |
---|
218 | n/a | a[0] = a |
---|
219 | n/a | self.assertEqual(ascii(a), '{0: {...}}') |
---|
220 | n/a | # Advanced checks for unicode strings |
---|
221 | n/a | def _check_uni(s): |
---|
222 | n/a | self.assertEqual(ascii(s), repr(s)) |
---|
223 | n/a | _check_uni("'") |
---|
224 | n/a | _check_uni('"') |
---|
225 | n/a | _check_uni('"\'') |
---|
226 | n/a | _check_uni('\0') |
---|
227 | n/a | _check_uni('\r\n\t .') |
---|
228 | n/a | # Unprintable non-ASCII characters |
---|
229 | n/a | _check_uni('\x85') |
---|
230 | n/a | _check_uni('\u1fff') |
---|
231 | n/a | _check_uni('\U00012fff') |
---|
232 | n/a | # Lone surrogates |
---|
233 | n/a | _check_uni('\ud800') |
---|
234 | n/a | _check_uni('\udfff') |
---|
235 | n/a | # Issue #9804: surrogates should be joined even for printable |
---|
236 | n/a | # wide characters (UCS-2 builds). |
---|
237 | n/a | self.assertEqual(ascii('\U0001d121'), "'\\U0001d121'") |
---|
238 | n/a | # All together |
---|
239 | n/a | s = "'\0\"\n\r\t abcd\x85é\U00012fff\uD800\U0001D121xxx." |
---|
240 | n/a | self.assertEqual(ascii(s), |
---|
241 | n/a | r"""'\'\x00"\n\r\t abcd\x85\xe9\U00012fff\ud800\U0001d121xxx.'""") |
---|
242 | n/a | |
---|
243 | n/a | def test_neg(self): |
---|
244 | n/a | x = -sys.maxsize-1 |
---|
245 | n/a | self.assertTrue(isinstance(x, int)) |
---|
246 | n/a | self.assertEqual(-x, sys.maxsize+1) |
---|
247 | n/a | |
---|
248 | n/a | def test_callable(self): |
---|
249 | n/a | self.assertTrue(callable(len)) |
---|
250 | n/a | self.assertFalse(callable("a")) |
---|
251 | n/a | self.assertTrue(callable(callable)) |
---|
252 | n/a | self.assertTrue(callable(lambda x, y: x + y)) |
---|
253 | n/a | self.assertFalse(callable(__builtins__)) |
---|
254 | n/a | def f(): pass |
---|
255 | n/a | self.assertTrue(callable(f)) |
---|
256 | n/a | |
---|
257 | n/a | class C1: |
---|
258 | n/a | def meth(self): pass |
---|
259 | n/a | self.assertTrue(callable(C1)) |
---|
260 | n/a | c = C1() |
---|
261 | n/a | self.assertTrue(callable(c.meth)) |
---|
262 | n/a | self.assertFalse(callable(c)) |
---|
263 | n/a | |
---|
264 | n/a | # __call__ is looked up on the class, not the instance |
---|
265 | n/a | c.__call__ = None |
---|
266 | n/a | self.assertFalse(callable(c)) |
---|
267 | n/a | c.__call__ = lambda self: 0 |
---|
268 | n/a | self.assertFalse(callable(c)) |
---|
269 | n/a | del c.__call__ |
---|
270 | n/a | self.assertFalse(callable(c)) |
---|
271 | n/a | |
---|
272 | n/a | class C2(object): |
---|
273 | n/a | def __call__(self): pass |
---|
274 | n/a | c2 = C2() |
---|
275 | n/a | self.assertTrue(callable(c2)) |
---|
276 | n/a | c2.__call__ = None |
---|
277 | n/a | self.assertTrue(callable(c2)) |
---|
278 | n/a | class C3(C2): pass |
---|
279 | n/a | c3 = C3() |
---|
280 | n/a | self.assertTrue(callable(c3)) |
---|
281 | n/a | |
---|
282 | n/a | def test_chr(self): |
---|
283 | n/a | self.assertEqual(chr(32), ' ') |
---|
284 | n/a | self.assertEqual(chr(65), 'A') |
---|
285 | n/a | self.assertEqual(chr(97), 'a') |
---|
286 | n/a | self.assertEqual(chr(0xff), '\xff') |
---|
287 | n/a | self.assertRaises(ValueError, chr, 1<<24) |
---|
288 | n/a | self.assertEqual(chr(sys.maxunicode), |
---|
289 | n/a | str('\\U0010ffff'.encode("ascii"), 'unicode-escape')) |
---|
290 | n/a | self.assertRaises(TypeError, chr) |
---|
291 | n/a | self.assertEqual(chr(0x0000FFFF), "\U0000FFFF") |
---|
292 | n/a | self.assertEqual(chr(0x00010000), "\U00010000") |
---|
293 | n/a | self.assertEqual(chr(0x00010001), "\U00010001") |
---|
294 | n/a | self.assertEqual(chr(0x000FFFFE), "\U000FFFFE") |
---|
295 | n/a | self.assertEqual(chr(0x000FFFFF), "\U000FFFFF") |
---|
296 | n/a | self.assertEqual(chr(0x00100000), "\U00100000") |
---|
297 | n/a | self.assertEqual(chr(0x00100001), "\U00100001") |
---|
298 | n/a | self.assertEqual(chr(0x0010FFFE), "\U0010FFFE") |
---|
299 | n/a | self.assertEqual(chr(0x0010FFFF), "\U0010FFFF") |
---|
300 | n/a | self.assertRaises(ValueError, chr, -1) |
---|
301 | n/a | self.assertRaises(ValueError, chr, 0x00110000) |
---|
302 | n/a | self.assertRaises((OverflowError, ValueError), chr, 2**32) |
---|
303 | n/a | |
---|
304 | n/a | def test_cmp(self): |
---|
305 | n/a | self.assertTrue(not hasattr(builtins, "cmp")) |
---|
306 | n/a | |
---|
307 | n/a | def test_compile(self): |
---|
308 | n/a | compile('print(1)\n', '', 'exec') |
---|
309 | n/a | bom = b'\xef\xbb\xbf' |
---|
310 | n/a | compile(bom + b'print(1)\n', '', 'exec') |
---|
311 | n/a | compile(source='pass', filename='?', mode='exec') |
---|
312 | n/a | compile(dont_inherit=0, filename='tmp', source='0', mode='eval') |
---|
313 | n/a | compile('pass', '?', dont_inherit=1, mode='exec') |
---|
314 | n/a | compile(memoryview(b"text"), "name", "exec") |
---|
315 | n/a | self.assertRaises(TypeError, compile) |
---|
316 | n/a | self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'badmode') |
---|
317 | n/a | self.assertRaises(ValueError, compile, 'print(42)\n', '<string>', 'single', 0xff) |
---|
318 | n/a | self.assertRaises(ValueError, compile, chr(0), 'f', 'exec') |
---|
319 | n/a | self.assertRaises(TypeError, compile, 'pass', '?', 'exec', |
---|
320 | n/a | mode='eval', source='0', filename='tmp') |
---|
321 | n/a | compile('print("\xe5")\n', '', 'exec') |
---|
322 | n/a | self.assertRaises(ValueError, compile, chr(0), 'f', 'exec') |
---|
323 | n/a | self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad') |
---|
324 | n/a | |
---|
325 | n/a | # test the optimize argument |
---|
326 | n/a | |
---|
327 | n/a | codestr = '''def f(): |
---|
328 | n/a | """doc""" |
---|
329 | n/a | try: |
---|
330 | n/a | assert False |
---|
331 | n/a | except AssertionError: |
---|
332 | n/a | return (True, f.__doc__) |
---|
333 | n/a | else: |
---|
334 | n/a | return (False, f.__doc__) |
---|
335 | n/a | ''' |
---|
336 | n/a | def f(): """doc""" |
---|
337 | n/a | values = [(-1, __debug__, f.__doc__), |
---|
338 | n/a | (0, True, 'doc'), |
---|
339 | n/a | (1, False, 'doc'), |
---|
340 | n/a | (2, False, None)] |
---|
341 | n/a | for optval, debugval, docstring in values: |
---|
342 | n/a | # test both direct compilation and compilation via AST |
---|
343 | n/a | codeobjs = [] |
---|
344 | n/a | codeobjs.append(compile(codestr, "<test>", "exec", optimize=optval)) |
---|
345 | n/a | tree = ast.parse(codestr) |
---|
346 | n/a | codeobjs.append(compile(tree, "<test>", "exec", optimize=optval)) |
---|
347 | n/a | for code in codeobjs: |
---|
348 | n/a | ns = {} |
---|
349 | n/a | exec(code, ns) |
---|
350 | n/a | rv = ns['f']() |
---|
351 | n/a | self.assertEqual(rv, (debugval, docstring)) |
---|
352 | n/a | |
---|
353 | n/a | def test_delattr(self): |
---|
354 | n/a | sys.spam = 1 |
---|
355 | n/a | delattr(sys, 'spam') |
---|
356 | n/a | self.assertRaises(TypeError, delattr) |
---|
357 | n/a | |
---|
358 | n/a | def test_dir(self): |
---|
359 | n/a | # dir(wrong number of arguments) |
---|
360 | n/a | self.assertRaises(TypeError, dir, 42, 42) |
---|
361 | n/a | |
---|
362 | n/a | # dir() - local scope |
---|
363 | n/a | local_var = 1 |
---|
364 | n/a | self.assertIn('local_var', dir()) |
---|
365 | n/a | |
---|
366 | n/a | # dir(module) |
---|
367 | n/a | self.assertIn('exit', dir(sys)) |
---|
368 | n/a | |
---|
369 | n/a | # dir(module_with_invalid__dict__) |
---|
370 | n/a | class Foo(types.ModuleType): |
---|
371 | n/a | __dict__ = 8 |
---|
372 | n/a | f = Foo("foo") |
---|
373 | n/a | self.assertRaises(TypeError, dir, f) |
---|
374 | n/a | |
---|
375 | n/a | # dir(type) |
---|
376 | n/a | self.assertIn("strip", dir(str)) |
---|
377 | n/a | self.assertNotIn("__mro__", dir(str)) |
---|
378 | n/a | |
---|
379 | n/a | # dir(obj) |
---|
380 | n/a | class Foo(object): |
---|
381 | n/a | def __init__(self): |
---|
382 | n/a | self.x = 7 |
---|
383 | n/a | self.y = 8 |
---|
384 | n/a | self.z = 9 |
---|
385 | n/a | f = Foo() |
---|
386 | n/a | self.assertIn("y", dir(f)) |
---|
387 | n/a | |
---|
388 | n/a | # dir(obj_no__dict__) |
---|
389 | n/a | class Foo(object): |
---|
390 | n/a | __slots__ = [] |
---|
391 | n/a | f = Foo() |
---|
392 | n/a | self.assertIn("__repr__", dir(f)) |
---|
393 | n/a | |
---|
394 | n/a | # dir(obj_no__class__with__dict__) |
---|
395 | n/a | # (an ugly trick to cause getattr(f, "__class__") to fail) |
---|
396 | n/a | class Foo(object): |
---|
397 | n/a | __slots__ = ["__class__", "__dict__"] |
---|
398 | n/a | def __init__(self): |
---|
399 | n/a | self.bar = "wow" |
---|
400 | n/a | f = Foo() |
---|
401 | n/a | self.assertNotIn("__repr__", dir(f)) |
---|
402 | n/a | self.assertIn("bar", dir(f)) |
---|
403 | n/a | |
---|
404 | n/a | # dir(obj_using __dir__) |
---|
405 | n/a | class Foo(object): |
---|
406 | n/a | def __dir__(self): |
---|
407 | n/a | return ["kan", "ga", "roo"] |
---|
408 | n/a | f = Foo() |
---|
409 | n/a | self.assertTrue(dir(f) == ["ga", "kan", "roo"]) |
---|
410 | n/a | |
---|
411 | n/a | # dir(obj__dir__tuple) |
---|
412 | n/a | class Foo(object): |
---|
413 | n/a | def __dir__(self): |
---|
414 | n/a | return ("b", "c", "a") |
---|
415 | n/a | res = dir(Foo()) |
---|
416 | n/a | self.assertIsInstance(res, list) |
---|
417 | n/a | self.assertTrue(res == ["a", "b", "c"]) |
---|
418 | n/a | |
---|
419 | n/a | # dir(obj__dir__not_sequence) |
---|
420 | n/a | class Foo(object): |
---|
421 | n/a | def __dir__(self): |
---|
422 | n/a | return 7 |
---|
423 | n/a | f = Foo() |
---|
424 | n/a | self.assertRaises(TypeError, dir, f) |
---|
425 | n/a | |
---|
426 | n/a | # dir(traceback) |
---|
427 | n/a | try: |
---|
428 | n/a | raise IndexError |
---|
429 | n/a | except: |
---|
430 | n/a | self.assertEqual(len(dir(sys.exc_info()[2])), 4) |
---|
431 | n/a | |
---|
432 | n/a | # test that object has a __dir__() |
---|
433 | n/a | self.assertEqual(sorted([].__dir__()), dir([])) |
---|
434 | n/a | |
---|
435 | n/a | def test_divmod(self): |
---|
436 | n/a | self.assertEqual(divmod(12, 7), (1, 5)) |
---|
437 | n/a | self.assertEqual(divmod(-12, 7), (-2, 2)) |
---|
438 | n/a | self.assertEqual(divmod(12, -7), (-2, -2)) |
---|
439 | n/a | self.assertEqual(divmod(-12, -7), (1, -5)) |
---|
440 | n/a | |
---|
441 | n/a | self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0)) |
---|
442 | n/a | |
---|
443 | n/a | for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)), |
---|
444 | n/a | (-3.25, 1.0, (-4.0, 0.75)), |
---|
445 | n/a | (3.25, -1.0, (-4.0, -0.75)), |
---|
446 | n/a | (-3.25, -1.0, (3.0, -0.25))]: |
---|
447 | n/a | result = divmod(num, denom) |
---|
448 | n/a | self.assertAlmostEqual(result[0], exp_result[0]) |
---|
449 | n/a | self.assertAlmostEqual(result[1], exp_result[1]) |
---|
450 | n/a | |
---|
451 | n/a | self.assertRaises(TypeError, divmod) |
---|
452 | n/a | |
---|
453 | n/a | def test_eval(self): |
---|
454 | n/a | self.assertEqual(eval('1+1'), 2) |
---|
455 | n/a | self.assertEqual(eval(' 1+1\n'), 2) |
---|
456 | n/a | globals = {'a': 1, 'b': 2} |
---|
457 | n/a | locals = {'b': 200, 'c': 300} |
---|
458 | n/a | self.assertEqual(eval('a', globals) , 1) |
---|
459 | n/a | self.assertEqual(eval('a', globals, locals), 1) |
---|
460 | n/a | self.assertEqual(eval('b', globals, locals), 200) |
---|
461 | n/a | self.assertEqual(eval('c', globals, locals), 300) |
---|
462 | n/a | globals = {'a': 1, 'b': 2} |
---|
463 | n/a | locals = {'b': 200, 'c': 300} |
---|
464 | n/a | bom = b'\xef\xbb\xbf' |
---|
465 | n/a | self.assertEqual(eval(bom + b'a', globals, locals), 1) |
---|
466 | n/a | self.assertEqual(eval('"\xe5"', globals), "\xe5") |
---|
467 | n/a | self.assertRaises(TypeError, eval) |
---|
468 | n/a | self.assertRaises(TypeError, eval, ()) |
---|
469 | n/a | self.assertRaises(SyntaxError, eval, bom[:2] + b'a') |
---|
470 | n/a | |
---|
471 | n/a | class X: |
---|
472 | n/a | def __getitem__(self, key): |
---|
473 | n/a | raise ValueError |
---|
474 | n/a | self.assertRaises(ValueError, eval, "foo", {}, X()) |
---|
475 | n/a | |
---|
476 | n/a | def test_general_eval(self): |
---|
477 | n/a | # Tests that general mappings can be used for the locals argument |
---|
478 | n/a | |
---|
479 | n/a | class M: |
---|
480 | n/a | "Test mapping interface versus possible calls from eval()." |
---|
481 | n/a | def __getitem__(self, key): |
---|
482 | n/a | if key == 'a': |
---|
483 | n/a | return 12 |
---|
484 | n/a | raise KeyError |
---|
485 | n/a | def keys(self): |
---|
486 | n/a | return list('xyz') |
---|
487 | n/a | |
---|
488 | n/a | m = M() |
---|
489 | n/a | g = globals() |
---|
490 | n/a | self.assertEqual(eval('a', g, m), 12) |
---|
491 | n/a | self.assertRaises(NameError, eval, 'b', g, m) |
---|
492 | n/a | self.assertEqual(eval('dir()', g, m), list('xyz')) |
---|
493 | n/a | self.assertEqual(eval('globals()', g, m), g) |
---|
494 | n/a | self.assertEqual(eval('locals()', g, m), m) |
---|
495 | n/a | self.assertRaises(TypeError, eval, 'a', m) |
---|
496 | n/a | class A: |
---|
497 | n/a | "Non-mapping" |
---|
498 | n/a | pass |
---|
499 | n/a | m = A() |
---|
500 | n/a | self.assertRaises(TypeError, eval, 'a', g, m) |
---|
501 | n/a | |
---|
502 | n/a | # Verify that dict subclasses work as well |
---|
503 | n/a | class D(dict): |
---|
504 | n/a | def __getitem__(self, key): |
---|
505 | n/a | if key == 'a': |
---|
506 | n/a | return 12 |
---|
507 | n/a | return dict.__getitem__(self, key) |
---|
508 | n/a | def keys(self): |
---|
509 | n/a | return list('xyz') |
---|
510 | n/a | |
---|
511 | n/a | d = D() |
---|
512 | n/a | self.assertEqual(eval('a', g, d), 12) |
---|
513 | n/a | self.assertRaises(NameError, eval, 'b', g, d) |
---|
514 | n/a | self.assertEqual(eval('dir()', g, d), list('xyz')) |
---|
515 | n/a | self.assertEqual(eval('globals()', g, d), g) |
---|
516 | n/a | self.assertEqual(eval('locals()', g, d), d) |
---|
517 | n/a | |
---|
518 | n/a | # Verify locals stores (used by list comps) |
---|
519 | n/a | eval('[locals() for i in (2,3)]', g, d) |
---|
520 | n/a | eval('[locals() for i in (2,3)]', g, collections.UserDict()) |
---|
521 | n/a | |
---|
522 | n/a | class SpreadSheet: |
---|
523 | n/a | "Sample application showing nested, calculated lookups." |
---|
524 | n/a | _cells = {} |
---|
525 | n/a | def __setitem__(self, key, formula): |
---|
526 | n/a | self._cells[key] = formula |
---|
527 | n/a | def __getitem__(self, key): |
---|
528 | n/a | return eval(self._cells[key], globals(), self) |
---|
529 | n/a | |
---|
530 | n/a | ss = SpreadSheet() |
---|
531 | n/a | ss['a1'] = '5' |
---|
532 | n/a | ss['a2'] = 'a1*6' |
---|
533 | n/a | ss['a3'] = 'a2*7' |
---|
534 | n/a | self.assertEqual(ss['a3'], 210) |
---|
535 | n/a | |
---|
536 | n/a | # Verify that dir() catches a non-list returned by eval |
---|
537 | n/a | # SF bug #1004669 |
---|
538 | n/a | class C: |
---|
539 | n/a | def __getitem__(self, item): |
---|
540 | n/a | raise KeyError(item) |
---|
541 | n/a | def keys(self): |
---|
542 | n/a | return 1 # used to be 'a' but that's no longer an error |
---|
543 | n/a | self.assertRaises(TypeError, eval, 'dir()', globals(), C()) |
---|
544 | n/a | |
---|
545 | n/a | def test_exec(self): |
---|
546 | n/a | g = {} |
---|
547 | n/a | exec('z = 1', g) |
---|
548 | n/a | if '__builtins__' in g: |
---|
549 | n/a | del g['__builtins__'] |
---|
550 | n/a | self.assertEqual(g, {'z': 1}) |
---|
551 | n/a | |
---|
552 | n/a | exec('z = 1+1', g) |
---|
553 | n/a | if '__builtins__' in g: |
---|
554 | n/a | del g['__builtins__'] |
---|
555 | n/a | self.assertEqual(g, {'z': 2}) |
---|
556 | n/a | g = {} |
---|
557 | n/a | l = {} |
---|
558 | n/a | |
---|
559 | n/a | with check_warnings(): |
---|
560 | n/a | warnings.filterwarnings("ignore", "global statement", |
---|
561 | n/a | module="<string>") |
---|
562 | n/a | exec('global a; a = 1; b = 2', g, l) |
---|
563 | n/a | if '__builtins__' in g: |
---|
564 | n/a | del g['__builtins__'] |
---|
565 | n/a | if '__builtins__' in l: |
---|
566 | n/a | del l['__builtins__'] |
---|
567 | n/a | self.assertEqual((g, l), ({'a': 1}, {'b': 2})) |
---|
568 | n/a | |
---|
569 | n/a | def test_exec_globals(self): |
---|
570 | n/a | code = compile("print('Hello World!')", "", "exec") |
---|
571 | n/a | # no builtin function |
---|
572 | n/a | self.assertRaisesRegex(NameError, "name 'print' is not defined", |
---|
573 | n/a | exec, code, {'__builtins__': {}}) |
---|
574 | n/a | # __builtins__ must be a mapping type |
---|
575 | n/a | self.assertRaises(TypeError, |
---|
576 | n/a | exec, code, {'__builtins__': 123}) |
---|
577 | n/a | |
---|
578 | n/a | # no __build_class__ function |
---|
579 | n/a | code = compile("class A: pass", "", "exec") |
---|
580 | n/a | self.assertRaisesRegex(NameError, "__build_class__ not found", |
---|
581 | n/a | exec, code, {'__builtins__': {}}) |
---|
582 | n/a | |
---|
583 | n/a | class frozendict_error(Exception): |
---|
584 | n/a | pass |
---|
585 | n/a | |
---|
586 | n/a | class frozendict(dict): |
---|
587 | n/a | def __setitem__(self, key, value): |
---|
588 | n/a | raise frozendict_error("frozendict is readonly") |
---|
589 | n/a | |
---|
590 | n/a | # read-only builtins |
---|
591 | n/a | if isinstance(__builtins__, types.ModuleType): |
---|
592 | n/a | frozen_builtins = frozendict(__builtins__.__dict__) |
---|
593 | n/a | else: |
---|
594 | n/a | frozen_builtins = frozendict(__builtins__) |
---|
595 | n/a | code = compile("__builtins__['superglobal']=2; print(superglobal)", "test", "exec") |
---|
596 | n/a | self.assertRaises(frozendict_error, |
---|
597 | n/a | exec, code, {'__builtins__': frozen_builtins}) |
---|
598 | n/a | |
---|
599 | n/a | # read-only globals |
---|
600 | n/a | namespace = frozendict({}) |
---|
601 | n/a | code = compile("x=1", "test", "exec") |
---|
602 | n/a | self.assertRaises(frozendict_error, |
---|
603 | n/a | exec, code, namespace) |
---|
604 | n/a | |
---|
605 | n/a | def test_exec_redirected(self): |
---|
606 | n/a | savestdout = sys.stdout |
---|
607 | n/a | sys.stdout = None # Whatever that cannot flush() |
---|
608 | n/a | try: |
---|
609 | n/a | # Used to raise SystemError('error return without exception set') |
---|
610 | n/a | exec('a') |
---|
611 | n/a | except NameError: |
---|
612 | n/a | pass |
---|
613 | n/a | finally: |
---|
614 | n/a | sys.stdout = savestdout |
---|
615 | n/a | |
---|
616 | n/a | def test_filter(self): |
---|
617 | n/a | self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld')) |
---|
618 | n/a | self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9]) |
---|
619 | n/a | self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2]) |
---|
620 | n/a | self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81]) |
---|
621 | n/a | self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81]) |
---|
622 | n/a | def identity(item): |
---|
623 | n/a | return 1 |
---|
624 | n/a | filter(identity, Squares(5)) |
---|
625 | n/a | self.assertRaises(TypeError, filter) |
---|
626 | n/a | class BadSeq(object): |
---|
627 | n/a | def __getitem__(self, index): |
---|
628 | n/a | if index<4: |
---|
629 | n/a | return 42 |
---|
630 | n/a | raise ValueError |
---|
631 | n/a | self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq())) |
---|
632 | n/a | def badfunc(): |
---|
633 | n/a | pass |
---|
634 | n/a | self.assertRaises(TypeError, list, filter(badfunc, range(5))) |
---|
635 | n/a | |
---|
636 | n/a | # test bltinmodule.c::filtertuple() |
---|
637 | n/a | self.assertEqual(list(filter(None, (1, 2))), [1, 2]) |
---|
638 | n/a | self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4]) |
---|
639 | n/a | self.assertRaises(TypeError, list, filter(42, (1, 2))) |
---|
640 | n/a | |
---|
641 | n/a | def test_filter_pickle(self): |
---|
642 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
643 | n/a | f1 = filter(filter_char, "abcdeabcde") |
---|
644 | n/a | f2 = filter(filter_char, "abcdeabcde") |
---|
645 | n/a | self.check_iter_pickle(f1, list(f2), proto) |
---|
646 | n/a | |
---|
647 | n/a | def test_getattr(self): |
---|
648 | n/a | self.assertTrue(getattr(sys, 'stdout') is sys.stdout) |
---|
649 | n/a | self.assertRaises(TypeError, getattr, sys, 1) |
---|
650 | n/a | self.assertRaises(TypeError, getattr, sys, 1, "foo") |
---|
651 | n/a | self.assertRaises(TypeError, getattr) |
---|
652 | n/a | self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode)) |
---|
653 | n/a | # unicode surrogates are not encodable to the default encoding (utf8) |
---|
654 | n/a | self.assertRaises(AttributeError, getattr, 1, "\uDAD1\uD51E") |
---|
655 | n/a | |
---|
656 | n/a | def test_hasattr(self): |
---|
657 | n/a | self.assertTrue(hasattr(sys, 'stdout')) |
---|
658 | n/a | self.assertRaises(TypeError, hasattr, sys, 1) |
---|
659 | n/a | self.assertRaises(TypeError, hasattr) |
---|
660 | n/a | self.assertEqual(False, hasattr(sys, chr(sys.maxunicode))) |
---|
661 | n/a | |
---|
662 | n/a | # Check that hasattr propagates all exceptions outside of |
---|
663 | n/a | # AttributeError. |
---|
664 | n/a | class A: |
---|
665 | n/a | def __getattr__(self, what): |
---|
666 | n/a | raise SystemExit |
---|
667 | n/a | self.assertRaises(SystemExit, hasattr, A(), "b") |
---|
668 | n/a | class B: |
---|
669 | n/a | def __getattr__(self, what): |
---|
670 | n/a | raise ValueError |
---|
671 | n/a | self.assertRaises(ValueError, hasattr, B(), "b") |
---|
672 | n/a | |
---|
673 | n/a | def test_hash(self): |
---|
674 | n/a | hash(None) |
---|
675 | n/a | self.assertEqual(hash(1), hash(1)) |
---|
676 | n/a | self.assertEqual(hash(1), hash(1.0)) |
---|
677 | n/a | hash('spam') |
---|
678 | n/a | self.assertEqual(hash('spam'), hash(b'spam')) |
---|
679 | n/a | hash((0,1,2,3)) |
---|
680 | n/a | def f(): pass |
---|
681 | n/a | self.assertRaises(TypeError, hash, []) |
---|
682 | n/a | self.assertRaises(TypeError, hash, {}) |
---|
683 | n/a | # Bug 1536021: Allow hash to return long objects |
---|
684 | n/a | class X: |
---|
685 | n/a | def __hash__(self): |
---|
686 | n/a | return 2**100 |
---|
687 | n/a | self.assertEqual(type(hash(X())), int) |
---|
688 | n/a | class Z(int): |
---|
689 | n/a | def __hash__(self): |
---|
690 | n/a | return self |
---|
691 | n/a | self.assertEqual(hash(Z(42)), hash(42)) |
---|
692 | n/a | |
---|
693 | n/a | def test_hex(self): |
---|
694 | n/a | self.assertEqual(hex(16), '0x10') |
---|
695 | n/a | self.assertEqual(hex(-16), '-0x10') |
---|
696 | n/a | self.assertRaises(TypeError, hex, {}) |
---|
697 | n/a | |
---|
698 | n/a | def test_id(self): |
---|
699 | n/a | id(None) |
---|
700 | n/a | id(1) |
---|
701 | n/a | id(1.0) |
---|
702 | n/a | id('spam') |
---|
703 | n/a | id((0,1,2,3)) |
---|
704 | n/a | id([0,1,2,3]) |
---|
705 | n/a | id({'spam': 1, 'eggs': 2, 'ham': 3}) |
---|
706 | n/a | |
---|
707 | n/a | # Test input() later, alphabetized as if it were raw_input |
---|
708 | n/a | |
---|
709 | n/a | def test_iter(self): |
---|
710 | n/a | self.assertRaises(TypeError, iter) |
---|
711 | n/a | self.assertRaises(TypeError, iter, 42, 42) |
---|
712 | n/a | lists = [("1", "2"), ["1", "2"], "12"] |
---|
713 | n/a | for l in lists: |
---|
714 | n/a | i = iter(l) |
---|
715 | n/a | self.assertEqual(next(i), '1') |
---|
716 | n/a | self.assertEqual(next(i), '2') |
---|
717 | n/a | self.assertRaises(StopIteration, next, i) |
---|
718 | n/a | |
---|
719 | n/a | def test_isinstance(self): |
---|
720 | n/a | class C: |
---|
721 | n/a | pass |
---|
722 | n/a | class D(C): |
---|
723 | n/a | pass |
---|
724 | n/a | class E: |
---|
725 | n/a | pass |
---|
726 | n/a | c = C() |
---|
727 | n/a | d = D() |
---|
728 | n/a | e = E() |
---|
729 | n/a | self.assertTrue(isinstance(c, C)) |
---|
730 | n/a | self.assertTrue(isinstance(d, C)) |
---|
731 | n/a | self.assertTrue(not isinstance(e, C)) |
---|
732 | n/a | self.assertTrue(not isinstance(c, D)) |
---|
733 | n/a | self.assertTrue(not isinstance('foo', E)) |
---|
734 | n/a | self.assertRaises(TypeError, isinstance, E, 'foo') |
---|
735 | n/a | self.assertRaises(TypeError, isinstance) |
---|
736 | n/a | |
---|
737 | n/a | def test_issubclass(self): |
---|
738 | n/a | class C: |
---|
739 | n/a | pass |
---|
740 | n/a | class D(C): |
---|
741 | n/a | pass |
---|
742 | n/a | class E: |
---|
743 | n/a | pass |
---|
744 | n/a | c = C() |
---|
745 | n/a | d = D() |
---|
746 | n/a | e = E() |
---|
747 | n/a | self.assertTrue(issubclass(D, C)) |
---|
748 | n/a | self.assertTrue(issubclass(C, C)) |
---|
749 | n/a | self.assertTrue(not issubclass(C, D)) |
---|
750 | n/a | self.assertRaises(TypeError, issubclass, 'foo', E) |
---|
751 | n/a | self.assertRaises(TypeError, issubclass, E, 'foo') |
---|
752 | n/a | self.assertRaises(TypeError, issubclass) |
---|
753 | n/a | |
---|
754 | n/a | def test_len(self): |
---|
755 | n/a | self.assertEqual(len('123'), 3) |
---|
756 | n/a | self.assertEqual(len(()), 0) |
---|
757 | n/a | self.assertEqual(len((1, 2, 3, 4)), 4) |
---|
758 | n/a | self.assertEqual(len([1, 2, 3, 4]), 4) |
---|
759 | n/a | self.assertEqual(len({}), 0) |
---|
760 | n/a | self.assertEqual(len({'a':1, 'b': 2}), 2) |
---|
761 | n/a | class BadSeq: |
---|
762 | n/a | def __len__(self): |
---|
763 | n/a | raise ValueError |
---|
764 | n/a | self.assertRaises(ValueError, len, BadSeq()) |
---|
765 | n/a | class InvalidLen: |
---|
766 | n/a | def __len__(self): |
---|
767 | n/a | return None |
---|
768 | n/a | self.assertRaises(TypeError, len, InvalidLen()) |
---|
769 | n/a | class FloatLen: |
---|
770 | n/a | def __len__(self): |
---|
771 | n/a | return 4.5 |
---|
772 | n/a | self.assertRaises(TypeError, len, FloatLen()) |
---|
773 | n/a | class HugeLen: |
---|
774 | n/a | def __len__(self): |
---|
775 | n/a | return sys.maxsize + 1 |
---|
776 | n/a | self.assertRaises(OverflowError, len, HugeLen()) |
---|
777 | n/a | class NoLenMethod(object): pass |
---|
778 | n/a | self.assertRaises(TypeError, len, NoLenMethod()) |
---|
779 | n/a | |
---|
780 | n/a | def test_map(self): |
---|
781 | n/a | self.assertEqual( |
---|
782 | n/a | list(map(lambda x: x*x, range(1,4))), |
---|
783 | n/a | [1, 4, 9] |
---|
784 | n/a | ) |
---|
785 | n/a | try: |
---|
786 | n/a | from math import sqrt |
---|
787 | n/a | except ImportError: |
---|
788 | n/a | def sqrt(x): |
---|
789 | n/a | return pow(x, 0.5) |
---|
790 | n/a | self.assertEqual( |
---|
791 | n/a | list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])), |
---|
792 | n/a | [[4.0, 2.0], [9.0, 3.0]] |
---|
793 | n/a | ) |
---|
794 | n/a | self.assertEqual( |
---|
795 | n/a | list(map(lambda x, y: x+y, [1,3,2], [9,1,4])), |
---|
796 | n/a | [10, 4, 6] |
---|
797 | n/a | ) |
---|
798 | n/a | |
---|
799 | n/a | def plus(*v): |
---|
800 | n/a | accu = 0 |
---|
801 | n/a | for i in v: accu = accu + i |
---|
802 | n/a | return accu |
---|
803 | n/a | self.assertEqual( |
---|
804 | n/a | list(map(plus, [1, 3, 7])), |
---|
805 | n/a | [1, 3, 7] |
---|
806 | n/a | ) |
---|
807 | n/a | self.assertEqual( |
---|
808 | n/a | list(map(plus, [1, 3, 7], [4, 9, 2])), |
---|
809 | n/a | [1+4, 3+9, 7+2] |
---|
810 | n/a | ) |
---|
811 | n/a | self.assertEqual( |
---|
812 | n/a | list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])), |
---|
813 | n/a | [1+4+1, 3+9+1, 7+2+0] |
---|
814 | n/a | ) |
---|
815 | n/a | self.assertEqual( |
---|
816 | n/a | list(map(int, Squares(10))), |
---|
817 | n/a | [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] |
---|
818 | n/a | ) |
---|
819 | n/a | def Max(a, b): |
---|
820 | n/a | if a is None: |
---|
821 | n/a | return b |
---|
822 | n/a | if b is None: |
---|
823 | n/a | return a |
---|
824 | n/a | return max(a, b) |
---|
825 | n/a | self.assertEqual( |
---|
826 | n/a | list(map(Max, Squares(3), Squares(2))), |
---|
827 | n/a | [0, 1] |
---|
828 | n/a | ) |
---|
829 | n/a | self.assertRaises(TypeError, map) |
---|
830 | n/a | self.assertRaises(TypeError, map, lambda x: x, 42) |
---|
831 | n/a | class BadSeq: |
---|
832 | n/a | def __iter__(self): |
---|
833 | n/a | raise ValueError |
---|
834 | n/a | yield None |
---|
835 | n/a | self.assertRaises(ValueError, list, map(lambda x: x, BadSeq())) |
---|
836 | n/a | def badfunc(x): |
---|
837 | n/a | raise RuntimeError |
---|
838 | n/a | self.assertRaises(RuntimeError, list, map(badfunc, range(5))) |
---|
839 | n/a | |
---|
840 | n/a | def test_map_pickle(self): |
---|
841 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
842 | n/a | m1 = map(map_char, "Is this the real life?") |
---|
843 | n/a | m2 = map(map_char, "Is this the real life?") |
---|
844 | n/a | self.check_iter_pickle(m1, list(m2), proto) |
---|
845 | n/a | |
---|
846 | n/a | def test_max(self): |
---|
847 | n/a | self.assertEqual(max('123123'), '3') |
---|
848 | n/a | self.assertEqual(max(1, 2, 3), 3) |
---|
849 | n/a | self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3) |
---|
850 | n/a | self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3) |
---|
851 | n/a | |
---|
852 | n/a | self.assertEqual(max(1, 2, 3.0), 3.0) |
---|
853 | n/a | self.assertEqual(max(1, 2.0, 3), 3) |
---|
854 | n/a | self.assertEqual(max(1.0, 2, 3), 3) |
---|
855 | n/a | |
---|
856 | n/a | self.assertRaises(TypeError, max) |
---|
857 | n/a | self.assertRaises(TypeError, max, 42) |
---|
858 | n/a | self.assertRaises(ValueError, max, ()) |
---|
859 | n/a | class BadSeq: |
---|
860 | n/a | def __getitem__(self, index): |
---|
861 | n/a | raise ValueError |
---|
862 | n/a | self.assertRaises(ValueError, max, BadSeq()) |
---|
863 | n/a | |
---|
864 | n/a | for stmt in ( |
---|
865 | n/a | "max(key=int)", # no args |
---|
866 | n/a | "max(default=None)", |
---|
867 | n/a | "max(1, 2, default=None)", # require container for default |
---|
868 | n/a | "max(default=None, key=int)", |
---|
869 | n/a | "max(1, key=int)", # single arg not iterable |
---|
870 | n/a | "max(1, 2, keystone=int)", # wrong keyword |
---|
871 | n/a | "max(1, 2, key=int, abc=int)", # two many keywords |
---|
872 | n/a | "max(1, 2, key=1)", # keyfunc is not callable |
---|
873 | n/a | ): |
---|
874 | n/a | try: |
---|
875 | n/a | exec(stmt, globals()) |
---|
876 | n/a | except TypeError: |
---|
877 | n/a | pass |
---|
878 | n/a | else: |
---|
879 | n/a | self.fail(stmt) |
---|
880 | n/a | |
---|
881 | n/a | self.assertEqual(max((1,), key=neg), 1) # one elem iterable |
---|
882 | n/a | self.assertEqual(max((1,2), key=neg), 1) # two elem iterable |
---|
883 | n/a | self.assertEqual(max(1, 2, key=neg), 1) # two elems |
---|
884 | n/a | |
---|
885 | n/a | self.assertEqual(max((), default=None), None) # zero elem iterable |
---|
886 | n/a | self.assertEqual(max((1,), default=None), 1) # one elem iterable |
---|
887 | n/a | self.assertEqual(max((1,2), default=None), 2) # two elem iterable |
---|
888 | n/a | |
---|
889 | n/a | self.assertEqual(max((), default=1, key=neg), 1) |
---|
890 | n/a | self.assertEqual(max((1, 2), default=3, key=neg), 1) |
---|
891 | n/a | |
---|
892 | n/a | data = [random.randrange(200) for i in range(100)] |
---|
893 | n/a | keys = dict((elem, random.randrange(50)) for elem in data) |
---|
894 | n/a | f = keys.__getitem__ |
---|
895 | n/a | self.assertEqual(max(data, key=f), |
---|
896 | n/a | sorted(reversed(data), key=f)[-1]) |
---|
897 | n/a | |
---|
898 | n/a | def test_min(self): |
---|
899 | n/a | self.assertEqual(min('123123'), '1') |
---|
900 | n/a | self.assertEqual(min(1, 2, 3), 1) |
---|
901 | n/a | self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1) |
---|
902 | n/a | self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1) |
---|
903 | n/a | |
---|
904 | n/a | self.assertEqual(min(1, 2, 3.0), 1) |
---|
905 | n/a | self.assertEqual(min(1, 2.0, 3), 1) |
---|
906 | n/a | self.assertEqual(min(1.0, 2, 3), 1.0) |
---|
907 | n/a | |
---|
908 | n/a | self.assertRaises(TypeError, min) |
---|
909 | n/a | self.assertRaises(TypeError, min, 42) |
---|
910 | n/a | self.assertRaises(ValueError, min, ()) |
---|
911 | n/a | class BadSeq: |
---|
912 | n/a | def __getitem__(self, index): |
---|
913 | n/a | raise ValueError |
---|
914 | n/a | self.assertRaises(ValueError, min, BadSeq()) |
---|
915 | n/a | |
---|
916 | n/a | for stmt in ( |
---|
917 | n/a | "min(key=int)", # no args |
---|
918 | n/a | "min(default=None)", |
---|
919 | n/a | "min(1, 2, default=None)", # require container for default |
---|
920 | n/a | "min(default=None, key=int)", |
---|
921 | n/a | "min(1, key=int)", # single arg not iterable |
---|
922 | n/a | "min(1, 2, keystone=int)", # wrong keyword |
---|
923 | n/a | "min(1, 2, key=int, abc=int)", # two many keywords |
---|
924 | n/a | "min(1, 2, key=1)", # keyfunc is not callable |
---|
925 | n/a | ): |
---|
926 | n/a | try: |
---|
927 | n/a | exec(stmt, globals()) |
---|
928 | n/a | except TypeError: |
---|
929 | n/a | pass |
---|
930 | n/a | else: |
---|
931 | n/a | self.fail(stmt) |
---|
932 | n/a | |
---|
933 | n/a | self.assertEqual(min((1,), key=neg), 1) # one elem iterable |
---|
934 | n/a | self.assertEqual(min((1,2), key=neg), 2) # two elem iterable |
---|
935 | n/a | self.assertEqual(min(1, 2, key=neg), 2) # two elems |
---|
936 | n/a | |
---|
937 | n/a | self.assertEqual(min((), default=None), None) # zero elem iterable |
---|
938 | n/a | self.assertEqual(min((1,), default=None), 1) # one elem iterable |
---|
939 | n/a | self.assertEqual(min((1,2), default=None), 1) # two elem iterable |
---|
940 | n/a | |
---|
941 | n/a | self.assertEqual(min((), default=1, key=neg), 1) |
---|
942 | n/a | self.assertEqual(min((1, 2), default=1, key=neg), 2) |
---|
943 | n/a | |
---|
944 | n/a | data = [random.randrange(200) for i in range(100)] |
---|
945 | n/a | keys = dict((elem, random.randrange(50)) for elem in data) |
---|
946 | n/a | f = keys.__getitem__ |
---|
947 | n/a | self.assertEqual(min(data, key=f), |
---|
948 | n/a | sorted(data, key=f)[0]) |
---|
949 | n/a | |
---|
950 | n/a | def test_next(self): |
---|
951 | n/a | it = iter(range(2)) |
---|
952 | n/a | self.assertEqual(next(it), 0) |
---|
953 | n/a | self.assertEqual(next(it), 1) |
---|
954 | n/a | self.assertRaises(StopIteration, next, it) |
---|
955 | n/a | self.assertRaises(StopIteration, next, it) |
---|
956 | n/a | self.assertEqual(next(it, 42), 42) |
---|
957 | n/a | |
---|
958 | n/a | class Iter(object): |
---|
959 | n/a | def __iter__(self): |
---|
960 | n/a | return self |
---|
961 | n/a | def __next__(self): |
---|
962 | n/a | raise StopIteration |
---|
963 | n/a | |
---|
964 | n/a | it = iter(Iter()) |
---|
965 | n/a | self.assertEqual(next(it, 42), 42) |
---|
966 | n/a | self.assertRaises(StopIteration, next, it) |
---|
967 | n/a | |
---|
968 | n/a | def gen(): |
---|
969 | n/a | yield 1 |
---|
970 | n/a | return |
---|
971 | n/a | |
---|
972 | n/a | it = gen() |
---|
973 | n/a | self.assertEqual(next(it), 1) |
---|
974 | n/a | self.assertRaises(StopIteration, next, it) |
---|
975 | n/a | self.assertEqual(next(it, 42), 42) |
---|
976 | n/a | |
---|
977 | n/a | def test_oct(self): |
---|
978 | n/a | self.assertEqual(oct(100), '0o144') |
---|
979 | n/a | self.assertEqual(oct(-100), '-0o144') |
---|
980 | n/a | self.assertRaises(TypeError, oct, ()) |
---|
981 | n/a | |
---|
982 | n/a | def write_testfile(self): |
---|
983 | n/a | # NB the first 4 lines are also used to test input, below |
---|
984 | n/a | fp = open(TESTFN, 'w') |
---|
985 | n/a | self.addCleanup(unlink, TESTFN) |
---|
986 | n/a | with fp: |
---|
987 | n/a | fp.write('1+1\n') |
---|
988 | n/a | fp.write('The quick brown fox jumps over the lazy dog') |
---|
989 | n/a | fp.write('.\n') |
---|
990 | n/a | fp.write('Dear John\n') |
---|
991 | n/a | fp.write('XXX'*100) |
---|
992 | n/a | fp.write('YYY'*100) |
---|
993 | n/a | |
---|
994 | n/a | def test_open(self): |
---|
995 | n/a | self.write_testfile() |
---|
996 | n/a | fp = open(TESTFN, 'r') |
---|
997 | n/a | with fp: |
---|
998 | n/a | self.assertEqual(fp.readline(4), '1+1\n') |
---|
999 | n/a | self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\n') |
---|
1000 | n/a | self.assertEqual(fp.readline(4), 'Dear') |
---|
1001 | n/a | self.assertEqual(fp.readline(100), ' John\n') |
---|
1002 | n/a | self.assertEqual(fp.read(300), 'XXX'*100) |
---|
1003 | n/a | self.assertEqual(fp.read(1000), 'YYY'*100) |
---|
1004 | n/a | |
---|
1005 | n/a | def test_open_default_encoding(self): |
---|
1006 | n/a | old_environ = dict(os.environ) |
---|
1007 | n/a | try: |
---|
1008 | n/a | # try to get a user preferred encoding different than the current |
---|
1009 | n/a | # locale encoding to check that open() uses the current locale |
---|
1010 | n/a | # encoding and not the user preferred encoding |
---|
1011 | n/a | for key in ('LC_ALL', 'LANG', 'LC_CTYPE'): |
---|
1012 | n/a | if key in os.environ: |
---|
1013 | n/a | del os.environ[key] |
---|
1014 | n/a | |
---|
1015 | n/a | self.write_testfile() |
---|
1016 | n/a | current_locale_encoding = locale.getpreferredencoding(False) |
---|
1017 | n/a | fp = open(TESTFN, 'w') |
---|
1018 | n/a | with fp: |
---|
1019 | n/a | self.assertEqual(fp.encoding, current_locale_encoding) |
---|
1020 | n/a | finally: |
---|
1021 | n/a | os.environ.clear() |
---|
1022 | n/a | os.environ.update(old_environ) |
---|
1023 | n/a | |
---|
1024 | n/a | def test_open_non_inheritable(self): |
---|
1025 | n/a | fileobj = open(__file__) |
---|
1026 | n/a | with fileobj: |
---|
1027 | n/a | self.assertFalse(os.get_inheritable(fileobj.fileno())) |
---|
1028 | n/a | |
---|
1029 | n/a | def test_ord(self): |
---|
1030 | n/a | self.assertEqual(ord(' '), 32) |
---|
1031 | n/a | self.assertEqual(ord('A'), 65) |
---|
1032 | n/a | self.assertEqual(ord('a'), 97) |
---|
1033 | n/a | self.assertEqual(ord('\x80'), 128) |
---|
1034 | n/a | self.assertEqual(ord('\xff'), 255) |
---|
1035 | n/a | |
---|
1036 | n/a | self.assertEqual(ord(b' '), 32) |
---|
1037 | n/a | self.assertEqual(ord(b'A'), 65) |
---|
1038 | n/a | self.assertEqual(ord(b'a'), 97) |
---|
1039 | n/a | self.assertEqual(ord(b'\x80'), 128) |
---|
1040 | n/a | self.assertEqual(ord(b'\xff'), 255) |
---|
1041 | n/a | |
---|
1042 | n/a | self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode) |
---|
1043 | n/a | self.assertRaises(TypeError, ord, 42) |
---|
1044 | n/a | |
---|
1045 | n/a | self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF) |
---|
1046 | n/a | self.assertEqual(ord("\U0000FFFF"), 0x0000FFFF) |
---|
1047 | n/a | self.assertEqual(ord("\U00010000"), 0x00010000) |
---|
1048 | n/a | self.assertEqual(ord("\U00010001"), 0x00010001) |
---|
1049 | n/a | self.assertEqual(ord("\U000FFFFE"), 0x000FFFFE) |
---|
1050 | n/a | self.assertEqual(ord("\U000FFFFF"), 0x000FFFFF) |
---|
1051 | n/a | self.assertEqual(ord("\U00100000"), 0x00100000) |
---|
1052 | n/a | self.assertEqual(ord("\U00100001"), 0x00100001) |
---|
1053 | n/a | self.assertEqual(ord("\U0010FFFE"), 0x0010FFFE) |
---|
1054 | n/a | self.assertEqual(ord("\U0010FFFF"), 0x0010FFFF) |
---|
1055 | n/a | |
---|
1056 | n/a | def test_pow(self): |
---|
1057 | n/a | self.assertEqual(pow(0,0), 1) |
---|
1058 | n/a | self.assertEqual(pow(0,1), 0) |
---|
1059 | n/a | self.assertEqual(pow(1,0), 1) |
---|
1060 | n/a | self.assertEqual(pow(1,1), 1) |
---|
1061 | n/a | |
---|
1062 | n/a | self.assertEqual(pow(2,0), 1) |
---|
1063 | n/a | self.assertEqual(pow(2,10), 1024) |
---|
1064 | n/a | self.assertEqual(pow(2,20), 1024*1024) |
---|
1065 | n/a | self.assertEqual(pow(2,30), 1024*1024*1024) |
---|
1066 | n/a | |
---|
1067 | n/a | self.assertEqual(pow(-2,0), 1) |
---|
1068 | n/a | self.assertEqual(pow(-2,1), -2) |
---|
1069 | n/a | self.assertEqual(pow(-2,2), 4) |
---|
1070 | n/a | self.assertEqual(pow(-2,3), -8) |
---|
1071 | n/a | |
---|
1072 | n/a | self.assertAlmostEqual(pow(0.,0), 1.) |
---|
1073 | n/a | self.assertAlmostEqual(pow(0.,1), 0.) |
---|
1074 | n/a | self.assertAlmostEqual(pow(1.,0), 1.) |
---|
1075 | n/a | self.assertAlmostEqual(pow(1.,1), 1.) |
---|
1076 | n/a | |
---|
1077 | n/a | self.assertAlmostEqual(pow(2.,0), 1.) |
---|
1078 | n/a | self.assertAlmostEqual(pow(2.,10), 1024.) |
---|
1079 | n/a | self.assertAlmostEqual(pow(2.,20), 1024.*1024.) |
---|
1080 | n/a | self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.) |
---|
1081 | n/a | |
---|
1082 | n/a | self.assertAlmostEqual(pow(-2.,0), 1.) |
---|
1083 | n/a | self.assertAlmostEqual(pow(-2.,1), -2.) |
---|
1084 | n/a | self.assertAlmostEqual(pow(-2.,2), 4.) |
---|
1085 | n/a | self.assertAlmostEqual(pow(-2.,3), -8.) |
---|
1086 | n/a | |
---|
1087 | n/a | for x in 2, 2.0: |
---|
1088 | n/a | for y in 10, 10.0: |
---|
1089 | n/a | for z in 1000, 1000.0: |
---|
1090 | n/a | if isinstance(x, float) or \ |
---|
1091 | n/a | isinstance(y, float) or \ |
---|
1092 | n/a | isinstance(z, float): |
---|
1093 | n/a | self.assertRaises(TypeError, pow, x, y, z) |
---|
1094 | n/a | else: |
---|
1095 | n/a | self.assertAlmostEqual(pow(x, y, z), 24.0) |
---|
1096 | n/a | |
---|
1097 | n/a | self.assertAlmostEqual(pow(-1, 0.5), 1j) |
---|
1098 | n/a | self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j) |
---|
1099 | n/a | |
---|
1100 | n/a | self.assertRaises(ValueError, pow, -1, -2, 3) |
---|
1101 | n/a | self.assertRaises(ValueError, pow, 1, 2, 0) |
---|
1102 | n/a | |
---|
1103 | n/a | self.assertRaises(TypeError, pow) |
---|
1104 | n/a | |
---|
1105 | n/a | def test_input(self): |
---|
1106 | n/a | self.write_testfile() |
---|
1107 | n/a | fp = open(TESTFN, 'r') |
---|
1108 | n/a | savestdin = sys.stdin |
---|
1109 | n/a | savestdout = sys.stdout # Eats the echo |
---|
1110 | n/a | try: |
---|
1111 | n/a | sys.stdin = fp |
---|
1112 | n/a | sys.stdout = BitBucket() |
---|
1113 | n/a | self.assertEqual(input(), "1+1") |
---|
1114 | n/a | self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.') |
---|
1115 | n/a | self.assertEqual(input('testing\n'), 'Dear John') |
---|
1116 | n/a | |
---|
1117 | n/a | # SF 1535165: don't segfault on closed stdin |
---|
1118 | n/a | # sys.stdout must be a regular file for triggering |
---|
1119 | n/a | sys.stdout = savestdout |
---|
1120 | n/a | sys.stdin.close() |
---|
1121 | n/a | self.assertRaises(ValueError, input) |
---|
1122 | n/a | |
---|
1123 | n/a | sys.stdout = BitBucket() |
---|
1124 | n/a | sys.stdin = io.StringIO("NULL\0") |
---|
1125 | n/a | self.assertRaises(TypeError, input, 42, 42) |
---|
1126 | n/a | sys.stdin = io.StringIO(" 'whitespace'") |
---|
1127 | n/a | self.assertEqual(input(), " 'whitespace'") |
---|
1128 | n/a | sys.stdin = io.StringIO() |
---|
1129 | n/a | self.assertRaises(EOFError, input) |
---|
1130 | n/a | |
---|
1131 | n/a | del sys.stdout |
---|
1132 | n/a | self.assertRaises(RuntimeError, input, 'prompt') |
---|
1133 | n/a | del sys.stdin |
---|
1134 | n/a | self.assertRaises(RuntimeError, input, 'prompt') |
---|
1135 | n/a | finally: |
---|
1136 | n/a | sys.stdin = savestdin |
---|
1137 | n/a | sys.stdout = savestdout |
---|
1138 | n/a | fp.close() |
---|
1139 | n/a | |
---|
1140 | n/a | # test_int(): see test_int.py for tests of built-in function int(). |
---|
1141 | n/a | |
---|
1142 | n/a | def test_repr(self): |
---|
1143 | n/a | self.assertEqual(repr(''), '\'\'') |
---|
1144 | n/a | self.assertEqual(repr(0), '0') |
---|
1145 | n/a | self.assertEqual(repr(()), '()') |
---|
1146 | n/a | self.assertEqual(repr([]), '[]') |
---|
1147 | n/a | self.assertEqual(repr({}), '{}') |
---|
1148 | n/a | a = [] |
---|
1149 | n/a | a.append(a) |
---|
1150 | n/a | self.assertEqual(repr(a), '[[...]]') |
---|
1151 | n/a | a = {} |
---|
1152 | n/a | a[0] = a |
---|
1153 | n/a | self.assertEqual(repr(a), '{0: {...}}') |
---|
1154 | n/a | |
---|
1155 | n/a | def test_round(self): |
---|
1156 | n/a | self.assertEqual(round(0.0), 0.0) |
---|
1157 | n/a | self.assertEqual(type(round(0.0)), int) |
---|
1158 | n/a | self.assertEqual(round(1.0), 1.0) |
---|
1159 | n/a | self.assertEqual(round(10.0), 10.0) |
---|
1160 | n/a | self.assertEqual(round(1000000000.0), 1000000000.0) |
---|
1161 | n/a | self.assertEqual(round(1e20), 1e20) |
---|
1162 | n/a | |
---|
1163 | n/a | self.assertEqual(round(-1.0), -1.0) |
---|
1164 | n/a | self.assertEqual(round(-10.0), -10.0) |
---|
1165 | n/a | self.assertEqual(round(-1000000000.0), -1000000000.0) |
---|
1166 | n/a | self.assertEqual(round(-1e20), -1e20) |
---|
1167 | n/a | |
---|
1168 | n/a | self.assertEqual(round(0.1), 0.0) |
---|
1169 | n/a | self.assertEqual(round(1.1), 1.0) |
---|
1170 | n/a | self.assertEqual(round(10.1), 10.0) |
---|
1171 | n/a | self.assertEqual(round(1000000000.1), 1000000000.0) |
---|
1172 | n/a | |
---|
1173 | n/a | self.assertEqual(round(-1.1), -1.0) |
---|
1174 | n/a | self.assertEqual(round(-10.1), -10.0) |
---|
1175 | n/a | self.assertEqual(round(-1000000000.1), -1000000000.0) |
---|
1176 | n/a | |
---|
1177 | n/a | self.assertEqual(round(0.9), 1.0) |
---|
1178 | n/a | self.assertEqual(round(9.9), 10.0) |
---|
1179 | n/a | self.assertEqual(round(999999999.9), 1000000000.0) |
---|
1180 | n/a | |
---|
1181 | n/a | self.assertEqual(round(-0.9), -1.0) |
---|
1182 | n/a | self.assertEqual(round(-9.9), -10.0) |
---|
1183 | n/a | self.assertEqual(round(-999999999.9), -1000000000.0) |
---|
1184 | n/a | |
---|
1185 | n/a | self.assertEqual(round(-8.0, -1), -10.0) |
---|
1186 | n/a | self.assertEqual(type(round(-8.0, -1)), float) |
---|
1187 | n/a | |
---|
1188 | n/a | self.assertEqual(type(round(-8.0, 0)), float) |
---|
1189 | n/a | self.assertEqual(type(round(-8.0, 1)), float) |
---|
1190 | n/a | |
---|
1191 | n/a | # Check even / odd rounding behaviour |
---|
1192 | n/a | self.assertEqual(round(5.5), 6) |
---|
1193 | n/a | self.assertEqual(round(6.5), 6) |
---|
1194 | n/a | self.assertEqual(round(-5.5), -6) |
---|
1195 | n/a | self.assertEqual(round(-6.5), -6) |
---|
1196 | n/a | |
---|
1197 | n/a | # Check behavior on ints |
---|
1198 | n/a | self.assertEqual(round(0), 0) |
---|
1199 | n/a | self.assertEqual(round(8), 8) |
---|
1200 | n/a | self.assertEqual(round(-8), -8) |
---|
1201 | n/a | self.assertEqual(type(round(0)), int) |
---|
1202 | n/a | self.assertEqual(type(round(-8, -1)), int) |
---|
1203 | n/a | self.assertEqual(type(round(-8, 0)), int) |
---|
1204 | n/a | self.assertEqual(type(round(-8, 1)), int) |
---|
1205 | n/a | |
---|
1206 | n/a | # test new kwargs |
---|
1207 | n/a | self.assertEqual(round(number=-8.0, ndigits=-1), -10.0) |
---|
1208 | n/a | |
---|
1209 | n/a | self.assertRaises(TypeError, round) |
---|
1210 | n/a | |
---|
1211 | n/a | # test generic rounding delegation for reals |
---|
1212 | n/a | class TestRound: |
---|
1213 | n/a | def __round__(self): |
---|
1214 | n/a | return 23 |
---|
1215 | n/a | |
---|
1216 | n/a | class TestNoRound: |
---|
1217 | n/a | pass |
---|
1218 | n/a | |
---|
1219 | n/a | self.assertEqual(round(TestRound()), 23) |
---|
1220 | n/a | |
---|
1221 | n/a | self.assertRaises(TypeError, round, 1, 2, 3) |
---|
1222 | n/a | self.assertRaises(TypeError, round, TestNoRound()) |
---|
1223 | n/a | |
---|
1224 | n/a | t = TestNoRound() |
---|
1225 | n/a | t.__round__ = lambda *args: args |
---|
1226 | n/a | self.assertRaises(TypeError, round, t) |
---|
1227 | n/a | self.assertRaises(TypeError, round, t, 0) |
---|
1228 | n/a | |
---|
1229 | n/a | # Some versions of glibc for alpha have a bug that affects |
---|
1230 | n/a | # float -> integer rounding (floor, ceil, rint, round) for |
---|
1231 | n/a | # values in the range [2**52, 2**53). See: |
---|
1232 | n/a | # |
---|
1233 | n/a | # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350 |
---|
1234 | n/a | # |
---|
1235 | n/a | # We skip this test on Linux/alpha if it would fail. |
---|
1236 | n/a | linux_alpha = (platform.system().startswith('Linux') and |
---|
1237 | n/a | platform.machine().startswith('alpha')) |
---|
1238 | n/a | system_round_bug = round(5e15+1) != 5e15+1 |
---|
1239 | n/a | @unittest.skipIf(linux_alpha and system_round_bug, |
---|
1240 | n/a | "test will fail; failure is probably due to a " |
---|
1241 | n/a | "buggy system round function") |
---|
1242 | n/a | def test_round_large(self): |
---|
1243 | n/a | # Issue #1869: integral floats should remain unchanged |
---|
1244 | n/a | self.assertEqual(round(5e15-1), 5e15-1) |
---|
1245 | n/a | self.assertEqual(round(5e15), 5e15) |
---|
1246 | n/a | self.assertEqual(round(5e15+1), 5e15+1) |
---|
1247 | n/a | self.assertEqual(round(5e15+2), 5e15+2) |
---|
1248 | n/a | self.assertEqual(round(5e15+3), 5e15+3) |
---|
1249 | n/a | |
---|
1250 | n/a | def test_bug_27936(self): |
---|
1251 | n/a | # Verify that ndigits=None means the same as passing in no argument |
---|
1252 | n/a | for x in [1234, |
---|
1253 | n/a | 1234.56, |
---|
1254 | n/a | decimal.Decimal('1234.56'), |
---|
1255 | n/a | fractions.Fraction(123456, 100)]: |
---|
1256 | n/a | self.assertEqual(round(x, None), round(x)) |
---|
1257 | n/a | self.assertEqual(type(round(x, None)), type(round(x))) |
---|
1258 | n/a | |
---|
1259 | n/a | def test_setattr(self): |
---|
1260 | n/a | setattr(sys, 'spam', 1) |
---|
1261 | n/a | self.assertEqual(sys.spam, 1) |
---|
1262 | n/a | self.assertRaises(TypeError, setattr, sys, 1, 'spam') |
---|
1263 | n/a | self.assertRaises(TypeError, setattr) |
---|
1264 | n/a | |
---|
1265 | n/a | # test_str(): see test_unicode.py and test_bytes.py for str() tests. |
---|
1266 | n/a | |
---|
1267 | n/a | def test_sum(self): |
---|
1268 | n/a | self.assertEqual(sum([]), 0) |
---|
1269 | n/a | self.assertEqual(sum(list(range(2,8))), 27) |
---|
1270 | n/a | self.assertEqual(sum(iter(list(range(2,8)))), 27) |
---|
1271 | n/a | self.assertEqual(sum(Squares(10)), 285) |
---|
1272 | n/a | self.assertEqual(sum(iter(Squares(10))), 285) |
---|
1273 | n/a | self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3]) |
---|
1274 | n/a | |
---|
1275 | n/a | self.assertRaises(TypeError, sum) |
---|
1276 | n/a | self.assertRaises(TypeError, sum, 42) |
---|
1277 | n/a | self.assertRaises(TypeError, sum, ['a', 'b', 'c']) |
---|
1278 | n/a | self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '') |
---|
1279 | n/a | self.assertRaises(TypeError, sum, [b'a', b'c'], b'') |
---|
1280 | n/a | values = [bytearray(b'a'), bytearray(b'b')] |
---|
1281 | n/a | self.assertRaises(TypeError, sum, values, bytearray(b'')) |
---|
1282 | n/a | self.assertRaises(TypeError, sum, [[1], [2], [3]]) |
---|
1283 | n/a | self.assertRaises(TypeError, sum, [{2:3}]) |
---|
1284 | n/a | self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3}) |
---|
1285 | n/a | |
---|
1286 | n/a | class BadSeq: |
---|
1287 | n/a | def __getitem__(self, index): |
---|
1288 | n/a | raise ValueError |
---|
1289 | n/a | self.assertRaises(ValueError, sum, BadSeq()) |
---|
1290 | n/a | |
---|
1291 | n/a | empty = [] |
---|
1292 | n/a | sum(([x] for x in range(10)), empty) |
---|
1293 | n/a | self.assertEqual(empty, []) |
---|
1294 | n/a | |
---|
1295 | n/a | def test_type(self): |
---|
1296 | n/a | self.assertEqual(type(''), type('123')) |
---|
1297 | n/a | self.assertNotEqual(type(''), type(())) |
---|
1298 | n/a | |
---|
1299 | n/a | # We don't want self in vars(), so these are static methods |
---|
1300 | n/a | |
---|
1301 | n/a | @staticmethod |
---|
1302 | n/a | def get_vars_f0(): |
---|
1303 | n/a | return vars() |
---|
1304 | n/a | |
---|
1305 | n/a | @staticmethod |
---|
1306 | n/a | def get_vars_f2(): |
---|
1307 | n/a | BuiltinTest.get_vars_f0() |
---|
1308 | n/a | a = 1 |
---|
1309 | n/a | b = 2 |
---|
1310 | n/a | return vars() |
---|
1311 | n/a | |
---|
1312 | n/a | class C_get_vars(object): |
---|
1313 | n/a | def getDict(self): |
---|
1314 | n/a | return {'a':2} |
---|
1315 | n/a | __dict__ = property(fget=getDict) |
---|
1316 | n/a | |
---|
1317 | n/a | def test_vars(self): |
---|
1318 | n/a | self.assertEqual(set(vars()), set(dir())) |
---|
1319 | n/a | self.assertEqual(set(vars(sys)), set(dir(sys))) |
---|
1320 | n/a | self.assertEqual(self.get_vars_f0(), {}) |
---|
1321 | n/a | self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2}) |
---|
1322 | n/a | self.assertRaises(TypeError, vars, 42, 42) |
---|
1323 | n/a | self.assertRaises(TypeError, vars, 42) |
---|
1324 | n/a | self.assertEqual(vars(self.C_get_vars()), {'a':2}) |
---|
1325 | n/a | |
---|
1326 | n/a | def test_zip(self): |
---|
1327 | n/a | a = (1, 2, 3) |
---|
1328 | n/a | b = (4, 5, 6) |
---|
1329 | n/a | t = [(1, 4), (2, 5), (3, 6)] |
---|
1330 | n/a | self.assertEqual(list(zip(a, b)), t) |
---|
1331 | n/a | b = [4, 5, 6] |
---|
1332 | n/a | self.assertEqual(list(zip(a, b)), t) |
---|
1333 | n/a | b = (4, 5, 6, 7) |
---|
1334 | n/a | self.assertEqual(list(zip(a, b)), t) |
---|
1335 | n/a | class I: |
---|
1336 | n/a | def __getitem__(self, i): |
---|
1337 | n/a | if i < 0 or i > 2: raise IndexError |
---|
1338 | n/a | return i + 4 |
---|
1339 | n/a | self.assertEqual(list(zip(a, I())), t) |
---|
1340 | n/a | self.assertEqual(list(zip()), []) |
---|
1341 | n/a | self.assertEqual(list(zip(*[])), []) |
---|
1342 | n/a | self.assertRaises(TypeError, zip, None) |
---|
1343 | n/a | class G: |
---|
1344 | n/a | pass |
---|
1345 | n/a | self.assertRaises(TypeError, zip, a, G()) |
---|
1346 | n/a | self.assertRaises(RuntimeError, zip, a, TestFailingIter()) |
---|
1347 | n/a | |
---|
1348 | n/a | # Make sure zip doesn't try to allocate a billion elements for the |
---|
1349 | n/a | # result list when one of its arguments doesn't say how long it is. |
---|
1350 | n/a | # A MemoryError is the most likely failure mode. |
---|
1351 | n/a | class SequenceWithoutALength: |
---|
1352 | n/a | def __getitem__(self, i): |
---|
1353 | n/a | if i == 5: |
---|
1354 | n/a | raise IndexError |
---|
1355 | n/a | else: |
---|
1356 | n/a | return i |
---|
1357 | n/a | self.assertEqual( |
---|
1358 | n/a | list(zip(SequenceWithoutALength(), range(2**30))), |
---|
1359 | n/a | list(enumerate(range(5))) |
---|
1360 | n/a | ) |
---|
1361 | n/a | |
---|
1362 | n/a | class BadSeq: |
---|
1363 | n/a | def __getitem__(self, i): |
---|
1364 | n/a | if i == 5: |
---|
1365 | n/a | raise ValueError |
---|
1366 | n/a | else: |
---|
1367 | n/a | return i |
---|
1368 | n/a | self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq())) |
---|
1369 | n/a | |
---|
1370 | n/a | def test_zip_pickle(self): |
---|
1371 | n/a | a = (1, 2, 3) |
---|
1372 | n/a | b = (4, 5, 6) |
---|
1373 | n/a | t = [(1, 4), (2, 5), (3, 6)] |
---|
1374 | n/a | for proto in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1375 | n/a | z1 = zip(a, b) |
---|
1376 | n/a | self.check_iter_pickle(z1, t, proto) |
---|
1377 | n/a | |
---|
1378 | n/a | def test_format(self): |
---|
1379 | n/a | # Test the basic machinery of the format() builtin. Don't test |
---|
1380 | n/a | # the specifics of the various formatters |
---|
1381 | n/a | self.assertEqual(format(3, ''), '3') |
---|
1382 | n/a | |
---|
1383 | n/a | # Returns some classes to use for various tests. There's |
---|
1384 | n/a | # an old-style version, and a new-style version |
---|
1385 | n/a | def classes_new(): |
---|
1386 | n/a | class A(object): |
---|
1387 | n/a | def __init__(self, x): |
---|
1388 | n/a | self.x = x |
---|
1389 | n/a | def __format__(self, format_spec): |
---|
1390 | n/a | return str(self.x) + format_spec |
---|
1391 | n/a | class DerivedFromA(A): |
---|
1392 | n/a | pass |
---|
1393 | n/a | |
---|
1394 | n/a | class Simple(object): pass |
---|
1395 | n/a | class DerivedFromSimple(Simple): |
---|
1396 | n/a | def __init__(self, x): |
---|
1397 | n/a | self.x = x |
---|
1398 | n/a | def __format__(self, format_spec): |
---|
1399 | n/a | return str(self.x) + format_spec |
---|
1400 | n/a | class DerivedFromSimple2(DerivedFromSimple): pass |
---|
1401 | n/a | return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2 |
---|
1402 | n/a | |
---|
1403 | n/a | def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2): |
---|
1404 | n/a | self.assertEqual(format(A(3), 'spec'), '3spec') |
---|
1405 | n/a | self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec') |
---|
1406 | n/a | self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc') |
---|
1407 | n/a | self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'), |
---|
1408 | n/a | '10abcdef') |
---|
1409 | n/a | |
---|
1410 | n/a | class_test(*classes_new()) |
---|
1411 | n/a | |
---|
1412 | n/a | def empty_format_spec(value): |
---|
1413 | n/a | # test that: |
---|
1414 | n/a | # format(x, '') == str(x) |
---|
1415 | n/a | # format(x) == str(x) |
---|
1416 | n/a | self.assertEqual(format(value, ""), str(value)) |
---|
1417 | n/a | self.assertEqual(format(value), str(value)) |
---|
1418 | n/a | |
---|
1419 | n/a | # for builtin types, format(x, "") == str(x) |
---|
1420 | n/a | empty_format_spec(17**13) |
---|
1421 | n/a | empty_format_spec(1.0) |
---|
1422 | n/a | empty_format_spec(3.1415e104) |
---|
1423 | n/a | empty_format_spec(-3.1415e104) |
---|
1424 | n/a | empty_format_spec(3.1415e-104) |
---|
1425 | n/a | empty_format_spec(-3.1415e-104) |
---|
1426 | n/a | empty_format_spec(object) |
---|
1427 | n/a | empty_format_spec(None) |
---|
1428 | n/a | |
---|
1429 | n/a | # TypeError because self.__format__ returns the wrong type |
---|
1430 | n/a | class BadFormatResult: |
---|
1431 | n/a | def __format__(self, format_spec): |
---|
1432 | n/a | return 1.0 |
---|
1433 | n/a | self.assertRaises(TypeError, format, BadFormatResult(), "") |
---|
1434 | n/a | |
---|
1435 | n/a | # TypeError because format_spec is not unicode or str |
---|
1436 | n/a | self.assertRaises(TypeError, format, object(), 4) |
---|
1437 | n/a | self.assertRaises(TypeError, format, object(), object()) |
---|
1438 | n/a | |
---|
1439 | n/a | # tests for object.__format__ really belong elsewhere, but |
---|
1440 | n/a | # there's no good place to put them |
---|
1441 | n/a | x = object().__format__('') |
---|
1442 | n/a | self.assertTrue(x.startswith('<object object at')) |
---|
1443 | n/a | |
---|
1444 | n/a | # first argument to object.__format__ must be string |
---|
1445 | n/a | self.assertRaises(TypeError, object().__format__, 3) |
---|
1446 | n/a | self.assertRaises(TypeError, object().__format__, object()) |
---|
1447 | n/a | self.assertRaises(TypeError, object().__format__, None) |
---|
1448 | n/a | |
---|
1449 | n/a | # -------------------------------------------------------------------- |
---|
1450 | n/a | # Issue #7994: object.__format__ with a non-empty format string is |
---|
1451 | n/a | # disallowed |
---|
1452 | n/a | class A: |
---|
1453 | n/a | def __format__(self, fmt_str): |
---|
1454 | n/a | return format('', fmt_str) |
---|
1455 | n/a | |
---|
1456 | n/a | self.assertEqual(format(A()), '') |
---|
1457 | n/a | self.assertEqual(format(A(), ''), '') |
---|
1458 | n/a | self.assertEqual(format(A(), 's'), '') |
---|
1459 | n/a | |
---|
1460 | n/a | class B: |
---|
1461 | n/a | pass |
---|
1462 | n/a | |
---|
1463 | n/a | class C(object): |
---|
1464 | n/a | pass |
---|
1465 | n/a | |
---|
1466 | n/a | for cls in [object, B, C]: |
---|
1467 | n/a | obj = cls() |
---|
1468 | n/a | self.assertEqual(format(obj), str(obj)) |
---|
1469 | n/a | self.assertEqual(format(obj, ''), str(obj)) |
---|
1470 | n/a | with self.assertRaisesRegex(TypeError, |
---|
1471 | n/a | r'\b%s\b' % re.escape(cls.__name__)): |
---|
1472 | n/a | format(obj, 's') |
---|
1473 | n/a | # -------------------------------------------------------------------- |
---|
1474 | n/a | |
---|
1475 | n/a | # make sure we can take a subclass of str as a format spec |
---|
1476 | n/a | class DerivedFromStr(str): pass |
---|
1477 | n/a | self.assertEqual(format(0, DerivedFromStr('10')), ' 0') |
---|
1478 | n/a | |
---|
1479 | n/a | def test_bin(self): |
---|
1480 | n/a | self.assertEqual(bin(0), '0b0') |
---|
1481 | n/a | self.assertEqual(bin(1), '0b1') |
---|
1482 | n/a | self.assertEqual(bin(-1), '-0b1') |
---|
1483 | n/a | self.assertEqual(bin(2**65), '0b1' + '0' * 65) |
---|
1484 | n/a | self.assertEqual(bin(2**65-1), '0b' + '1' * 65) |
---|
1485 | n/a | self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65) |
---|
1486 | n/a | self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65) |
---|
1487 | n/a | |
---|
1488 | n/a | def test_bytearray_translate(self): |
---|
1489 | n/a | x = bytearray(b"abc") |
---|
1490 | n/a | self.assertRaises(ValueError, x.translate, b"1", 1) |
---|
1491 | n/a | self.assertRaises(TypeError, x.translate, b"1"*256, 1) |
---|
1492 | n/a | |
---|
1493 | n/a | def test_construct_singletons(self): |
---|
1494 | n/a | for const in None, Ellipsis, NotImplemented: |
---|
1495 | n/a | tp = type(const) |
---|
1496 | n/a | self.assertIs(tp(), const) |
---|
1497 | n/a | self.assertRaises(TypeError, tp, 1, 2) |
---|
1498 | n/a | self.assertRaises(TypeError, tp, a=1, b=2) |
---|
1499 | n/a | |
---|
1500 | n/a | @unittest.skipUnless(pty, "the pty and signal modules must be available") |
---|
1501 | n/a | class PtyTests(unittest.TestCase): |
---|
1502 | n/a | """Tests that use a pseudo terminal to guarantee stdin and stdout are |
---|
1503 | n/a | terminals in the test environment""" |
---|
1504 | n/a | |
---|
1505 | n/a | def run_child(self, child, terminal_input): |
---|
1506 | n/a | r, w = os.pipe() # Pipe test results from child back to parent |
---|
1507 | n/a | try: |
---|
1508 | n/a | pid, fd = pty.fork() |
---|
1509 | n/a | except (OSError, AttributeError) as e: |
---|
1510 | n/a | os.close(r) |
---|
1511 | n/a | os.close(w) |
---|
1512 | n/a | self.skipTest("pty.fork() raised {}".format(e)) |
---|
1513 | n/a | raise |
---|
1514 | n/a | if pid == 0: |
---|
1515 | n/a | # Child |
---|
1516 | n/a | try: |
---|
1517 | n/a | # Make sure we don't get stuck if there's a problem |
---|
1518 | n/a | signal.alarm(2) |
---|
1519 | n/a | os.close(r) |
---|
1520 | n/a | with open(w, "w") as wpipe: |
---|
1521 | n/a | child(wpipe) |
---|
1522 | n/a | except: |
---|
1523 | n/a | traceback.print_exc() |
---|
1524 | n/a | finally: |
---|
1525 | n/a | # We don't want to return to unittest... |
---|
1526 | n/a | os._exit(0) |
---|
1527 | n/a | # Parent |
---|
1528 | n/a | os.close(w) |
---|
1529 | n/a | os.write(fd, terminal_input) |
---|
1530 | n/a | # Get results from the pipe |
---|
1531 | n/a | with open(r, "r") as rpipe: |
---|
1532 | n/a | lines = [] |
---|
1533 | n/a | while True: |
---|
1534 | n/a | line = rpipe.readline().strip() |
---|
1535 | n/a | if line == "": |
---|
1536 | n/a | # The other end was closed => the child exited |
---|
1537 | n/a | break |
---|
1538 | n/a | lines.append(line) |
---|
1539 | n/a | # Check the result was got and corresponds to the user's terminal input |
---|
1540 | n/a | if len(lines) != 2: |
---|
1541 | n/a | # Something went wrong, try to get at stderr |
---|
1542 | n/a | # Beware of Linux raising EIO when the slave is closed |
---|
1543 | n/a | child_output = bytearray() |
---|
1544 | n/a | while True: |
---|
1545 | n/a | try: |
---|
1546 | n/a | chunk = os.read(fd, 3000) |
---|
1547 | n/a | except OSError: # Assume EIO |
---|
1548 | n/a | break |
---|
1549 | n/a | if not chunk: |
---|
1550 | n/a | break |
---|
1551 | n/a | child_output.extend(chunk) |
---|
1552 | n/a | os.close(fd) |
---|
1553 | n/a | child_output = child_output.decode("ascii", "ignore") |
---|
1554 | n/a | self.fail("got %d lines in pipe but expected 2, child output was:\n%s" |
---|
1555 | n/a | % (len(lines), child_output)) |
---|
1556 | n/a | os.close(fd) |
---|
1557 | n/a | return lines |
---|
1558 | n/a | |
---|
1559 | n/a | def check_input_tty(self, prompt, terminal_input, stdio_encoding=None): |
---|
1560 | n/a | if not sys.stdin.isatty() or not sys.stdout.isatty(): |
---|
1561 | n/a | self.skipTest("stdin and stdout must be ttys") |
---|
1562 | n/a | def child(wpipe): |
---|
1563 | n/a | # Check the error handlers are accounted for |
---|
1564 | n/a | if stdio_encoding: |
---|
1565 | n/a | sys.stdin = io.TextIOWrapper(sys.stdin.detach(), |
---|
1566 | n/a | encoding=stdio_encoding, |
---|
1567 | n/a | errors='surrogateescape') |
---|
1568 | n/a | sys.stdout = io.TextIOWrapper(sys.stdout.detach(), |
---|
1569 | n/a | encoding=stdio_encoding, |
---|
1570 | n/a | errors='replace') |
---|
1571 | n/a | print("tty =", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe) |
---|
1572 | n/a | print(ascii(input(prompt)), file=wpipe) |
---|
1573 | n/a | lines = self.run_child(child, terminal_input + b"\r\n") |
---|
1574 | n/a | # Check we did exercise the GNU readline path |
---|
1575 | n/a | self.assertIn(lines[0], {'tty = True', 'tty = False'}) |
---|
1576 | n/a | if lines[0] != 'tty = True': |
---|
1577 | n/a | self.skipTest("standard IO in should have been a tty") |
---|
1578 | n/a | input_result = eval(lines[1]) # ascii() -> eval() roundtrip |
---|
1579 | n/a | if stdio_encoding: |
---|
1580 | n/a | expected = terminal_input.decode(stdio_encoding, 'surrogateescape') |
---|
1581 | n/a | else: |
---|
1582 | n/a | expected = terminal_input.decode(sys.stdin.encoding) # what else? |
---|
1583 | n/a | self.assertEqual(input_result, expected) |
---|
1584 | n/a | |
---|
1585 | n/a | def test_input_tty(self): |
---|
1586 | n/a | # Test input() functionality when wired to a tty (the code path |
---|
1587 | n/a | # is different and invokes GNU readline if available). |
---|
1588 | n/a | self.check_input_tty("prompt", b"quux") |
---|
1589 | n/a | |
---|
1590 | n/a | def test_input_tty_non_ascii(self): |
---|
1591 | n/a | # Check stdin/stdout encoding is used when invoking GNU readline |
---|
1592 | n/a | self.check_input_tty("prompté", b"quux\xe9", "utf-8") |
---|
1593 | n/a | |
---|
1594 | n/a | def test_input_tty_non_ascii_unicode_errors(self): |
---|
1595 | n/a | # Check stdin/stdout error handler is used when invoking GNU readline |
---|
1596 | n/a | self.check_input_tty("prompté", b"quux\xe9", "ascii") |
---|
1597 | n/a | |
---|
1598 | n/a | def test_input_no_stdout_fileno(self): |
---|
1599 | n/a | # Issue #24402: If stdin is the original terminal but stdout.fileno() |
---|
1600 | n/a | # fails, do not use the original stdout file descriptor |
---|
1601 | n/a | def child(wpipe): |
---|
1602 | n/a | print("stdin.isatty():", sys.stdin.isatty(), file=wpipe) |
---|
1603 | n/a | sys.stdout = io.StringIO() # Does not support fileno() |
---|
1604 | n/a | input("prompt") |
---|
1605 | n/a | print("captured:", ascii(sys.stdout.getvalue()), file=wpipe) |
---|
1606 | n/a | lines = self.run_child(child, b"quux\r") |
---|
1607 | n/a | expected = ( |
---|
1608 | n/a | "stdin.isatty(): True", |
---|
1609 | n/a | "captured: 'prompt'", |
---|
1610 | n/a | ) |
---|
1611 | n/a | self.assertSequenceEqual(lines, expected) |
---|
1612 | n/a | |
---|
1613 | n/a | class TestSorted(unittest.TestCase): |
---|
1614 | n/a | |
---|
1615 | n/a | def test_basic(self): |
---|
1616 | n/a | data = list(range(100)) |
---|
1617 | n/a | copy = data[:] |
---|
1618 | n/a | random.shuffle(copy) |
---|
1619 | n/a | self.assertEqual(data, sorted(copy)) |
---|
1620 | n/a | self.assertNotEqual(data, copy) |
---|
1621 | n/a | |
---|
1622 | n/a | data.reverse() |
---|
1623 | n/a | random.shuffle(copy) |
---|
1624 | n/a | self.assertEqual(data, sorted(copy, key=lambda x: -x)) |
---|
1625 | n/a | self.assertNotEqual(data, copy) |
---|
1626 | n/a | random.shuffle(copy) |
---|
1627 | n/a | self.assertEqual(data, sorted(copy, reverse=1)) |
---|
1628 | n/a | self.assertNotEqual(data, copy) |
---|
1629 | n/a | |
---|
1630 | n/a | def test_bad_arguments(self): |
---|
1631 | n/a | # Issue #29327: The first argument is positional-only. |
---|
1632 | n/a | sorted([]) |
---|
1633 | n/a | with self.assertRaises(TypeError): |
---|
1634 | n/a | sorted(iterable=[]) |
---|
1635 | n/a | # Other arguments are keyword-only |
---|
1636 | n/a | sorted([], key=None) |
---|
1637 | n/a | with self.assertRaises(TypeError): |
---|
1638 | n/a | sorted([], None) |
---|
1639 | n/a | |
---|
1640 | n/a | def test_inputtypes(self): |
---|
1641 | n/a | s = 'abracadabra' |
---|
1642 | n/a | types = [list, tuple, str] |
---|
1643 | n/a | for T in types: |
---|
1644 | n/a | self.assertEqual(sorted(s), sorted(T(s))) |
---|
1645 | n/a | |
---|
1646 | n/a | s = ''.join(set(s)) # unique letters only |
---|
1647 | n/a | types = [str, set, frozenset, list, tuple, dict.fromkeys] |
---|
1648 | n/a | for T in types: |
---|
1649 | n/a | self.assertEqual(sorted(s), sorted(T(s))) |
---|
1650 | n/a | |
---|
1651 | n/a | def test_baddecorator(self): |
---|
1652 | n/a | data = 'The quick Brown fox Jumped over The lazy Dog'.split() |
---|
1653 | n/a | self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0) |
---|
1654 | n/a | |
---|
1655 | n/a | |
---|
1656 | n/a | class ShutdownTest(unittest.TestCase): |
---|
1657 | n/a | |
---|
1658 | n/a | def test_cleanup(self): |
---|
1659 | n/a | # Issue #19255: builtins are still available at shutdown |
---|
1660 | n/a | code = """if 1: |
---|
1661 | n/a | import builtins |
---|
1662 | n/a | import sys |
---|
1663 | n/a | |
---|
1664 | n/a | class C: |
---|
1665 | n/a | def __del__(self): |
---|
1666 | n/a | print("before") |
---|
1667 | n/a | # Check that builtins still exist |
---|
1668 | n/a | len(()) |
---|
1669 | n/a | print("after") |
---|
1670 | n/a | |
---|
1671 | n/a | c = C() |
---|
1672 | n/a | # Make this module survive until builtins and sys are cleaned |
---|
1673 | n/a | builtins.here = sys.modules[__name__] |
---|
1674 | n/a | sys.here = sys.modules[__name__] |
---|
1675 | n/a | # Create a reference loop so that this module needs to go |
---|
1676 | n/a | # through a GC phase. |
---|
1677 | n/a | here = sys.modules[__name__] |
---|
1678 | n/a | """ |
---|
1679 | n/a | # Issue #20599: Force ASCII encoding to get a codec implemented in C, |
---|
1680 | n/a | # otherwise the codec may be unloaded before C.__del__() is called, and |
---|
1681 | n/a | # so print("before") fails because the codec cannot be used to encode |
---|
1682 | n/a | # "before" to sys.stdout.encoding. For example, on Windows, |
---|
1683 | n/a | # sys.stdout.encoding is the OEM code page and these code pages are |
---|
1684 | n/a | # implemented in Python |
---|
1685 | n/a | rc, out, err = assert_python_ok("-c", code, |
---|
1686 | n/a | PYTHONIOENCODING="ascii") |
---|
1687 | n/a | self.assertEqual(["before", "after"], out.decode().splitlines()) |
---|
1688 | n/a | |
---|
1689 | n/a | |
---|
1690 | n/a | class TestType(unittest.TestCase): |
---|
1691 | n/a | def test_new_type(self): |
---|
1692 | n/a | A = type('A', (), {}) |
---|
1693 | n/a | self.assertEqual(A.__name__, 'A') |
---|
1694 | n/a | self.assertEqual(A.__qualname__, 'A') |
---|
1695 | n/a | self.assertEqual(A.__module__, __name__) |
---|
1696 | n/a | self.assertEqual(A.__bases__, (object,)) |
---|
1697 | n/a | self.assertIs(A.__base__, object) |
---|
1698 | n/a | x = A() |
---|
1699 | n/a | self.assertIs(type(x), A) |
---|
1700 | n/a | self.assertIs(x.__class__, A) |
---|
1701 | n/a | |
---|
1702 | n/a | class B: |
---|
1703 | n/a | def ham(self): |
---|
1704 | n/a | return 'ham%d' % self |
---|
1705 | n/a | C = type('C', (B, int), {'spam': lambda self: 'spam%s' % self}) |
---|
1706 | n/a | self.assertEqual(C.__name__, 'C') |
---|
1707 | n/a | self.assertEqual(C.__qualname__, 'C') |
---|
1708 | n/a | self.assertEqual(C.__module__, __name__) |
---|
1709 | n/a | self.assertEqual(C.__bases__, (B, int)) |
---|
1710 | n/a | self.assertIs(C.__base__, int) |
---|
1711 | n/a | self.assertIn('spam', C.__dict__) |
---|
1712 | n/a | self.assertNotIn('ham', C.__dict__) |
---|
1713 | n/a | x = C(42) |
---|
1714 | n/a | self.assertEqual(x, 42) |
---|
1715 | n/a | self.assertIs(type(x), C) |
---|
1716 | n/a | self.assertIs(x.__class__, C) |
---|
1717 | n/a | self.assertEqual(x.ham(), 'ham42') |
---|
1718 | n/a | self.assertEqual(x.spam(), 'spam42') |
---|
1719 | n/a | self.assertEqual(x.to_bytes(2, 'little'), b'\x2a\x00') |
---|
1720 | n/a | |
---|
1721 | n/a | def test_type_nokwargs(self): |
---|
1722 | n/a | with self.assertRaises(TypeError): |
---|
1723 | n/a | type('a', (), {}, x=5) |
---|
1724 | n/a | with self.assertRaises(TypeError): |
---|
1725 | n/a | type('a', (), dict={}) |
---|
1726 | n/a | |
---|
1727 | n/a | def test_type_name(self): |
---|
1728 | n/a | for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '': |
---|
1729 | n/a | with self.subTest(name=name): |
---|
1730 | n/a | A = type(name, (), {}) |
---|
1731 | n/a | self.assertEqual(A.__name__, name) |
---|
1732 | n/a | self.assertEqual(A.__qualname__, name) |
---|
1733 | n/a | self.assertEqual(A.__module__, __name__) |
---|
1734 | n/a | with self.assertRaises(ValueError): |
---|
1735 | n/a | type('A\x00B', (), {}) |
---|
1736 | n/a | with self.assertRaises(ValueError): |
---|
1737 | n/a | type('A\udcdcB', (), {}) |
---|
1738 | n/a | with self.assertRaises(TypeError): |
---|
1739 | n/a | type(b'A', (), {}) |
---|
1740 | n/a | |
---|
1741 | n/a | C = type('C', (), {}) |
---|
1742 | n/a | for name in 'A', '\xc4', '\U0001f40d', 'B.A', '42', '': |
---|
1743 | n/a | with self.subTest(name=name): |
---|
1744 | n/a | C.__name__ = name |
---|
1745 | n/a | self.assertEqual(C.__name__, name) |
---|
1746 | n/a | self.assertEqual(C.__qualname__, 'C') |
---|
1747 | n/a | self.assertEqual(C.__module__, __name__) |
---|
1748 | n/a | |
---|
1749 | n/a | A = type('C', (), {}) |
---|
1750 | n/a | with self.assertRaises(ValueError): |
---|
1751 | n/a | A.__name__ = 'A\x00B' |
---|
1752 | n/a | self.assertEqual(A.__name__, 'C') |
---|
1753 | n/a | with self.assertRaises(ValueError): |
---|
1754 | n/a | A.__name__ = 'A\udcdcB' |
---|
1755 | n/a | self.assertEqual(A.__name__, 'C') |
---|
1756 | n/a | with self.assertRaises(TypeError): |
---|
1757 | n/a | A.__name__ = b'A' |
---|
1758 | n/a | self.assertEqual(A.__name__, 'C') |
---|
1759 | n/a | |
---|
1760 | n/a | def test_type_qualname(self): |
---|
1761 | n/a | A = type('A', (), {'__qualname__': 'B.C'}) |
---|
1762 | n/a | self.assertEqual(A.__name__, 'A') |
---|
1763 | n/a | self.assertEqual(A.__qualname__, 'B.C') |
---|
1764 | n/a | self.assertEqual(A.__module__, __name__) |
---|
1765 | n/a | with self.assertRaises(TypeError): |
---|
1766 | n/a | type('A', (), {'__qualname__': b'B'}) |
---|
1767 | n/a | self.assertEqual(A.__qualname__, 'B.C') |
---|
1768 | n/a | |
---|
1769 | n/a | A.__qualname__ = 'D.E' |
---|
1770 | n/a | self.assertEqual(A.__name__, 'A') |
---|
1771 | n/a | self.assertEqual(A.__qualname__, 'D.E') |
---|
1772 | n/a | with self.assertRaises(TypeError): |
---|
1773 | n/a | A.__qualname__ = b'B' |
---|
1774 | n/a | self.assertEqual(A.__qualname__, 'D.E') |
---|
1775 | n/a | |
---|
1776 | n/a | def test_type_doc(self): |
---|
1777 | n/a | for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', b'x', 42, None: |
---|
1778 | n/a | A = type('A', (), {'__doc__': doc}) |
---|
1779 | n/a | self.assertEqual(A.__doc__, doc) |
---|
1780 | n/a | with self.assertRaises(UnicodeEncodeError): |
---|
1781 | n/a | type('A', (), {'__doc__': 'x\udcdcy'}) |
---|
1782 | n/a | |
---|
1783 | n/a | A = type('A', (), {}) |
---|
1784 | n/a | self.assertEqual(A.__doc__, None) |
---|
1785 | n/a | for doc in 'x', '\xc4', '\U0001f40d', 'x\x00y', 'x\udcdcy', b'x', 42, None: |
---|
1786 | n/a | A.__doc__ = doc |
---|
1787 | n/a | self.assertEqual(A.__doc__, doc) |
---|
1788 | n/a | |
---|
1789 | n/a | def test_bad_args(self): |
---|
1790 | n/a | with self.assertRaises(TypeError): |
---|
1791 | n/a | type() |
---|
1792 | n/a | with self.assertRaises(TypeError): |
---|
1793 | n/a | type('A', ()) |
---|
1794 | n/a | with self.assertRaises(TypeError): |
---|
1795 | n/a | type('A', (), {}, ()) |
---|
1796 | n/a | with self.assertRaises(TypeError): |
---|
1797 | n/a | type('A', (), dict={}) |
---|
1798 | n/a | with self.assertRaises(TypeError): |
---|
1799 | n/a | type('A', [], {}) |
---|
1800 | n/a | with self.assertRaises(TypeError): |
---|
1801 | n/a | type('A', (), types.MappingProxyType({})) |
---|
1802 | n/a | with self.assertRaises(TypeError): |
---|
1803 | n/a | type('A', (None,), {}) |
---|
1804 | n/a | with self.assertRaises(TypeError): |
---|
1805 | n/a | type('A', (bool,), {}) |
---|
1806 | n/a | with self.assertRaises(TypeError): |
---|
1807 | n/a | type('A', (int, str), {}) |
---|
1808 | n/a | |
---|
1809 | n/a | def test_bad_slots(self): |
---|
1810 | n/a | with self.assertRaises(TypeError): |
---|
1811 | n/a | type('A', (), {'__slots__': b'x'}) |
---|
1812 | n/a | with self.assertRaises(TypeError): |
---|
1813 | n/a | type('A', (int,), {'__slots__': 'x'}) |
---|
1814 | n/a | with self.assertRaises(TypeError): |
---|
1815 | n/a | type('A', (), {'__slots__': ''}) |
---|
1816 | n/a | with self.assertRaises(TypeError): |
---|
1817 | n/a | type('A', (), {'__slots__': '42'}) |
---|
1818 | n/a | with self.assertRaises(TypeError): |
---|
1819 | n/a | type('A', (), {'__slots__': 'x\x00y'}) |
---|
1820 | n/a | with self.assertRaises(ValueError): |
---|
1821 | n/a | type('A', (), {'__slots__': 'x', 'x': 0}) |
---|
1822 | n/a | with self.assertRaises(TypeError): |
---|
1823 | n/a | type('A', (), {'__slots__': ('__dict__', '__dict__')}) |
---|
1824 | n/a | with self.assertRaises(TypeError): |
---|
1825 | n/a | type('A', (), {'__slots__': ('__weakref__', '__weakref__')}) |
---|
1826 | n/a | |
---|
1827 | n/a | class B: |
---|
1828 | n/a | pass |
---|
1829 | n/a | with self.assertRaises(TypeError): |
---|
1830 | n/a | type('A', (B,), {'__slots__': '__dict__'}) |
---|
1831 | n/a | with self.assertRaises(TypeError): |
---|
1832 | n/a | type('A', (B,), {'__slots__': '__weakref__'}) |
---|
1833 | n/a | |
---|
1834 | n/a | |
---|
1835 | n/a | def load_tests(loader, tests, pattern): |
---|
1836 | n/a | from doctest import DocTestSuite |
---|
1837 | n/a | tests.addTest(DocTestSuite(builtins)) |
---|
1838 | n/a | return tests |
---|
1839 | n/a | |
---|
1840 | n/a | if __name__ == "__main__": |
---|
1841 | n/a | unittest.main() |
---|