ยปCore Development>Code coverage>Lib/test/test_types.py

Python code coverage for Lib/test/test_types.py

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