1 | n/a | # Python test set -- part 6, built-in types |
---|
2 | n/a | |
---|
3 | n/a | from test.support import run_with_locale |
---|
4 | n/a | import collections.abc |
---|
5 | n/a | import inspect |
---|
6 | n/a | import pickle |
---|
7 | n/a | import locale |
---|
8 | n/a | import sys |
---|
9 | n/a | import types |
---|
10 | n/a | import unittest.mock |
---|
11 | n/a | import weakref |
---|
12 | n/a | |
---|
13 | n/a | class TypesTests(unittest.TestCase): |
---|
14 | n/a | |
---|
15 | n/a | def test_truth_values(self): |
---|
16 | n/a | if None: self.fail('None is true instead of false') |
---|
17 | n/a | if 0: self.fail('0 is true instead of false') |
---|
18 | n/a | if 0.0: self.fail('0.0 is true instead of false') |
---|
19 | n/a | if '': self.fail('\'\' is true instead of false') |
---|
20 | n/a | if not 1: self.fail('1 is false instead of true') |
---|
21 | n/a | if not 1.0: self.fail('1.0 is false instead of true') |
---|
22 | n/a | if not 'x': self.fail('\'x\' is false instead of true') |
---|
23 | n/a | if not {'x': 1}: self.fail('{\'x\': 1} is false instead of true') |
---|
24 | n/a | def f(): pass |
---|
25 | n/a | class C: pass |
---|
26 | n/a | x = C() |
---|
27 | n/a | if not f: self.fail('f is false instead of true') |
---|
28 | n/a | if not C: self.fail('C is false instead of true') |
---|
29 | n/a | if not sys: self.fail('sys is false instead of true') |
---|
30 | n/a | if not x: self.fail('x is false instead of true') |
---|
31 | n/a | |
---|
32 | n/a | def test_boolean_ops(self): |
---|
33 | n/a | if 0 or 0: self.fail('0 or 0 is true instead of false') |
---|
34 | n/a | if 1 and 1: pass |
---|
35 | n/a | else: self.fail('1 and 1 is false instead of true') |
---|
36 | n/a | if not 1: self.fail('not 1 is true instead of false') |
---|
37 | n/a | |
---|
38 | n/a | def test_comparisons(self): |
---|
39 | n/a | if 0 < 1 <= 1 == 1 >= 1 > 0 != 1: pass |
---|
40 | n/a | else: self.fail('int comparisons failed') |
---|
41 | n/a | if 0.0 < 1.0 <= 1.0 == 1.0 >= 1.0 > 0.0 != 1.0: pass |
---|
42 | n/a | else: self.fail('float comparisons failed') |
---|
43 | n/a | if '' < 'a' <= 'a' == 'a' < 'abc' < 'abd' < 'b': pass |
---|
44 | n/a | else: self.fail('string comparisons failed') |
---|
45 | n/a | if None is None: pass |
---|
46 | n/a | else: self.fail('identity test failed') |
---|
47 | n/a | |
---|
48 | n/a | def test_float_constructor(self): |
---|
49 | n/a | self.assertRaises(ValueError, float, '') |
---|
50 | n/a | self.assertRaises(ValueError, float, '5\0') |
---|
51 | n/a | self.assertRaises(ValueError, float, '5_5\0') |
---|
52 | n/a | |
---|
53 | n/a | def test_zero_division(self): |
---|
54 | n/a | try: 5.0 / 0.0 |
---|
55 | n/a | except ZeroDivisionError: pass |
---|
56 | n/a | else: self.fail("5.0 / 0.0 didn't raise ZeroDivisionError") |
---|
57 | n/a | |
---|
58 | n/a | try: 5.0 // 0.0 |
---|
59 | n/a | except ZeroDivisionError: pass |
---|
60 | n/a | else: self.fail("5.0 // 0.0 didn't raise ZeroDivisionError") |
---|
61 | n/a | |
---|
62 | n/a | try: 5.0 % 0.0 |
---|
63 | n/a | except ZeroDivisionError: pass |
---|
64 | n/a | else: self.fail("5.0 % 0.0 didn't raise ZeroDivisionError") |
---|
65 | n/a | |
---|
66 | n/a | try: 5 / 0 |
---|
67 | n/a | except ZeroDivisionError: pass |
---|
68 | n/a | else: self.fail("5 / 0 didn't raise ZeroDivisionError") |
---|
69 | n/a | |
---|
70 | n/a | try: 5 // 0 |
---|
71 | n/a | except ZeroDivisionError: pass |
---|
72 | n/a | else: self.fail("5 // 0 didn't raise ZeroDivisionError") |
---|
73 | n/a | |
---|
74 | n/a | try: 5 % 0 |
---|
75 | n/a | except ZeroDivisionError: pass |
---|
76 | n/a | else: self.fail("5 % 0 didn't raise ZeroDivisionError") |
---|
77 | n/a | |
---|
78 | n/a | def test_numeric_types(self): |
---|
79 | n/a | if 0 != 0.0 or 1 != 1.0 or -1 != -1.0: |
---|
80 | n/a | self.fail('int/float value not equal') |
---|
81 | n/a | # calling built-in types without argument must return 0 |
---|
82 | n/a | if int() != 0: self.fail('int() does not return 0') |
---|
83 | n/a | if float() != 0.0: self.fail('float() does not return 0.0') |
---|
84 | n/a | if int(1.9) == 1 == int(1.1) and int(-1.1) == -1 == int(-1.9): pass |
---|
85 | n/a | else: self.fail('int() does not round properly') |
---|
86 | n/a | if float(1) == 1.0 and float(-1) == -1.0 and float(0) == 0.0: pass |
---|
87 | n/a | else: self.fail('float() does not work properly') |
---|
88 | n/a | |
---|
89 | n/a | def test_float_to_string(self): |
---|
90 | n/a | def test(f, result): |
---|
91 | n/a | self.assertEqual(f.__format__('e'), result) |
---|
92 | n/a | self.assertEqual('%e' % f, result) |
---|
93 | n/a | |
---|
94 | n/a | # test all 2 digit exponents, both with __format__ and with |
---|
95 | n/a | # '%' formatting |
---|
96 | n/a | for i in range(-99, 100): |
---|
97 | n/a | test(float('1.5e'+str(i)), '1.500000e{0:+03d}'.format(i)) |
---|
98 | n/a | |
---|
99 | n/a | # test some 3 digit exponents |
---|
100 | n/a | self.assertEqual(1.5e100.__format__('e'), '1.500000e+100') |
---|
101 | n/a | self.assertEqual('%e' % 1.5e100, '1.500000e+100') |
---|
102 | n/a | |
---|
103 | n/a | self.assertEqual(1.5e101.__format__('e'), '1.500000e+101') |
---|
104 | n/a | self.assertEqual('%e' % 1.5e101, '1.500000e+101') |
---|
105 | n/a | |
---|
106 | n/a | self.assertEqual(1.5e-100.__format__('e'), '1.500000e-100') |
---|
107 | n/a | self.assertEqual('%e' % 1.5e-100, '1.500000e-100') |
---|
108 | n/a | |
---|
109 | n/a | self.assertEqual(1.5e-101.__format__('e'), '1.500000e-101') |
---|
110 | n/a | self.assertEqual('%e' % 1.5e-101, '1.500000e-101') |
---|
111 | n/a | |
---|
112 | n/a | self.assertEqual('%g' % 1.0, '1') |
---|
113 | n/a | self.assertEqual('%#g' % 1.0, '1.00000') |
---|
114 | n/a | |
---|
115 | n/a | def test_normal_integers(self): |
---|
116 | n/a | # Ensure the first 256 integers are shared |
---|
117 | n/a | a = 256 |
---|
118 | n/a | b = 128*2 |
---|
119 | n/a | if a is not b: self.fail('256 is not shared') |
---|
120 | n/a | if 12 + 24 != 36: self.fail('int op') |
---|
121 | n/a | if 12 + (-24) != -12: self.fail('int op') |
---|
122 | n/a | if (-12) + 24 != 12: self.fail('int op') |
---|
123 | n/a | if (-12) + (-24) != -36: self.fail('int op') |
---|
124 | n/a | if not 12 < 24: self.fail('int op') |
---|
125 | n/a | if not -24 < -12: self.fail('int op') |
---|
126 | n/a | # Test for a particular bug in integer multiply |
---|
127 | n/a | xsize, ysize, zsize = 238, 356, 4 |
---|
128 | n/a | if not (xsize*ysize*zsize == zsize*xsize*ysize == 338912): |
---|
129 | n/a | self.fail('int mul commutativity') |
---|
130 | n/a | # And another. |
---|
131 | n/a | m = -sys.maxsize - 1 |
---|
132 | n/a | for divisor in 1, 2, 4, 8, 16, 32: |
---|
133 | n/a | j = m // divisor |
---|
134 | n/a | prod = divisor * j |
---|
135 | n/a | if prod != m: |
---|
136 | n/a | self.fail("%r * %r == %r != %r" % (divisor, j, prod, m)) |
---|
137 | n/a | if type(prod) is not int: |
---|
138 | n/a | self.fail("expected type(prod) to be int, not %r" % |
---|
139 | n/a | type(prod)) |
---|
140 | n/a | # Check for unified integral type |
---|
141 | n/a | for divisor in 1, 2, 4, 8, 16, 32: |
---|
142 | n/a | j = m // divisor - 1 |
---|
143 | n/a | prod = divisor * j |
---|
144 | n/a | if type(prod) is not int: |
---|
145 | n/a | self.fail("expected type(%r) to be int, not %r" % |
---|
146 | n/a | (prod, type(prod))) |
---|
147 | n/a | # Check for unified integral type |
---|
148 | n/a | m = sys.maxsize |
---|
149 | n/a | for divisor in 1, 2, 4, 8, 16, 32: |
---|
150 | n/a | j = m // divisor + 1 |
---|
151 | n/a | prod = divisor * j |
---|
152 | n/a | if type(prod) is not int: |
---|
153 | n/a | self.fail("expected type(%r) to be int, not %r" % |
---|
154 | n/a | (prod, type(prod))) |
---|
155 | n/a | |
---|
156 | n/a | x = sys.maxsize |
---|
157 | n/a | self.assertIsInstance(x + 1, int, |
---|
158 | n/a | "(sys.maxsize + 1) should have returned int") |
---|
159 | n/a | self.assertIsInstance(-x - 1, int, |
---|
160 | n/a | "(-sys.maxsize - 1) should have returned int") |
---|
161 | n/a | self.assertIsInstance(-x - 2, int, |
---|
162 | n/a | "(-sys.maxsize - 2) should have returned int") |
---|
163 | n/a | |
---|
164 | n/a | try: 5 << -5 |
---|
165 | n/a | except ValueError: pass |
---|
166 | n/a | else: self.fail('int negative shift <<') |
---|
167 | n/a | |
---|
168 | n/a | try: 5 >> -5 |
---|
169 | n/a | except ValueError: pass |
---|
170 | n/a | else: self.fail('int negative shift >>') |
---|
171 | n/a | |
---|
172 | n/a | def test_floats(self): |
---|
173 | n/a | if 12.0 + 24.0 != 36.0: self.fail('float op') |
---|
174 | n/a | if 12.0 + (-24.0) != -12.0: self.fail('float op') |
---|
175 | n/a | if (-12.0) + 24.0 != 12.0: self.fail('float op') |
---|
176 | n/a | if (-12.0) + (-24.0) != -36.0: self.fail('float op') |
---|
177 | n/a | if not 12.0 < 24.0: self.fail('float op') |
---|
178 | n/a | if not -24.0 < -12.0: self.fail('float op') |
---|
179 | n/a | |
---|
180 | n/a | def test_strings(self): |
---|
181 | n/a | if len('') != 0: self.fail('len(\'\')') |
---|
182 | n/a | if len('a') != 1: self.fail('len(\'a\')') |
---|
183 | n/a | if len('abcdef') != 6: self.fail('len(\'abcdef\')') |
---|
184 | n/a | if 'xyz' + 'abcde' != 'xyzabcde': self.fail('string concatenation') |
---|
185 | n/a | if 'xyz'*3 != 'xyzxyzxyz': self.fail('string repetition *3') |
---|
186 | n/a | if 0*'abcde' != '': self.fail('string repetition 0*') |
---|
187 | n/a | if min('abc') != 'a' or max('abc') != 'c': self.fail('min/max string') |
---|
188 | n/a | if 'a' in 'abc' and 'b' in 'abc' and 'c' in 'abc' and 'd' not in 'abc': pass |
---|
189 | n/a | else: self.fail('in/not in string') |
---|
190 | n/a | x = 'x'*103 |
---|
191 | n/a | if '%s!'%x != x+'!': self.fail('nasty string formatting bug') |
---|
192 | n/a | |
---|
193 | n/a | #extended slices for strings |
---|
194 | n/a | a = '0123456789' |
---|
195 | n/a | self.assertEqual(a[::], a) |
---|
196 | n/a | self.assertEqual(a[::2], '02468') |
---|
197 | n/a | self.assertEqual(a[1::2], '13579') |
---|
198 | n/a | self.assertEqual(a[::-1],'9876543210') |
---|
199 | n/a | self.assertEqual(a[::-2], '97531') |
---|
200 | n/a | self.assertEqual(a[3::-2], '31') |
---|
201 | n/a | self.assertEqual(a[-100:100:], a) |
---|
202 | n/a | self.assertEqual(a[100:-100:-1], a[::-1]) |
---|
203 | n/a | self.assertEqual(a[-100:100:2], '02468') |
---|
204 | n/a | |
---|
205 | n/a | def test_type_function(self): |
---|
206 | n/a | self.assertRaises(TypeError, type, 1, 2) |
---|
207 | n/a | self.assertRaises(TypeError, type, 1, 2, 3, 4) |
---|
208 | n/a | |
---|
209 | n/a | def test_int__format__(self): |
---|
210 | n/a | def test(i, format_spec, result): |
---|
211 | n/a | # just make sure we have the unified type for integers |
---|
212 | n/a | assert type(i) == int |
---|
213 | n/a | assert type(format_spec) == str |
---|
214 | n/a | self.assertEqual(i.__format__(format_spec), result) |
---|
215 | n/a | |
---|
216 | n/a | test(123456789, 'd', '123456789') |
---|
217 | n/a | test(123456789, 'd', '123456789') |
---|
218 | n/a | |
---|
219 | n/a | test(1, 'c', '\01') |
---|
220 | n/a | |
---|
221 | n/a | # sign and aligning are interdependent |
---|
222 | n/a | test(1, "-", '1') |
---|
223 | n/a | test(-1, "-", '-1') |
---|
224 | n/a | test(1, "-3", ' 1') |
---|
225 | n/a | test(-1, "-3", ' -1') |
---|
226 | n/a | test(1, "+3", ' +1') |
---|
227 | n/a | test(-1, "+3", ' -1') |
---|
228 | n/a | test(1, " 3", ' 1') |
---|
229 | n/a | test(-1, " 3", ' -1') |
---|
230 | n/a | test(1, " ", ' 1') |
---|
231 | n/a | test(-1, " ", '-1') |
---|
232 | n/a | |
---|
233 | n/a | # hex |
---|
234 | n/a | test(3, "x", "3") |
---|
235 | n/a | test(3, "X", "3") |
---|
236 | n/a | test(1234, "x", "4d2") |
---|
237 | n/a | test(-1234, "x", "-4d2") |
---|
238 | n/a | test(1234, "8x", " 4d2") |
---|
239 | n/a | test(-1234, "8x", " -4d2") |
---|
240 | n/a | test(1234, "x", "4d2") |
---|
241 | n/a | test(-1234, "x", "-4d2") |
---|
242 | n/a | test(-3, "x", "-3") |
---|
243 | n/a | test(-3, "X", "-3") |
---|
244 | n/a | test(int('be', 16), "x", "be") |
---|
245 | n/a | test(int('be', 16), "X", "BE") |
---|
246 | n/a | test(-int('be', 16), "x", "-be") |
---|
247 | n/a | test(-int('be', 16), "X", "-BE") |
---|
248 | n/a | |
---|
249 | n/a | # octal |
---|
250 | n/a | test(3, "o", "3") |
---|
251 | n/a | test(-3, "o", "-3") |
---|
252 | n/a | test(65, "o", "101") |
---|
253 | n/a | test(-65, "o", "-101") |
---|
254 | n/a | test(1234, "o", "2322") |
---|
255 | n/a | test(-1234, "o", "-2322") |
---|
256 | n/a | test(1234, "-o", "2322") |
---|
257 | n/a | test(-1234, "-o", "-2322") |
---|
258 | n/a | test(1234, " o", " 2322") |
---|
259 | n/a | test(-1234, " o", "-2322") |
---|
260 | n/a | test(1234, "+o", "+2322") |
---|
261 | n/a | test(-1234, "+o", "-2322") |
---|
262 | n/a | |
---|
263 | n/a | # binary |
---|
264 | n/a | test(3, "b", "11") |
---|
265 | n/a | test(-3, "b", "-11") |
---|
266 | n/a | test(1234, "b", "10011010010") |
---|
267 | n/a | test(-1234, "b", "-10011010010") |
---|
268 | n/a | test(1234, "-b", "10011010010") |
---|
269 | n/a | test(-1234, "-b", "-10011010010") |
---|
270 | n/a | test(1234, " b", " 10011010010") |
---|
271 | n/a | test(-1234, " b", "-10011010010") |
---|
272 | n/a | test(1234, "+b", "+10011010010") |
---|
273 | n/a | test(-1234, "+b", "-10011010010") |
---|
274 | n/a | |
---|
275 | n/a | # alternate (#) formatting |
---|
276 | n/a | test(0, "#b", '0b0') |
---|
277 | n/a | test(0, "-#b", '0b0') |
---|
278 | n/a | test(1, "-#b", '0b1') |
---|
279 | n/a | test(-1, "-#b", '-0b1') |
---|
280 | n/a | test(-1, "-#5b", ' -0b1') |
---|
281 | n/a | test(1, "+#5b", ' +0b1') |
---|
282 | n/a | test(100, "+#b", '+0b1100100') |
---|
283 | n/a | test(100, "#012b", '0b0001100100') |
---|
284 | n/a | test(-100, "#012b", '-0b001100100') |
---|
285 | n/a | |
---|
286 | n/a | test(0, "#o", '0o0') |
---|
287 | n/a | test(0, "-#o", '0o0') |
---|
288 | n/a | test(1, "-#o", '0o1') |
---|
289 | n/a | test(-1, "-#o", '-0o1') |
---|
290 | n/a | test(-1, "-#5o", ' -0o1') |
---|
291 | n/a | test(1, "+#5o", ' +0o1') |
---|
292 | n/a | test(100, "+#o", '+0o144') |
---|
293 | n/a | test(100, "#012o", '0o0000000144') |
---|
294 | n/a | test(-100, "#012o", '-0o000000144') |
---|
295 | n/a | |
---|
296 | n/a | test(0, "#x", '0x0') |
---|
297 | n/a | test(0, "-#x", '0x0') |
---|
298 | n/a | test(1, "-#x", '0x1') |
---|
299 | n/a | test(-1, "-#x", '-0x1') |
---|
300 | n/a | test(-1, "-#5x", ' -0x1') |
---|
301 | n/a | test(1, "+#5x", ' +0x1') |
---|
302 | n/a | test(100, "+#x", '+0x64') |
---|
303 | n/a | test(100, "#012x", '0x0000000064') |
---|
304 | n/a | test(-100, "#012x", '-0x000000064') |
---|
305 | n/a | test(123456, "#012x", '0x000001e240') |
---|
306 | n/a | test(-123456, "#012x", '-0x00001e240') |
---|
307 | n/a | |
---|
308 | n/a | test(0, "#X", '0X0') |
---|
309 | n/a | test(0, "-#X", '0X0') |
---|
310 | n/a | test(1, "-#X", '0X1') |
---|
311 | n/a | test(-1, "-#X", '-0X1') |
---|
312 | n/a | test(-1, "-#5X", ' -0X1') |
---|
313 | n/a | test(1, "+#5X", ' +0X1') |
---|
314 | n/a | test(100, "+#X", '+0X64') |
---|
315 | n/a | test(100, "#012X", '0X0000000064') |
---|
316 | n/a | test(-100, "#012X", '-0X000000064') |
---|
317 | n/a | test(123456, "#012X", '0X000001E240') |
---|
318 | n/a | test(-123456, "#012X", '-0X00001E240') |
---|
319 | n/a | |
---|
320 | n/a | test(123, ',', '123') |
---|
321 | n/a | test(-123, ',', '-123') |
---|
322 | n/a | test(1234, ',', '1,234') |
---|
323 | n/a | test(-1234, ',', '-1,234') |
---|
324 | n/a | test(123456, ',', '123,456') |
---|
325 | n/a | test(-123456, ',', '-123,456') |
---|
326 | n/a | test(1234567, ',', '1,234,567') |
---|
327 | n/a | test(-1234567, ',', '-1,234,567') |
---|
328 | n/a | |
---|
329 | n/a | # issue 5782, commas with no specifier type |
---|
330 | n/a | test(1234, '010,', '00,001,234') |
---|
331 | n/a | |
---|
332 | n/a | # Unified type for integers |
---|
333 | n/a | test(10**100, 'd', '1' + '0' * 100) |
---|
334 | n/a | test(10**100+100, 'd', '1' + '0' * 97 + '100') |
---|
335 | n/a | |
---|
336 | n/a | # make sure these are errors |
---|
337 | n/a | |
---|
338 | n/a | # precision disallowed |
---|
339 | n/a | self.assertRaises(ValueError, 3 .__format__, "1.3") |
---|
340 | n/a | # sign not allowed with 'c' |
---|
341 | n/a | self.assertRaises(ValueError, 3 .__format__, "+c") |
---|
342 | n/a | # format spec must be string |
---|
343 | n/a | self.assertRaises(TypeError, 3 .__format__, None) |
---|
344 | n/a | self.assertRaises(TypeError, 3 .__format__, 0) |
---|
345 | n/a | # can't have ',' with 'n' |
---|
346 | n/a | self.assertRaises(ValueError, 3 .__format__, ",n") |
---|
347 | n/a | # can't have ',' with 'c' |
---|
348 | n/a | self.assertRaises(ValueError, 3 .__format__, ",c") |
---|
349 | n/a | # can't have '#' with 'c' |
---|
350 | n/a | self.assertRaises(ValueError, 3 .__format__, "#c") |
---|
351 | n/a | |
---|
352 | n/a | # ensure that only int and float type specifiers work |
---|
353 | n/a | for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + |
---|
354 | n/a | [chr(x) for x in range(ord('A'), ord('Z')+1)]): |
---|
355 | n/a | if not format_spec in 'bcdoxXeEfFgGn%': |
---|
356 | n/a | self.assertRaises(ValueError, 0 .__format__, format_spec) |
---|
357 | n/a | self.assertRaises(ValueError, 1 .__format__, format_spec) |
---|
358 | n/a | self.assertRaises(ValueError, (-1) .__format__, format_spec) |
---|
359 | n/a | |
---|
360 | n/a | # ensure that float type specifiers work; format converts |
---|
361 | n/a | # the int to a float |
---|
362 | n/a | for format_spec in 'eEfFgG%': |
---|
363 | n/a | for value in [0, 1, -1, 100, -100, 1234567890, -1234567890]: |
---|
364 | n/a | self.assertEqual(value.__format__(format_spec), |
---|
365 | n/a | float(value).__format__(format_spec)) |
---|
366 | n/a | |
---|
367 | n/a | # Issue 6902 |
---|
368 | n/a | test(123456, "0<20", '12345600000000000000') |
---|
369 | n/a | test(123456, "1<20", '12345611111111111111') |
---|
370 | n/a | test(123456, "*<20", '123456**************') |
---|
371 | n/a | test(123456, "0>20", '00000000000000123456') |
---|
372 | n/a | test(123456, "1>20", '11111111111111123456') |
---|
373 | n/a | test(123456, "*>20", '**************123456') |
---|
374 | n/a | test(123456, "0=20", '00000000000000123456') |
---|
375 | n/a | test(123456, "1=20", '11111111111111123456') |
---|
376 | n/a | test(123456, "*=20", '**************123456') |
---|
377 | n/a | |
---|
378 | n/a | @run_with_locale('LC_NUMERIC', 'en_US.UTF8') |
---|
379 | n/a | def test_float__format__locale(self): |
---|
380 | n/a | # test locale support for __format__ code 'n' |
---|
381 | n/a | |
---|
382 | n/a | for i in range(-10, 10): |
---|
383 | n/a | x = 1234567890.0 * (10.0 ** i) |
---|
384 | n/a | self.assertEqual(locale.format('%g', x, grouping=True), format(x, 'n')) |
---|
385 | n/a | self.assertEqual(locale.format('%.10g', x, grouping=True), format(x, '.10n')) |
---|
386 | n/a | |
---|
387 | n/a | @run_with_locale('LC_NUMERIC', 'en_US.UTF8') |
---|
388 | n/a | def test_int__format__locale(self): |
---|
389 | n/a | # test locale support for __format__ code 'n' for integers |
---|
390 | n/a | |
---|
391 | n/a | x = 123456789012345678901234567890 |
---|
392 | n/a | for i in range(0, 30): |
---|
393 | n/a | self.assertEqual(locale.format('%d', x, grouping=True), format(x, 'n')) |
---|
394 | n/a | |
---|
395 | n/a | # move to the next integer to test |
---|
396 | n/a | x = x // 10 |
---|
397 | n/a | |
---|
398 | n/a | rfmt = ">20n" |
---|
399 | n/a | lfmt = "<20n" |
---|
400 | n/a | cfmt = "^20n" |
---|
401 | n/a | for x in (1234, 12345, 123456, 1234567, 12345678, 123456789, 1234567890, 12345678900): |
---|
402 | n/a | self.assertEqual(len(format(0, rfmt)), len(format(x, rfmt))) |
---|
403 | n/a | self.assertEqual(len(format(0, lfmt)), len(format(x, lfmt))) |
---|
404 | n/a | self.assertEqual(len(format(0, cfmt)), len(format(x, cfmt))) |
---|
405 | n/a | |
---|
406 | n/a | def test_float__format__(self): |
---|
407 | n/a | def test(f, format_spec, result): |
---|
408 | n/a | self.assertEqual(f.__format__(format_spec), result) |
---|
409 | n/a | self.assertEqual(format(f, format_spec), result) |
---|
410 | n/a | |
---|
411 | n/a | test(0.0, 'f', '0.000000') |
---|
412 | n/a | |
---|
413 | n/a | # the default is 'g', except for empty format spec |
---|
414 | n/a | test(0.0, '', '0.0') |
---|
415 | n/a | test(0.01, '', '0.01') |
---|
416 | n/a | test(0.01, 'g', '0.01') |
---|
417 | n/a | |
---|
418 | n/a | # test for issue 3411 |
---|
419 | n/a | test(1.23, '1', '1.23') |
---|
420 | n/a | test(-1.23, '1', '-1.23') |
---|
421 | n/a | test(1.23, '1g', '1.23') |
---|
422 | n/a | test(-1.23, '1g', '-1.23') |
---|
423 | n/a | |
---|
424 | n/a | test( 1.0, ' g', ' 1') |
---|
425 | n/a | test(-1.0, ' g', '-1') |
---|
426 | n/a | test( 1.0, '+g', '+1') |
---|
427 | n/a | test(-1.0, '+g', '-1') |
---|
428 | n/a | test(1.1234e200, 'g', '1.1234e+200') |
---|
429 | n/a | test(1.1234e200, 'G', '1.1234E+200') |
---|
430 | n/a | |
---|
431 | n/a | |
---|
432 | n/a | test(1.0, 'f', '1.000000') |
---|
433 | n/a | |
---|
434 | n/a | test(-1.0, 'f', '-1.000000') |
---|
435 | n/a | |
---|
436 | n/a | test( 1.0, ' f', ' 1.000000') |
---|
437 | n/a | test(-1.0, ' f', '-1.000000') |
---|
438 | n/a | test( 1.0, '+f', '+1.000000') |
---|
439 | n/a | test(-1.0, '+f', '-1.000000') |
---|
440 | n/a | |
---|
441 | n/a | # Python versions <= 3.0 switched from 'f' to 'g' formatting for |
---|
442 | n/a | # values larger than 1e50. No longer. |
---|
443 | n/a | f = 1.1234e90 |
---|
444 | n/a | for fmt in 'f', 'F': |
---|
445 | n/a | # don't do a direct equality check, since on some |
---|
446 | n/a | # platforms only the first few digits of dtoa |
---|
447 | n/a | # will be reliable |
---|
448 | n/a | result = f.__format__(fmt) |
---|
449 | n/a | self.assertEqual(len(result), 98) |
---|
450 | n/a | self.assertEqual(result[-7], '.') |
---|
451 | n/a | self.assertIn(result[:12], ('112340000000', '112339999999')) |
---|
452 | n/a | f = 1.1234e200 |
---|
453 | n/a | for fmt in 'f', 'F': |
---|
454 | n/a | result = f.__format__(fmt) |
---|
455 | n/a | self.assertEqual(len(result), 208) |
---|
456 | n/a | self.assertEqual(result[-7], '.') |
---|
457 | n/a | self.assertIn(result[:12], ('112340000000', '112339999999')) |
---|
458 | n/a | |
---|
459 | n/a | |
---|
460 | n/a | test( 1.0, 'e', '1.000000e+00') |
---|
461 | n/a | test(-1.0, 'e', '-1.000000e+00') |
---|
462 | n/a | test( 1.0, 'E', '1.000000E+00') |
---|
463 | n/a | test(-1.0, 'E', '-1.000000E+00') |
---|
464 | n/a | test(1.1234e20, 'e', '1.123400e+20') |
---|
465 | n/a | test(1.1234e20, 'E', '1.123400E+20') |
---|
466 | n/a | |
---|
467 | n/a | # No format code means use g, but must have a decimal |
---|
468 | n/a | # and a number after the decimal. This is tricky, because |
---|
469 | n/a | # a totaly empty format specifier means something else. |
---|
470 | n/a | # So, just use a sign flag |
---|
471 | n/a | test(1e200, '+g', '+1e+200') |
---|
472 | n/a | test(1e200, '+', '+1e+200') |
---|
473 | n/a | |
---|
474 | n/a | test(1.1e200, '+g', '+1.1e+200') |
---|
475 | n/a | test(1.1e200, '+', '+1.1e+200') |
---|
476 | n/a | |
---|
477 | n/a | # 0 padding |
---|
478 | n/a | test(1234., '010f', '1234.000000') |
---|
479 | n/a | test(1234., '011f', '1234.000000') |
---|
480 | n/a | test(1234., '012f', '01234.000000') |
---|
481 | n/a | test(-1234., '011f', '-1234.000000') |
---|
482 | n/a | test(-1234., '012f', '-1234.000000') |
---|
483 | n/a | test(-1234., '013f', '-01234.000000') |
---|
484 | n/a | test(-1234.12341234, '013f', '-01234.123412') |
---|
485 | n/a | test(-123456.12341234, '011.2f', '-0123456.12') |
---|
486 | n/a | |
---|
487 | n/a | # issue 5782, commas with no specifier type |
---|
488 | n/a | test(1.2, '010,.2', '0,000,001.2') |
---|
489 | n/a | |
---|
490 | n/a | # 0 padding with commas |
---|
491 | n/a | test(1234., '011,f', '1,234.000000') |
---|
492 | n/a | test(1234., '012,f', '1,234.000000') |
---|
493 | n/a | test(1234., '013,f', '01,234.000000') |
---|
494 | n/a | test(-1234., '012,f', '-1,234.000000') |
---|
495 | n/a | test(-1234., '013,f', '-1,234.000000') |
---|
496 | n/a | test(-1234., '014,f', '-01,234.000000') |
---|
497 | n/a | test(-12345., '015,f', '-012,345.000000') |
---|
498 | n/a | test(-123456., '016,f', '-0,123,456.000000') |
---|
499 | n/a | test(-123456., '017,f', '-0,123,456.000000') |
---|
500 | n/a | test(-123456.12341234, '017,f', '-0,123,456.123412') |
---|
501 | n/a | test(-123456.12341234, '013,.2f', '-0,123,456.12') |
---|
502 | n/a | |
---|
503 | n/a | # % formatting |
---|
504 | n/a | test(-1.0, '%', '-100.000000%') |
---|
505 | n/a | |
---|
506 | n/a | # format spec must be string |
---|
507 | n/a | self.assertRaises(TypeError, 3.0.__format__, None) |
---|
508 | n/a | self.assertRaises(TypeError, 3.0.__format__, 0) |
---|
509 | n/a | |
---|
510 | n/a | # other format specifiers shouldn't work on floats, |
---|
511 | n/a | # in particular int specifiers |
---|
512 | n/a | for format_spec in ([chr(x) for x in range(ord('a'), ord('z')+1)] + |
---|
513 | n/a | [chr(x) for x in range(ord('A'), ord('Z')+1)]): |
---|
514 | n/a | if not format_spec in 'eEfFgGn%': |
---|
515 | n/a | self.assertRaises(ValueError, format, 0.0, format_spec) |
---|
516 | n/a | self.assertRaises(ValueError, format, 1.0, format_spec) |
---|
517 | n/a | self.assertRaises(ValueError, format, -1.0, format_spec) |
---|
518 | n/a | self.assertRaises(ValueError, format, 1e100, format_spec) |
---|
519 | n/a | self.assertRaises(ValueError, format, -1e100, format_spec) |
---|
520 | n/a | self.assertRaises(ValueError, format, 1e-100, format_spec) |
---|
521 | n/a | self.assertRaises(ValueError, format, -1e-100, format_spec) |
---|
522 | n/a | |
---|
523 | n/a | # Alternate float formatting |
---|
524 | n/a | test(1.0, '.0e', '1e+00') |
---|
525 | n/a | test(1.0, '#.0e', '1.e+00') |
---|
526 | n/a | test(1.0, '.0f', '1') |
---|
527 | n/a | test(1.0, '#.0f', '1.') |
---|
528 | n/a | test(1.1, 'g', '1.1') |
---|
529 | n/a | test(1.1, '#g', '1.10000') |
---|
530 | n/a | test(1.0, '.0%', '100%') |
---|
531 | n/a | test(1.0, '#.0%', '100.%') |
---|
532 | n/a | |
---|
533 | n/a | # Issue 7094: Alternate formatting (specified by #) |
---|
534 | n/a | test(1.0, '0e', '1.000000e+00') |
---|
535 | n/a | test(1.0, '#0e', '1.000000e+00') |
---|
536 | n/a | test(1.0, '0f', '1.000000' ) |
---|
537 | n/a | test(1.0, '#0f', '1.000000') |
---|
538 | n/a | test(1.0, '.1e', '1.0e+00') |
---|
539 | n/a | test(1.0, '#.1e', '1.0e+00') |
---|
540 | n/a | test(1.0, '.1f', '1.0') |
---|
541 | n/a | test(1.0, '#.1f', '1.0') |
---|
542 | n/a | test(1.0, '.1%', '100.0%') |
---|
543 | n/a | test(1.0, '#.1%', '100.0%') |
---|
544 | n/a | |
---|
545 | n/a | # Issue 6902 |
---|
546 | n/a | test(12345.6, "0<20", '12345.60000000000000') |
---|
547 | n/a | test(12345.6, "1<20", '12345.61111111111111') |
---|
548 | n/a | test(12345.6, "*<20", '12345.6*************') |
---|
549 | n/a | test(12345.6, "0>20", '000000000000012345.6') |
---|
550 | n/a | test(12345.6, "1>20", '111111111111112345.6') |
---|
551 | n/a | test(12345.6, "*>20", '*************12345.6') |
---|
552 | n/a | test(12345.6, "0=20", '000000000000012345.6') |
---|
553 | n/a | test(12345.6, "1=20", '111111111111112345.6') |
---|
554 | n/a | test(12345.6, "*=20", '*************12345.6') |
---|
555 | n/a | |
---|
556 | n/a | def test_format_spec_errors(self): |
---|
557 | n/a | # int, float, and string all share the same format spec |
---|
558 | n/a | # mini-language parser. |
---|
559 | n/a | |
---|
560 | n/a | # Check that we can't ask for too many digits. This is |
---|
561 | n/a | # probably a CPython specific test. It tries to put the width |
---|
562 | n/a | # into a C long. |
---|
563 | n/a | self.assertRaises(ValueError, format, 0, '1'*10000 + 'd') |
---|
564 | n/a | |
---|
565 | n/a | # Similar with the precision. |
---|
566 | n/a | self.assertRaises(ValueError, format, 0, '.' + '1'*10000 + 'd') |
---|
567 | n/a | |
---|
568 | n/a | # And may as well test both. |
---|
569 | n/a | self.assertRaises(ValueError, format, 0, '1'*1000 + '.' + '1'*10000 + 'd') |
---|
570 | n/a | |
---|
571 | n/a | # Make sure commas aren't allowed with various type codes |
---|
572 | n/a | for code in 'xXobns': |
---|
573 | n/a | self.assertRaises(ValueError, format, 0, ',' + code) |
---|
574 | n/a | |
---|
575 | n/a | def test_internal_sizes(self): |
---|
576 | n/a | self.assertGreater(object.__basicsize__, 0) |
---|
577 | n/a | self.assertGreater(tuple.__itemsize__, 0) |
---|
578 | n/a | |
---|
579 | n/a | def test_slot_wrapper_types(self): |
---|
580 | n/a | self.assertIsInstance(object.__init__, types.SlotWrapperType) |
---|
581 | n/a | self.assertIsInstance(object.__str__, types.SlotWrapperType) |
---|
582 | n/a | self.assertIsInstance(object.__lt__, types.SlotWrapperType) |
---|
583 | n/a | self.assertIsInstance(int.__lt__, types.SlotWrapperType) |
---|
584 | n/a | |
---|
585 | n/a | def test_method_wrapper_types(self): |
---|
586 | n/a | self.assertIsInstance(object().__init__, types.MethodWrapperType) |
---|
587 | n/a | self.assertIsInstance(object().__str__, types.MethodWrapperType) |
---|
588 | n/a | self.assertIsInstance(object().__lt__, types.MethodWrapperType) |
---|
589 | n/a | self.assertIsInstance((42).__lt__, types.MethodWrapperType) |
---|
590 | n/a | |
---|
591 | n/a | def test_method_descriptor_types(self): |
---|
592 | n/a | self.assertIsInstance(str.join, types.MethodDescriptorType) |
---|
593 | n/a | self.assertIsInstance(list.append, types.MethodDescriptorType) |
---|
594 | n/a | self.assertIsInstance(''.join, types.BuiltinMethodType) |
---|
595 | n/a | self.assertIsInstance([].append, types.BuiltinMethodType) |
---|
596 | n/a | |
---|
597 | n/a | |
---|
598 | n/a | class MappingProxyTests(unittest.TestCase): |
---|
599 | n/a | mappingproxy = types.MappingProxyType |
---|
600 | n/a | |
---|
601 | n/a | def test_constructor(self): |
---|
602 | n/a | class userdict(dict): |
---|
603 | n/a | pass |
---|
604 | n/a | |
---|
605 | n/a | mapping = {'x': 1, 'y': 2} |
---|
606 | n/a | self.assertEqual(self.mappingproxy(mapping), mapping) |
---|
607 | n/a | mapping = userdict(x=1, y=2) |
---|
608 | n/a | self.assertEqual(self.mappingproxy(mapping), mapping) |
---|
609 | n/a | mapping = collections.ChainMap({'x': 1}, {'y': 2}) |
---|
610 | n/a | self.assertEqual(self.mappingproxy(mapping), mapping) |
---|
611 | n/a | |
---|
612 | n/a | self.assertRaises(TypeError, self.mappingproxy, 10) |
---|
613 | n/a | self.assertRaises(TypeError, self.mappingproxy, ("a", "tuple")) |
---|
614 | n/a | self.assertRaises(TypeError, self.mappingproxy, ["a", "list"]) |
---|
615 | n/a | |
---|
616 | n/a | def test_methods(self): |
---|
617 | n/a | attrs = set(dir(self.mappingproxy({}))) - set(dir(object())) |
---|
618 | n/a | self.assertEqual(attrs, { |
---|
619 | n/a | '__contains__', |
---|
620 | n/a | '__getitem__', |
---|
621 | n/a | '__iter__', |
---|
622 | n/a | '__len__', |
---|
623 | n/a | 'copy', |
---|
624 | n/a | 'get', |
---|
625 | n/a | 'items', |
---|
626 | n/a | 'keys', |
---|
627 | n/a | 'values', |
---|
628 | n/a | }) |
---|
629 | n/a | |
---|
630 | n/a | def test_get(self): |
---|
631 | n/a | view = self.mappingproxy({'a': 'A', 'b': 'B'}) |
---|
632 | n/a | self.assertEqual(view['a'], 'A') |
---|
633 | n/a | self.assertEqual(view['b'], 'B') |
---|
634 | n/a | self.assertRaises(KeyError, view.__getitem__, 'xxx') |
---|
635 | n/a | self.assertEqual(view.get('a'), 'A') |
---|
636 | n/a | self.assertIsNone(view.get('xxx')) |
---|
637 | n/a | self.assertEqual(view.get('xxx', 42), 42) |
---|
638 | n/a | |
---|
639 | n/a | def test_missing(self): |
---|
640 | n/a | class dictmissing(dict): |
---|
641 | n/a | def __missing__(self, key): |
---|
642 | n/a | return "missing=%s" % key |
---|
643 | n/a | |
---|
644 | n/a | view = self.mappingproxy(dictmissing(x=1)) |
---|
645 | n/a | self.assertEqual(view['x'], 1) |
---|
646 | n/a | self.assertEqual(view['y'], 'missing=y') |
---|
647 | n/a | self.assertEqual(view.get('x'), 1) |
---|
648 | n/a | self.assertEqual(view.get('y'), None) |
---|
649 | n/a | self.assertEqual(view.get('y', 42), 42) |
---|
650 | n/a | self.assertTrue('x' in view) |
---|
651 | n/a | self.assertFalse('y' in view) |
---|
652 | n/a | |
---|
653 | n/a | def test_customdict(self): |
---|
654 | n/a | class customdict(dict): |
---|
655 | n/a | def __contains__(self, key): |
---|
656 | n/a | if key == 'magic': |
---|
657 | n/a | return True |
---|
658 | n/a | else: |
---|
659 | n/a | return dict.__contains__(self, key) |
---|
660 | n/a | |
---|
661 | n/a | def __iter__(self): |
---|
662 | n/a | return iter(('iter',)) |
---|
663 | n/a | |
---|
664 | n/a | def __len__(self): |
---|
665 | n/a | return 500 |
---|
666 | n/a | |
---|
667 | n/a | def copy(self): |
---|
668 | n/a | return 'copy' |
---|
669 | n/a | |
---|
670 | n/a | def keys(self): |
---|
671 | n/a | return 'keys' |
---|
672 | n/a | |
---|
673 | n/a | def items(self): |
---|
674 | n/a | return 'items' |
---|
675 | n/a | |
---|
676 | n/a | def values(self): |
---|
677 | n/a | return 'values' |
---|
678 | n/a | |
---|
679 | n/a | def __getitem__(self, key): |
---|
680 | n/a | return "getitem=%s" % dict.__getitem__(self, key) |
---|
681 | n/a | |
---|
682 | n/a | def get(self, key, default=None): |
---|
683 | n/a | return "get=%s" % dict.get(self, key, 'default=%r' % default) |
---|
684 | n/a | |
---|
685 | n/a | custom = customdict({'key': 'value'}) |
---|
686 | n/a | view = self.mappingproxy(custom) |
---|
687 | n/a | self.assertTrue('key' in view) |
---|
688 | n/a | self.assertTrue('magic' in view) |
---|
689 | n/a | self.assertFalse('xxx' in view) |
---|
690 | n/a | self.assertEqual(view['key'], 'getitem=value') |
---|
691 | n/a | self.assertRaises(KeyError, view.__getitem__, 'xxx') |
---|
692 | n/a | self.assertEqual(tuple(view), ('iter',)) |
---|
693 | n/a | self.assertEqual(len(view), 500) |
---|
694 | n/a | self.assertEqual(view.copy(), 'copy') |
---|
695 | n/a | self.assertEqual(view.get('key'), 'get=value') |
---|
696 | n/a | self.assertEqual(view.get('xxx'), 'get=default=None') |
---|
697 | n/a | self.assertEqual(view.items(), 'items') |
---|
698 | n/a | self.assertEqual(view.keys(), 'keys') |
---|
699 | n/a | self.assertEqual(view.values(), 'values') |
---|
700 | n/a | |
---|
701 | n/a | def test_chainmap(self): |
---|
702 | n/a | d1 = {'x': 1} |
---|
703 | n/a | d2 = {'y': 2} |
---|
704 | n/a | mapping = collections.ChainMap(d1, d2) |
---|
705 | n/a | view = self.mappingproxy(mapping) |
---|
706 | n/a | self.assertTrue('x' in view) |
---|
707 | n/a | self.assertTrue('y' in view) |
---|
708 | n/a | self.assertFalse('z' in view) |
---|
709 | n/a | self.assertEqual(view['x'], 1) |
---|
710 | n/a | self.assertEqual(view['y'], 2) |
---|
711 | n/a | self.assertRaises(KeyError, view.__getitem__, 'z') |
---|
712 | n/a | self.assertEqual(tuple(sorted(view)), ('x', 'y')) |
---|
713 | n/a | self.assertEqual(len(view), 2) |
---|
714 | n/a | copy = view.copy() |
---|
715 | n/a | self.assertIsNot(copy, mapping) |
---|
716 | n/a | self.assertIsInstance(copy, collections.ChainMap) |
---|
717 | n/a | self.assertEqual(copy, mapping) |
---|
718 | n/a | self.assertEqual(view.get('x'), 1) |
---|
719 | n/a | self.assertEqual(view.get('y'), 2) |
---|
720 | n/a | self.assertIsNone(view.get('z')) |
---|
721 | n/a | self.assertEqual(tuple(sorted(view.items())), (('x', 1), ('y', 2))) |
---|
722 | n/a | self.assertEqual(tuple(sorted(view.keys())), ('x', 'y')) |
---|
723 | n/a | self.assertEqual(tuple(sorted(view.values())), (1, 2)) |
---|
724 | n/a | |
---|
725 | n/a | def test_contains(self): |
---|
726 | n/a | view = self.mappingproxy(dict.fromkeys('abc')) |
---|
727 | n/a | self.assertTrue('a' in view) |
---|
728 | n/a | self.assertTrue('b' in view) |
---|
729 | n/a | self.assertTrue('c' in view) |
---|
730 | n/a | self.assertFalse('xxx' in view) |
---|
731 | n/a | |
---|
732 | n/a | def test_views(self): |
---|
733 | n/a | mapping = {} |
---|
734 | n/a | view = self.mappingproxy(mapping) |
---|
735 | n/a | keys = view.keys() |
---|
736 | n/a | values = view.values() |
---|
737 | n/a | items = view.items() |
---|
738 | n/a | self.assertEqual(list(keys), []) |
---|
739 | n/a | self.assertEqual(list(values), []) |
---|
740 | n/a | self.assertEqual(list(items), []) |
---|
741 | n/a | mapping['key'] = 'value' |
---|
742 | n/a | self.assertEqual(list(keys), ['key']) |
---|
743 | n/a | self.assertEqual(list(values), ['value']) |
---|
744 | n/a | self.assertEqual(list(items), [('key', 'value')]) |
---|
745 | n/a | |
---|
746 | n/a | def test_len(self): |
---|
747 | n/a | for expected in range(6): |
---|
748 | n/a | data = dict.fromkeys('abcde'[:expected]) |
---|
749 | n/a | self.assertEqual(len(data), expected) |
---|
750 | n/a | view = self.mappingproxy(data) |
---|
751 | n/a | self.assertEqual(len(view), expected) |
---|
752 | n/a | |
---|
753 | n/a | def test_iterators(self): |
---|
754 | n/a | keys = ('x', 'y') |
---|
755 | n/a | values = (1, 2) |
---|
756 | n/a | items = tuple(zip(keys, values)) |
---|
757 | n/a | view = self.mappingproxy(dict(items)) |
---|
758 | n/a | self.assertEqual(set(view), set(keys)) |
---|
759 | n/a | self.assertEqual(set(view.keys()), set(keys)) |
---|
760 | n/a | self.assertEqual(set(view.values()), set(values)) |
---|
761 | n/a | self.assertEqual(set(view.items()), set(items)) |
---|
762 | n/a | |
---|
763 | n/a | def test_copy(self): |
---|
764 | n/a | original = {'key1': 27, 'key2': 51, 'key3': 93} |
---|
765 | n/a | view = self.mappingproxy(original) |
---|
766 | n/a | copy = view.copy() |
---|
767 | n/a | self.assertEqual(type(copy), dict) |
---|
768 | n/a | self.assertEqual(copy, original) |
---|
769 | n/a | original['key1'] = 70 |
---|
770 | n/a | self.assertEqual(view['key1'], 70) |
---|
771 | n/a | self.assertEqual(copy['key1'], 27) |
---|
772 | n/a | |
---|
773 | n/a | |
---|
774 | n/a | class ClassCreationTests(unittest.TestCase): |
---|
775 | n/a | |
---|
776 | n/a | class Meta(type): |
---|
777 | n/a | def __init__(cls, name, bases, ns, **kw): |
---|
778 | n/a | super().__init__(name, bases, ns) |
---|
779 | n/a | @staticmethod |
---|
780 | n/a | def __new__(mcls, name, bases, ns, **kw): |
---|
781 | n/a | return super().__new__(mcls, name, bases, ns) |
---|
782 | n/a | @classmethod |
---|
783 | n/a | def __prepare__(mcls, name, bases, **kw): |
---|
784 | n/a | ns = super().__prepare__(name, bases) |
---|
785 | n/a | ns["y"] = 1 |
---|
786 | n/a | ns.update(kw) |
---|
787 | n/a | return ns |
---|
788 | n/a | |
---|
789 | n/a | def test_new_class_basics(self): |
---|
790 | n/a | C = types.new_class("C") |
---|
791 | n/a | self.assertEqual(C.__name__, "C") |
---|
792 | n/a | self.assertEqual(C.__bases__, (object,)) |
---|
793 | n/a | |
---|
794 | n/a | def test_new_class_subclass(self): |
---|
795 | n/a | C = types.new_class("C", (int,)) |
---|
796 | n/a | self.assertTrue(issubclass(C, int)) |
---|
797 | n/a | |
---|
798 | n/a | def test_new_class_meta(self): |
---|
799 | n/a | Meta = self.Meta |
---|
800 | n/a | settings = {"metaclass": Meta, "z": 2} |
---|
801 | n/a | # We do this twice to make sure the passed in dict isn't mutated |
---|
802 | n/a | for i in range(2): |
---|
803 | n/a | C = types.new_class("C" + str(i), (), settings) |
---|
804 | n/a | self.assertIsInstance(C, Meta) |
---|
805 | n/a | self.assertEqual(C.y, 1) |
---|
806 | n/a | self.assertEqual(C.z, 2) |
---|
807 | n/a | |
---|
808 | n/a | def test_new_class_exec_body(self): |
---|
809 | n/a | Meta = self.Meta |
---|
810 | n/a | def func(ns): |
---|
811 | n/a | ns["x"] = 0 |
---|
812 | n/a | C = types.new_class("C", (), {"metaclass": Meta, "z": 2}, func) |
---|
813 | n/a | self.assertIsInstance(C, Meta) |
---|
814 | n/a | self.assertEqual(C.x, 0) |
---|
815 | n/a | self.assertEqual(C.y, 1) |
---|
816 | n/a | self.assertEqual(C.z, 2) |
---|
817 | n/a | |
---|
818 | n/a | def test_new_class_metaclass_keywords(self): |
---|
819 | n/a | #Test that keywords are passed to the metaclass: |
---|
820 | n/a | def meta_func(name, bases, ns, **kw): |
---|
821 | n/a | return name, bases, ns, kw |
---|
822 | n/a | res = types.new_class("X", |
---|
823 | n/a | (int, object), |
---|
824 | n/a | dict(metaclass=meta_func, x=0)) |
---|
825 | n/a | self.assertEqual(res, ("X", (int, object), {}, {"x": 0})) |
---|
826 | n/a | |
---|
827 | n/a | def test_new_class_defaults(self): |
---|
828 | n/a | # Test defaults/keywords: |
---|
829 | n/a | C = types.new_class("C", (), {}, None) |
---|
830 | n/a | self.assertEqual(C.__name__, "C") |
---|
831 | n/a | self.assertEqual(C.__bases__, (object,)) |
---|
832 | n/a | |
---|
833 | n/a | def test_new_class_meta_with_base(self): |
---|
834 | n/a | Meta = self.Meta |
---|
835 | n/a | def func(ns): |
---|
836 | n/a | ns["x"] = 0 |
---|
837 | n/a | C = types.new_class(name="C", |
---|
838 | n/a | bases=(int,), |
---|
839 | n/a | kwds=dict(metaclass=Meta, z=2), |
---|
840 | n/a | exec_body=func) |
---|
841 | n/a | self.assertTrue(issubclass(C, int)) |
---|
842 | n/a | self.assertIsInstance(C, Meta) |
---|
843 | n/a | self.assertEqual(C.x, 0) |
---|
844 | n/a | self.assertEqual(C.y, 1) |
---|
845 | n/a | self.assertEqual(C.z, 2) |
---|
846 | n/a | |
---|
847 | n/a | # Many of the following tests are derived from test_descr.py |
---|
848 | n/a | def test_prepare_class(self): |
---|
849 | n/a | # Basic test of metaclass derivation |
---|
850 | n/a | expected_ns = {} |
---|
851 | n/a | class A(type): |
---|
852 | n/a | def __new__(*args, **kwargs): |
---|
853 | n/a | return type.__new__(*args, **kwargs) |
---|
854 | n/a | |
---|
855 | n/a | def __prepare__(*args): |
---|
856 | n/a | return expected_ns |
---|
857 | n/a | |
---|
858 | n/a | B = types.new_class("B", (object,)) |
---|
859 | n/a | C = types.new_class("C", (object,), {"metaclass": A}) |
---|
860 | n/a | |
---|
861 | n/a | # The most derived metaclass of D is A rather than type. |
---|
862 | n/a | meta, ns, kwds = types.prepare_class("D", (B, C), {"metaclass": type}) |
---|
863 | n/a | self.assertIs(meta, A) |
---|
864 | n/a | self.assertIs(ns, expected_ns) |
---|
865 | n/a | self.assertEqual(len(kwds), 0) |
---|
866 | n/a | |
---|
867 | n/a | def test_metaclass_derivation(self): |
---|
868 | n/a | # issue1294232: correct metaclass calculation |
---|
869 | n/a | new_calls = [] # to check the order of __new__ calls |
---|
870 | n/a | class AMeta(type): |
---|
871 | n/a | def __new__(mcls, name, bases, ns): |
---|
872 | n/a | new_calls.append('AMeta') |
---|
873 | n/a | return super().__new__(mcls, name, bases, ns) |
---|
874 | n/a | @classmethod |
---|
875 | n/a | def __prepare__(mcls, name, bases): |
---|
876 | n/a | return {} |
---|
877 | n/a | |
---|
878 | n/a | class BMeta(AMeta): |
---|
879 | n/a | def __new__(mcls, name, bases, ns): |
---|
880 | n/a | new_calls.append('BMeta') |
---|
881 | n/a | return super().__new__(mcls, name, bases, ns) |
---|
882 | n/a | @classmethod |
---|
883 | n/a | def __prepare__(mcls, name, bases): |
---|
884 | n/a | ns = super().__prepare__(name, bases) |
---|
885 | n/a | ns['BMeta_was_here'] = True |
---|
886 | n/a | return ns |
---|
887 | n/a | |
---|
888 | n/a | A = types.new_class("A", (), {"metaclass": AMeta}) |
---|
889 | n/a | self.assertEqual(new_calls, ['AMeta']) |
---|
890 | n/a | new_calls.clear() |
---|
891 | n/a | |
---|
892 | n/a | B = types.new_class("B", (), {"metaclass": BMeta}) |
---|
893 | n/a | # BMeta.__new__ calls AMeta.__new__ with super: |
---|
894 | n/a | self.assertEqual(new_calls, ['BMeta', 'AMeta']) |
---|
895 | n/a | new_calls.clear() |
---|
896 | n/a | |
---|
897 | n/a | C = types.new_class("C", (A, B)) |
---|
898 | n/a | # The most derived metaclass is BMeta: |
---|
899 | n/a | self.assertEqual(new_calls, ['BMeta', 'AMeta']) |
---|
900 | n/a | new_calls.clear() |
---|
901 | n/a | # BMeta.__prepare__ should've been called: |
---|
902 | n/a | self.assertIn('BMeta_was_here', C.__dict__) |
---|
903 | n/a | |
---|
904 | n/a | # The order of the bases shouldn't matter: |
---|
905 | n/a | C2 = types.new_class("C2", (B, A)) |
---|
906 | n/a | self.assertEqual(new_calls, ['BMeta', 'AMeta']) |
---|
907 | n/a | new_calls.clear() |
---|
908 | n/a | self.assertIn('BMeta_was_here', C2.__dict__) |
---|
909 | n/a | |
---|
910 | n/a | # Check correct metaclass calculation when a metaclass is declared: |
---|
911 | n/a | D = types.new_class("D", (C,), {"metaclass": type}) |
---|
912 | n/a | self.assertEqual(new_calls, ['BMeta', 'AMeta']) |
---|
913 | n/a | new_calls.clear() |
---|
914 | n/a | self.assertIn('BMeta_was_here', D.__dict__) |
---|
915 | n/a | |
---|
916 | n/a | E = types.new_class("E", (C,), {"metaclass": AMeta}) |
---|
917 | n/a | self.assertEqual(new_calls, ['BMeta', 'AMeta']) |
---|
918 | n/a | new_calls.clear() |
---|
919 | n/a | self.assertIn('BMeta_was_here', E.__dict__) |
---|
920 | n/a | |
---|
921 | n/a | def test_metaclass_override_function(self): |
---|
922 | n/a | # Special case: the given metaclass isn't a class, |
---|
923 | n/a | # so there is no metaclass calculation. |
---|
924 | n/a | class A(metaclass=self.Meta): |
---|
925 | n/a | pass |
---|
926 | n/a | |
---|
927 | n/a | marker = object() |
---|
928 | n/a | def func(*args, **kwargs): |
---|
929 | n/a | return marker |
---|
930 | n/a | |
---|
931 | n/a | X = types.new_class("X", (), {"metaclass": func}) |
---|
932 | n/a | Y = types.new_class("Y", (object,), {"metaclass": func}) |
---|
933 | n/a | Z = types.new_class("Z", (A,), {"metaclass": func}) |
---|
934 | n/a | self.assertIs(marker, X) |
---|
935 | n/a | self.assertIs(marker, Y) |
---|
936 | n/a | self.assertIs(marker, Z) |
---|
937 | n/a | |
---|
938 | n/a | def test_metaclass_override_callable(self): |
---|
939 | n/a | # The given metaclass is a class, |
---|
940 | n/a | # but not a descendant of type. |
---|
941 | n/a | new_calls = [] # to check the order of __new__ calls |
---|
942 | n/a | prepare_calls = [] # to track __prepare__ calls |
---|
943 | n/a | class ANotMeta: |
---|
944 | n/a | def __new__(mcls, *args, **kwargs): |
---|
945 | n/a | new_calls.append('ANotMeta') |
---|
946 | n/a | return super().__new__(mcls) |
---|
947 | n/a | @classmethod |
---|
948 | n/a | def __prepare__(mcls, name, bases): |
---|
949 | n/a | prepare_calls.append('ANotMeta') |
---|
950 | n/a | return {} |
---|
951 | n/a | |
---|
952 | n/a | class BNotMeta(ANotMeta): |
---|
953 | n/a | def __new__(mcls, *args, **kwargs): |
---|
954 | n/a | new_calls.append('BNotMeta') |
---|
955 | n/a | return super().__new__(mcls) |
---|
956 | n/a | @classmethod |
---|
957 | n/a | def __prepare__(mcls, name, bases): |
---|
958 | n/a | prepare_calls.append('BNotMeta') |
---|
959 | n/a | return super().__prepare__(name, bases) |
---|
960 | n/a | |
---|
961 | n/a | A = types.new_class("A", (), {"metaclass": ANotMeta}) |
---|
962 | n/a | self.assertIs(ANotMeta, type(A)) |
---|
963 | n/a | self.assertEqual(prepare_calls, ['ANotMeta']) |
---|
964 | n/a | prepare_calls.clear() |
---|
965 | n/a | self.assertEqual(new_calls, ['ANotMeta']) |
---|
966 | n/a | new_calls.clear() |
---|
967 | n/a | |
---|
968 | n/a | B = types.new_class("B", (), {"metaclass": BNotMeta}) |
---|
969 | n/a | self.assertIs(BNotMeta, type(B)) |
---|
970 | n/a | self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta']) |
---|
971 | n/a | prepare_calls.clear() |
---|
972 | n/a | self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta']) |
---|
973 | n/a | new_calls.clear() |
---|
974 | n/a | |
---|
975 | n/a | C = types.new_class("C", (A, B)) |
---|
976 | n/a | self.assertIs(BNotMeta, type(C)) |
---|
977 | n/a | self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta']) |
---|
978 | n/a | prepare_calls.clear() |
---|
979 | n/a | self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta']) |
---|
980 | n/a | new_calls.clear() |
---|
981 | n/a | |
---|
982 | n/a | C2 = types.new_class("C2", (B, A)) |
---|
983 | n/a | self.assertIs(BNotMeta, type(C2)) |
---|
984 | n/a | self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta']) |
---|
985 | n/a | prepare_calls.clear() |
---|
986 | n/a | self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta']) |
---|
987 | n/a | new_calls.clear() |
---|
988 | n/a | |
---|
989 | n/a | # This is a TypeError, because of a metaclass conflict: |
---|
990 | n/a | # BNotMeta is neither a subclass, nor a superclass of type |
---|
991 | n/a | with self.assertRaises(TypeError): |
---|
992 | n/a | D = types.new_class("D", (C,), {"metaclass": type}) |
---|
993 | n/a | |
---|
994 | n/a | E = types.new_class("E", (C,), {"metaclass": ANotMeta}) |
---|
995 | n/a | self.assertIs(BNotMeta, type(E)) |
---|
996 | n/a | self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta']) |
---|
997 | n/a | prepare_calls.clear() |
---|
998 | n/a | self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta']) |
---|
999 | n/a | new_calls.clear() |
---|
1000 | n/a | |
---|
1001 | n/a | F = types.new_class("F", (object(), C)) |
---|
1002 | n/a | self.assertIs(BNotMeta, type(F)) |
---|
1003 | n/a | self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta']) |
---|
1004 | n/a | prepare_calls.clear() |
---|
1005 | n/a | self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta']) |
---|
1006 | n/a | new_calls.clear() |
---|
1007 | n/a | |
---|
1008 | n/a | F2 = types.new_class("F2", (C, object())) |
---|
1009 | n/a | self.assertIs(BNotMeta, type(F2)) |
---|
1010 | n/a | self.assertEqual(prepare_calls, ['BNotMeta', 'ANotMeta']) |
---|
1011 | n/a | prepare_calls.clear() |
---|
1012 | n/a | self.assertEqual(new_calls, ['BNotMeta', 'ANotMeta']) |
---|
1013 | n/a | new_calls.clear() |
---|
1014 | n/a | |
---|
1015 | n/a | # TypeError: BNotMeta is neither a |
---|
1016 | n/a | # subclass, nor a superclass of int |
---|
1017 | n/a | with self.assertRaises(TypeError): |
---|
1018 | n/a | X = types.new_class("X", (C, int())) |
---|
1019 | n/a | with self.assertRaises(TypeError): |
---|
1020 | n/a | X = types.new_class("X", (int(), C)) |
---|
1021 | n/a | |
---|
1022 | n/a | def test_one_argument_type(self): |
---|
1023 | n/a | expected_message = 'type.__new__() takes exactly 3 arguments (1 given)' |
---|
1024 | n/a | |
---|
1025 | n/a | # Only type itself can use the one-argument form (#27157) |
---|
1026 | n/a | self.assertIs(type(5), int) |
---|
1027 | n/a | |
---|
1028 | n/a | class M(type): |
---|
1029 | n/a | pass |
---|
1030 | n/a | with self.assertRaises(TypeError) as cm: |
---|
1031 | n/a | M(5) |
---|
1032 | n/a | self.assertEqual(str(cm.exception), expected_message) |
---|
1033 | n/a | |
---|
1034 | n/a | class N(type, metaclass=M): |
---|
1035 | n/a | pass |
---|
1036 | n/a | with self.assertRaises(TypeError) as cm: |
---|
1037 | n/a | N(5) |
---|
1038 | n/a | self.assertEqual(str(cm.exception), expected_message) |
---|
1039 | n/a | |
---|
1040 | n/a | |
---|
1041 | n/a | class SimpleNamespaceTests(unittest.TestCase): |
---|
1042 | n/a | |
---|
1043 | n/a | def test_constructor(self): |
---|
1044 | n/a | ns1 = types.SimpleNamespace() |
---|
1045 | n/a | ns2 = types.SimpleNamespace(x=1, y=2) |
---|
1046 | n/a | ns3 = types.SimpleNamespace(**dict(x=1, y=2)) |
---|
1047 | n/a | |
---|
1048 | n/a | with self.assertRaises(TypeError): |
---|
1049 | n/a | types.SimpleNamespace(1, 2, 3) |
---|
1050 | n/a | |
---|
1051 | n/a | self.assertEqual(len(ns1.__dict__), 0) |
---|
1052 | n/a | self.assertEqual(vars(ns1), {}) |
---|
1053 | n/a | self.assertEqual(len(ns2.__dict__), 2) |
---|
1054 | n/a | self.assertEqual(vars(ns2), {'y': 2, 'x': 1}) |
---|
1055 | n/a | self.assertEqual(len(ns3.__dict__), 2) |
---|
1056 | n/a | self.assertEqual(vars(ns3), {'y': 2, 'x': 1}) |
---|
1057 | n/a | |
---|
1058 | n/a | def test_unbound(self): |
---|
1059 | n/a | ns1 = vars(types.SimpleNamespace()) |
---|
1060 | n/a | ns2 = vars(types.SimpleNamespace(x=1, y=2)) |
---|
1061 | n/a | |
---|
1062 | n/a | self.assertEqual(ns1, {}) |
---|
1063 | n/a | self.assertEqual(ns2, {'y': 2, 'x': 1}) |
---|
1064 | n/a | |
---|
1065 | n/a | def test_underlying_dict(self): |
---|
1066 | n/a | ns1 = types.SimpleNamespace() |
---|
1067 | n/a | ns2 = types.SimpleNamespace(x=1, y=2) |
---|
1068 | n/a | ns3 = types.SimpleNamespace(a=True, b=False) |
---|
1069 | n/a | mapping = ns3.__dict__ |
---|
1070 | n/a | del ns3 |
---|
1071 | n/a | |
---|
1072 | n/a | self.assertEqual(ns1.__dict__, {}) |
---|
1073 | n/a | self.assertEqual(ns2.__dict__, {'y': 2, 'x': 1}) |
---|
1074 | n/a | self.assertEqual(mapping, dict(a=True, b=False)) |
---|
1075 | n/a | |
---|
1076 | n/a | def test_attrget(self): |
---|
1077 | n/a | ns = types.SimpleNamespace(x=1, y=2, w=3) |
---|
1078 | n/a | |
---|
1079 | n/a | self.assertEqual(ns.x, 1) |
---|
1080 | n/a | self.assertEqual(ns.y, 2) |
---|
1081 | n/a | self.assertEqual(ns.w, 3) |
---|
1082 | n/a | with self.assertRaises(AttributeError): |
---|
1083 | n/a | ns.z |
---|
1084 | n/a | |
---|
1085 | n/a | def test_attrset(self): |
---|
1086 | n/a | ns1 = types.SimpleNamespace() |
---|
1087 | n/a | ns2 = types.SimpleNamespace(x=1, y=2, w=3) |
---|
1088 | n/a | ns1.a = 'spam' |
---|
1089 | n/a | ns1.b = 'ham' |
---|
1090 | n/a | ns2.z = 4 |
---|
1091 | n/a | ns2.theta = None |
---|
1092 | n/a | |
---|
1093 | n/a | self.assertEqual(ns1.__dict__, dict(a='spam', b='ham')) |
---|
1094 | n/a | self.assertEqual(ns2.__dict__, dict(x=1, y=2, w=3, z=4, theta=None)) |
---|
1095 | n/a | |
---|
1096 | n/a | def test_attrdel(self): |
---|
1097 | n/a | ns1 = types.SimpleNamespace() |
---|
1098 | n/a | ns2 = types.SimpleNamespace(x=1, y=2, w=3) |
---|
1099 | n/a | |
---|
1100 | n/a | with self.assertRaises(AttributeError): |
---|
1101 | n/a | del ns1.spam |
---|
1102 | n/a | with self.assertRaises(AttributeError): |
---|
1103 | n/a | del ns2.spam |
---|
1104 | n/a | |
---|
1105 | n/a | del ns2.y |
---|
1106 | n/a | self.assertEqual(vars(ns2), dict(w=3, x=1)) |
---|
1107 | n/a | ns2.y = 'spam' |
---|
1108 | n/a | self.assertEqual(vars(ns2), dict(w=3, x=1, y='spam')) |
---|
1109 | n/a | del ns2.y |
---|
1110 | n/a | self.assertEqual(vars(ns2), dict(w=3, x=1)) |
---|
1111 | n/a | |
---|
1112 | n/a | ns1.spam = 5 |
---|
1113 | n/a | self.assertEqual(vars(ns1), dict(spam=5)) |
---|
1114 | n/a | del ns1.spam |
---|
1115 | n/a | self.assertEqual(vars(ns1), {}) |
---|
1116 | n/a | |
---|
1117 | n/a | def test_repr(self): |
---|
1118 | n/a | ns1 = types.SimpleNamespace(x=1, y=2, w=3) |
---|
1119 | n/a | ns2 = types.SimpleNamespace() |
---|
1120 | n/a | ns2.x = "spam" |
---|
1121 | n/a | ns2._y = 5 |
---|
1122 | n/a | name = "namespace" |
---|
1123 | n/a | |
---|
1124 | n/a | self.assertEqual(repr(ns1), "{name}(w=3, x=1, y=2)".format(name=name)) |
---|
1125 | n/a | self.assertEqual(repr(ns2), "{name}(_y=5, x='spam')".format(name=name)) |
---|
1126 | n/a | |
---|
1127 | n/a | def test_equal(self): |
---|
1128 | n/a | ns1 = types.SimpleNamespace(x=1) |
---|
1129 | n/a | ns2 = types.SimpleNamespace() |
---|
1130 | n/a | ns2.x = 1 |
---|
1131 | n/a | |
---|
1132 | n/a | self.assertEqual(types.SimpleNamespace(), types.SimpleNamespace()) |
---|
1133 | n/a | self.assertEqual(ns1, ns2) |
---|
1134 | n/a | self.assertNotEqual(ns2, types.SimpleNamespace()) |
---|
1135 | n/a | |
---|
1136 | n/a | def test_nested(self): |
---|
1137 | n/a | ns1 = types.SimpleNamespace(a=1, b=2) |
---|
1138 | n/a | ns2 = types.SimpleNamespace() |
---|
1139 | n/a | ns3 = types.SimpleNamespace(x=ns1) |
---|
1140 | n/a | ns2.spam = ns1 |
---|
1141 | n/a | ns2.ham = '?' |
---|
1142 | n/a | ns2.spam = ns3 |
---|
1143 | n/a | |
---|
1144 | n/a | self.assertEqual(vars(ns1), dict(a=1, b=2)) |
---|
1145 | n/a | self.assertEqual(vars(ns2), dict(spam=ns3, ham='?')) |
---|
1146 | n/a | self.assertEqual(ns2.spam, ns3) |
---|
1147 | n/a | self.assertEqual(vars(ns3), dict(x=ns1)) |
---|
1148 | n/a | self.assertEqual(ns3.x.a, 1) |
---|
1149 | n/a | |
---|
1150 | n/a | def test_recursive(self): |
---|
1151 | n/a | ns1 = types.SimpleNamespace(c='cookie') |
---|
1152 | n/a | ns2 = types.SimpleNamespace() |
---|
1153 | n/a | ns3 = types.SimpleNamespace(x=1) |
---|
1154 | n/a | ns1.spam = ns1 |
---|
1155 | n/a | ns2.spam = ns3 |
---|
1156 | n/a | ns3.spam = ns2 |
---|
1157 | n/a | |
---|
1158 | n/a | self.assertEqual(ns1.spam, ns1) |
---|
1159 | n/a | self.assertEqual(ns1.spam.spam, ns1) |
---|
1160 | n/a | self.assertEqual(ns1.spam.spam, ns1.spam) |
---|
1161 | n/a | self.assertEqual(ns2.spam, ns3) |
---|
1162 | n/a | self.assertEqual(ns3.spam, ns2) |
---|
1163 | n/a | self.assertEqual(ns2.spam.spam, ns2) |
---|
1164 | n/a | |
---|
1165 | n/a | def test_recursive_repr(self): |
---|
1166 | n/a | ns1 = types.SimpleNamespace(c='cookie') |
---|
1167 | n/a | ns2 = types.SimpleNamespace() |
---|
1168 | n/a | ns3 = types.SimpleNamespace(x=1) |
---|
1169 | n/a | ns1.spam = ns1 |
---|
1170 | n/a | ns2.spam = ns3 |
---|
1171 | n/a | ns3.spam = ns2 |
---|
1172 | n/a | name = "namespace" |
---|
1173 | n/a | repr1 = "{name}(c='cookie', spam={name}(...))".format(name=name) |
---|
1174 | n/a | repr2 = "{name}(spam={name}(spam={name}(...), x=1))".format(name=name) |
---|
1175 | n/a | |
---|
1176 | n/a | self.assertEqual(repr(ns1), repr1) |
---|
1177 | n/a | self.assertEqual(repr(ns2), repr2) |
---|
1178 | n/a | |
---|
1179 | n/a | def test_as_dict(self): |
---|
1180 | n/a | ns = types.SimpleNamespace(spam='spamspamspam') |
---|
1181 | n/a | |
---|
1182 | n/a | with self.assertRaises(TypeError): |
---|
1183 | n/a | len(ns) |
---|
1184 | n/a | with self.assertRaises(TypeError): |
---|
1185 | n/a | iter(ns) |
---|
1186 | n/a | with self.assertRaises(TypeError): |
---|
1187 | n/a | 'spam' in ns |
---|
1188 | n/a | with self.assertRaises(TypeError): |
---|
1189 | n/a | ns['spam'] |
---|
1190 | n/a | |
---|
1191 | n/a | def test_subclass(self): |
---|
1192 | n/a | class Spam(types.SimpleNamespace): |
---|
1193 | n/a | pass |
---|
1194 | n/a | |
---|
1195 | n/a | spam = Spam(ham=8, eggs=9) |
---|
1196 | n/a | |
---|
1197 | n/a | self.assertIs(type(spam), Spam) |
---|
1198 | n/a | self.assertEqual(vars(spam), {'ham': 8, 'eggs': 9}) |
---|
1199 | n/a | |
---|
1200 | n/a | def test_pickle(self): |
---|
1201 | n/a | ns = types.SimpleNamespace(breakfast="spam", lunch="spam") |
---|
1202 | n/a | |
---|
1203 | n/a | for protocol in range(pickle.HIGHEST_PROTOCOL + 1): |
---|
1204 | n/a | pname = "protocol {}".format(protocol) |
---|
1205 | n/a | try: |
---|
1206 | n/a | ns_pickled = pickle.dumps(ns, protocol) |
---|
1207 | n/a | except TypeError as e: |
---|
1208 | n/a | raise TypeError(pname) from e |
---|
1209 | n/a | ns_roundtrip = pickle.loads(ns_pickled) |
---|
1210 | n/a | |
---|
1211 | n/a | self.assertEqual(ns, ns_roundtrip, pname) |
---|
1212 | n/a | |
---|
1213 | n/a | def test_fake_namespace_compare(self): |
---|
1214 | n/a | # Issue #24257: Incorrect use of PyObject_IsInstance() caused |
---|
1215 | n/a | # SystemError. |
---|
1216 | n/a | class FakeSimpleNamespace(str): |
---|
1217 | n/a | __class__ = types.SimpleNamespace |
---|
1218 | n/a | self.assertFalse(types.SimpleNamespace() == FakeSimpleNamespace()) |
---|
1219 | n/a | self.assertTrue(types.SimpleNamespace() != FakeSimpleNamespace()) |
---|
1220 | n/a | with self.assertRaises(TypeError): |
---|
1221 | n/a | types.SimpleNamespace() < FakeSimpleNamespace() |
---|
1222 | n/a | with self.assertRaises(TypeError): |
---|
1223 | n/a | types.SimpleNamespace() <= FakeSimpleNamespace() |
---|
1224 | n/a | with self.assertRaises(TypeError): |
---|
1225 | n/a | types.SimpleNamespace() > FakeSimpleNamespace() |
---|
1226 | n/a | with self.assertRaises(TypeError): |
---|
1227 | n/a | types.SimpleNamespace() >= FakeSimpleNamespace() |
---|
1228 | n/a | |
---|
1229 | n/a | |
---|
1230 | n/a | class CoroutineTests(unittest.TestCase): |
---|
1231 | n/a | def test_wrong_args(self): |
---|
1232 | n/a | samples = [None, 1, object()] |
---|
1233 | n/a | for sample in samples: |
---|
1234 | n/a | with self.assertRaisesRegex(TypeError, |
---|
1235 | n/a | 'types.coroutine.*expects a callable'): |
---|
1236 | n/a | types.coroutine(sample) |
---|
1237 | n/a | |
---|
1238 | n/a | def test_non_gen_values(self): |
---|
1239 | n/a | @types.coroutine |
---|
1240 | n/a | def foo(): |
---|
1241 | n/a | return 'spam' |
---|
1242 | n/a | self.assertEqual(foo(), 'spam') |
---|
1243 | n/a | |
---|
1244 | n/a | class Awaitable: |
---|
1245 | n/a | def __await__(self): |
---|
1246 | n/a | return () |
---|
1247 | n/a | aw = Awaitable() |
---|
1248 | n/a | @types.coroutine |
---|
1249 | n/a | def foo(): |
---|
1250 | n/a | return aw |
---|
1251 | n/a | self.assertIs(aw, foo()) |
---|
1252 | n/a | |
---|
1253 | n/a | # decorate foo second time |
---|
1254 | n/a | foo = types.coroutine(foo) |
---|
1255 | n/a | self.assertIs(aw, foo()) |
---|
1256 | n/a | |
---|
1257 | n/a | def test_async_def(self): |
---|
1258 | n/a | # Test that types.coroutine passes 'async def' coroutines |
---|
1259 | n/a | # without modification |
---|
1260 | n/a | |
---|
1261 | n/a | async def foo(): pass |
---|
1262 | n/a | foo_code = foo.__code__ |
---|
1263 | n/a | foo_flags = foo.__code__.co_flags |
---|
1264 | n/a | decorated_foo = types.coroutine(foo) |
---|
1265 | n/a | self.assertIs(foo, decorated_foo) |
---|
1266 | n/a | self.assertEqual(foo.__code__.co_flags, foo_flags) |
---|
1267 | n/a | self.assertIs(decorated_foo.__code__, foo_code) |
---|
1268 | n/a | |
---|
1269 | n/a | foo_coro = foo() |
---|
1270 | n/a | def bar(): return foo_coro |
---|
1271 | n/a | for _ in range(2): |
---|
1272 | n/a | bar = types.coroutine(bar) |
---|
1273 | n/a | coro = bar() |
---|
1274 | n/a | self.assertIs(foo_coro, coro) |
---|
1275 | n/a | self.assertEqual(coro.cr_code.co_flags, foo_flags) |
---|
1276 | n/a | coro.close() |
---|
1277 | n/a | |
---|
1278 | n/a | def test_duck_coro(self): |
---|
1279 | n/a | class CoroLike: |
---|
1280 | n/a | def send(self): pass |
---|
1281 | n/a | def throw(self): pass |
---|
1282 | n/a | def close(self): pass |
---|
1283 | n/a | def __await__(self): return self |
---|
1284 | n/a | |
---|
1285 | n/a | coro = CoroLike() |
---|
1286 | n/a | @types.coroutine |
---|
1287 | n/a | def foo(): |
---|
1288 | n/a | return coro |
---|
1289 | n/a | self.assertIs(foo(), coro) |
---|
1290 | n/a | self.assertIs(foo().__await__(), coro) |
---|
1291 | n/a | |
---|
1292 | n/a | def test_duck_corogen(self): |
---|
1293 | n/a | class CoroGenLike: |
---|
1294 | n/a | def send(self): pass |
---|
1295 | n/a | def throw(self): pass |
---|
1296 | n/a | def close(self): pass |
---|
1297 | n/a | def __await__(self): return self |
---|
1298 | n/a | def __iter__(self): return self |
---|
1299 | n/a | def __next__(self): pass |
---|
1300 | n/a | |
---|
1301 | n/a | coro = CoroGenLike() |
---|
1302 | n/a | @types.coroutine |
---|
1303 | n/a | def foo(): |
---|
1304 | n/a | return coro |
---|
1305 | n/a | self.assertIs(foo(), coro) |
---|
1306 | n/a | self.assertIs(foo().__await__(), coro) |
---|
1307 | n/a | |
---|
1308 | n/a | def test_duck_gen(self): |
---|
1309 | n/a | class GenLike: |
---|
1310 | n/a | def send(self): pass |
---|
1311 | n/a | def throw(self): pass |
---|
1312 | n/a | def close(self): pass |
---|
1313 | n/a | def __iter__(self): pass |
---|
1314 | n/a | def __next__(self): pass |
---|
1315 | n/a | |
---|
1316 | n/a | # Setup generator mock object |
---|
1317 | n/a | gen = unittest.mock.MagicMock(GenLike) |
---|
1318 | n/a | gen.__iter__ = lambda gen: gen |
---|
1319 | n/a | gen.__name__ = 'gen' |
---|
1320 | n/a | gen.__qualname__ = 'test.gen' |
---|
1321 | n/a | self.assertIsInstance(gen, collections.abc.Generator) |
---|
1322 | n/a | self.assertIs(gen, iter(gen)) |
---|
1323 | n/a | |
---|
1324 | n/a | @types.coroutine |
---|
1325 | n/a | def foo(): return gen |
---|
1326 | n/a | |
---|
1327 | n/a | wrapper = foo() |
---|
1328 | n/a | self.assertIsInstance(wrapper, types._GeneratorWrapper) |
---|
1329 | n/a | self.assertIs(wrapper.__await__(), wrapper) |
---|
1330 | n/a | # Wrapper proxies duck generators completely: |
---|
1331 | n/a | self.assertIs(iter(wrapper), wrapper) |
---|
1332 | n/a | |
---|
1333 | n/a | self.assertIsInstance(wrapper, collections.abc.Coroutine) |
---|
1334 | n/a | self.assertIsInstance(wrapper, collections.abc.Awaitable) |
---|
1335 | n/a | |
---|
1336 | n/a | self.assertIs(wrapper.__qualname__, gen.__qualname__) |
---|
1337 | n/a | self.assertIs(wrapper.__name__, gen.__name__) |
---|
1338 | n/a | |
---|
1339 | n/a | # Test AttributeErrors |
---|
1340 | n/a | for name in {'gi_running', 'gi_frame', 'gi_code', 'gi_yieldfrom', |
---|
1341 | n/a | 'cr_running', 'cr_frame', 'cr_code', 'cr_await'}: |
---|
1342 | n/a | with self.assertRaises(AttributeError): |
---|
1343 | n/a | getattr(wrapper, name) |
---|
1344 | n/a | |
---|
1345 | n/a | # Test attributes pass-through |
---|
1346 | n/a | gen.gi_running = object() |
---|
1347 | n/a | gen.gi_frame = object() |
---|
1348 | n/a | gen.gi_code = object() |
---|
1349 | n/a | gen.gi_yieldfrom = object() |
---|
1350 | n/a | self.assertIs(wrapper.gi_running, gen.gi_running) |
---|
1351 | n/a | self.assertIs(wrapper.gi_frame, gen.gi_frame) |
---|
1352 | n/a | self.assertIs(wrapper.gi_code, gen.gi_code) |
---|
1353 | n/a | self.assertIs(wrapper.gi_yieldfrom, gen.gi_yieldfrom) |
---|
1354 | n/a | self.assertIs(wrapper.cr_running, gen.gi_running) |
---|
1355 | n/a | self.assertIs(wrapper.cr_frame, gen.gi_frame) |
---|
1356 | n/a | self.assertIs(wrapper.cr_code, gen.gi_code) |
---|
1357 | n/a | self.assertIs(wrapper.cr_await, gen.gi_yieldfrom) |
---|
1358 | n/a | |
---|
1359 | n/a | wrapper.close() |
---|
1360 | n/a | gen.close.assert_called_once_with() |
---|
1361 | n/a | |
---|
1362 | n/a | wrapper.send(1) |
---|
1363 | n/a | gen.send.assert_called_once_with(1) |
---|
1364 | n/a | gen.reset_mock() |
---|
1365 | n/a | |
---|
1366 | n/a | next(wrapper) |
---|
1367 | n/a | gen.__next__.assert_called_once_with() |
---|
1368 | n/a | gen.reset_mock() |
---|
1369 | n/a | |
---|
1370 | n/a | wrapper.throw(1, 2, 3) |
---|
1371 | n/a | gen.throw.assert_called_once_with(1, 2, 3) |
---|
1372 | n/a | gen.reset_mock() |
---|
1373 | n/a | |
---|
1374 | n/a | wrapper.throw(1, 2) |
---|
1375 | n/a | gen.throw.assert_called_once_with(1, 2) |
---|
1376 | n/a | gen.reset_mock() |
---|
1377 | n/a | |
---|
1378 | n/a | wrapper.throw(1) |
---|
1379 | n/a | gen.throw.assert_called_once_with(1) |
---|
1380 | n/a | gen.reset_mock() |
---|
1381 | n/a | |
---|
1382 | n/a | # Test exceptions propagation |
---|
1383 | n/a | error = Exception() |
---|
1384 | n/a | gen.throw.side_effect = error |
---|
1385 | n/a | try: |
---|
1386 | n/a | wrapper.throw(1) |
---|
1387 | n/a | except Exception as ex: |
---|
1388 | n/a | self.assertIs(ex, error) |
---|
1389 | n/a | else: |
---|
1390 | n/a | self.fail('wrapper did not propagate an exception') |
---|
1391 | n/a | |
---|
1392 | n/a | # Test invalid args |
---|
1393 | n/a | gen.reset_mock() |
---|
1394 | n/a | with self.assertRaises(TypeError): |
---|
1395 | n/a | wrapper.throw() |
---|
1396 | n/a | self.assertFalse(gen.throw.called) |
---|
1397 | n/a | with self.assertRaises(TypeError): |
---|
1398 | n/a | wrapper.close(1) |
---|
1399 | n/a | self.assertFalse(gen.close.called) |
---|
1400 | n/a | with self.assertRaises(TypeError): |
---|
1401 | n/a | wrapper.send() |
---|
1402 | n/a | self.assertFalse(gen.send.called) |
---|
1403 | n/a | |
---|
1404 | n/a | # Test that we do not double wrap |
---|
1405 | n/a | @types.coroutine |
---|
1406 | n/a | def bar(): return wrapper |
---|
1407 | n/a | self.assertIs(wrapper, bar()) |
---|
1408 | n/a | |
---|
1409 | n/a | # Test weakrefs support |
---|
1410 | n/a | ref = weakref.ref(wrapper) |
---|
1411 | n/a | self.assertIs(ref(), wrapper) |
---|
1412 | n/a | |
---|
1413 | n/a | def test_duck_functional_gen(self): |
---|
1414 | n/a | class Generator: |
---|
1415 | n/a | """Emulates the following generator (very clumsy): |
---|
1416 | n/a | |
---|
1417 | n/a | def gen(fut): |
---|
1418 | n/a | result = yield fut |
---|
1419 | n/a | return result * 2 |
---|
1420 | n/a | """ |
---|
1421 | n/a | def __init__(self, fut): |
---|
1422 | n/a | self._i = 0 |
---|
1423 | n/a | self._fut = fut |
---|
1424 | n/a | def __iter__(self): |
---|
1425 | n/a | return self |
---|
1426 | n/a | def __next__(self): |
---|
1427 | n/a | return self.send(None) |
---|
1428 | n/a | def send(self, v): |
---|
1429 | n/a | try: |
---|
1430 | n/a | if self._i == 0: |
---|
1431 | n/a | assert v is None |
---|
1432 | n/a | return self._fut |
---|
1433 | n/a | if self._i == 1: |
---|
1434 | n/a | raise StopIteration(v * 2) |
---|
1435 | n/a | if self._i > 1: |
---|
1436 | n/a | raise StopIteration |
---|
1437 | n/a | finally: |
---|
1438 | n/a | self._i += 1 |
---|
1439 | n/a | def throw(self, tp, *exc): |
---|
1440 | n/a | self._i = 100 |
---|
1441 | n/a | if tp is not GeneratorExit: |
---|
1442 | n/a | raise tp |
---|
1443 | n/a | def close(self): |
---|
1444 | n/a | self.throw(GeneratorExit) |
---|
1445 | n/a | |
---|
1446 | n/a | @types.coroutine |
---|
1447 | n/a | def foo(): return Generator('spam') |
---|
1448 | n/a | |
---|
1449 | n/a | wrapper = foo() |
---|
1450 | n/a | self.assertIsInstance(wrapper, types._GeneratorWrapper) |
---|
1451 | n/a | |
---|
1452 | n/a | async def corofunc(): |
---|
1453 | n/a | return await foo() + 100 |
---|
1454 | n/a | coro = corofunc() |
---|
1455 | n/a | |
---|
1456 | n/a | self.assertEqual(coro.send(None), 'spam') |
---|
1457 | n/a | try: |
---|
1458 | n/a | coro.send(20) |
---|
1459 | n/a | except StopIteration as ex: |
---|
1460 | n/a | self.assertEqual(ex.args[0], 140) |
---|
1461 | n/a | else: |
---|
1462 | n/a | self.fail('StopIteration was expected') |
---|
1463 | n/a | |
---|
1464 | n/a | def test_gen(self): |
---|
1465 | n/a | def gen_func(): |
---|
1466 | n/a | yield 1 |
---|
1467 | n/a | return (yield 2) |
---|
1468 | n/a | gen = gen_func() |
---|
1469 | n/a | @types.coroutine |
---|
1470 | n/a | def foo(): return gen |
---|
1471 | n/a | wrapper = foo() |
---|
1472 | n/a | self.assertIsInstance(wrapper, types._GeneratorWrapper) |
---|
1473 | n/a | self.assertIs(wrapper.__await__(), gen) |
---|
1474 | n/a | |
---|
1475 | n/a | for name in ('__name__', '__qualname__', 'gi_code', |
---|
1476 | n/a | 'gi_running', 'gi_frame'): |
---|
1477 | n/a | self.assertIs(getattr(foo(), name), |
---|
1478 | n/a | getattr(gen, name)) |
---|
1479 | n/a | self.assertIs(foo().cr_code, gen.gi_code) |
---|
1480 | n/a | |
---|
1481 | n/a | self.assertEqual(next(wrapper), 1) |
---|
1482 | n/a | self.assertEqual(wrapper.send(None), 2) |
---|
1483 | n/a | with self.assertRaisesRegex(StopIteration, 'spam'): |
---|
1484 | n/a | wrapper.send('spam') |
---|
1485 | n/a | |
---|
1486 | n/a | gen = gen_func() |
---|
1487 | n/a | wrapper = foo() |
---|
1488 | n/a | wrapper.send(None) |
---|
1489 | n/a | with self.assertRaisesRegex(Exception, 'ham'): |
---|
1490 | n/a | wrapper.throw(Exception, Exception('ham')) |
---|
1491 | n/a | |
---|
1492 | n/a | # decorate foo second time |
---|
1493 | n/a | foo = types.coroutine(foo) |
---|
1494 | n/a | self.assertIs(foo().__await__(), gen) |
---|
1495 | n/a | |
---|
1496 | n/a | def test_returning_itercoro(self): |
---|
1497 | n/a | @types.coroutine |
---|
1498 | n/a | def gen(): |
---|
1499 | n/a | yield |
---|
1500 | n/a | |
---|
1501 | n/a | gencoro = gen() |
---|
1502 | n/a | |
---|
1503 | n/a | @types.coroutine |
---|
1504 | n/a | def foo(): |
---|
1505 | n/a | return gencoro |
---|
1506 | n/a | |
---|
1507 | n/a | self.assertIs(foo(), gencoro) |
---|
1508 | n/a | |
---|
1509 | n/a | # decorate foo second time |
---|
1510 | n/a | foo = types.coroutine(foo) |
---|
1511 | n/a | self.assertIs(foo(), gencoro) |
---|
1512 | n/a | |
---|
1513 | n/a | def test_genfunc(self): |
---|
1514 | n/a | def gen(): yield |
---|
1515 | n/a | self.assertIs(types.coroutine(gen), gen) |
---|
1516 | n/a | self.assertIs(types.coroutine(types.coroutine(gen)), gen) |
---|
1517 | n/a | |
---|
1518 | n/a | self.assertTrue(gen.__code__.co_flags & inspect.CO_ITERABLE_COROUTINE) |
---|
1519 | n/a | self.assertFalse(gen.__code__.co_flags & inspect.CO_COROUTINE) |
---|
1520 | n/a | |
---|
1521 | n/a | g = gen() |
---|
1522 | n/a | self.assertTrue(g.gi_code.co_flags & inspect.CO_ITERABLE_COROUTINE) |
---|
1523 | n/a | self.assertFalse(g.gi_code.co_flags & inspect.CO_COROUTINE) |
---|
1524 | n/a | |
---|
1525 | n/a | self.assertIs(types.coroutine(gen), gen) |
---|
1526 | n/a | |
---|
1527 | n/a | def test_wrapper_object(self): |
---|
1528 | n/a | def gen(): |
---|
1529 | n/a | yield |
---|
1530 | n/a | @types.coroutine |
---|
1531 | n/a | def coro(): |
---|
1532 | n/a | return gen() |
---|
1533 | n/a | |
---|
1534 | n/a | wrapper = coro() |
---|
1535 | n/a | self.assertIn('GeneratorWrapper', repr(wrapper)) |
---|
1536 | n/a | self.assertEqual(repr(wrapper), str(wrapper)) |
---|
1537 | n/a | self.assertTrue(set(dir(wrapper)).issuperset({ |
---|
1538 | n/a | '__await__', '__iter__', '__next__', 'cr_code', 'cr_running', |
---|
1539 | n/a | 'cr_frame', 'gi_code', 'gi_frame', 'gi_running', 'send', |
---|
1540 | n/a | 'close', 'throw'})) |
---|
1541 | n/a | |
---|
1542 | n/a | |
---|
1543 | n/a | if __name__ == '__main__': |
---|
1544 | n/a | unittest.main() |
---|