»Core Development>Code coverage>Lib/test/test_builtin.py

Python code coverage for Lib/test/test_builtin.py

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