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

Python code coverage for Lib/test/test_int.py

#countcontent
1n/aimport sys
2n/a
3n/aimport unittest
4n/afrom test import support
5n/afrom test.test_grammar import (VALID_UNDERSCORE_LITERALS,
6n/a INVALID_UNDERSCORE_LITERALS)
7n/a
8n/aL = [
9n/a ('0', 0),
10n/a ('1', 1),
11n/a ('9', 9),
12n/a ('10', 10),
13n/a ('99', 99),
14n/a ('100', 100),
15n/a ('314', 314),
16n/a (' 314', 314),
17n/a ('314 ', 314),
18n/a (' \t\t 314 \t\t ', 314),
19n/a (repr(sys.maxsize), sys.maxsize),
20n/a (' 1x', ValueError),
21n/a (' 1 ', 1),
22n/a (' 1\02 ', ValueError),
23n/a ('', ValueError),
24n/a (' ', ValueError),
25n/a (' \t\t ', ValueError),
26n/a ("\u0200", ValueError)
27n/a]
28n/a
29n/aclass IntSubclass(int):
30n/a pass
31n/a
32n/aclass IntTestCases(unittest.TestCase):
33n/a
34n/a def test_basic(self):
35n/a self.assertEqual(int(314), 314)
36n/a self.assertEqual(int(3.14), 3)
37n/a # Check that conversion from float truncates towards zero
38n/a self.assertEqual(int(-3.14), -3)
39n/a self.assertEqual(int(3.9), 3)
40n/a self.assertEqual(int(-3.9), -3)
41n/a self.assertEqual(int(3.5), 3)
42n/a self.assertEqual(int(-3.5), -3)
43n/a self.assertEqual(int("-3"), -3)
44n/a self.assertEqual(int(" -3 "), -3)
45n/a self.assertEqual(int("\N{EM SPACE}-3\N{EN SPACE}"), -3)
46n/a # Different base:
47n/a self.assertEqual(int("10",16), 16)
48n/a # Test conversion from strings and various anomalies
49n/a for s, v in L:
50n/a for sign in "", "+", "-":
51n/a for prefix in "", " ", "\t", " \t\t ":
52n/a ss = prefix + sign + s
53n/a vv = v
54n/a if sign == "-" and v is not ValueError:
55n/a vv = -v
56n/a try:
57n/a self.assertEqual(int(ss), vv)
58n/a except ValueError:
59n/a pass
60n/a
61n/a s = repr(-1-sys.maxsize)
62n/a x = int(s)
63n/a self.assertEqual(x+1, -sys.maxsize)
64n/a self.assertIsInstance(x, int)
65n/a # should return int
66n/a self.assertEqual(int(s[1:]), sys.maxsize+1)
67n/a
68n/a # should return int
69n/a x = int(1e100)
70n/a self.assertIsInstance(x, int)
71n/a x = int(-1e100)
72n/a self.assertIsInstance(x, int)
73n/a
74n/a
75n/a # SF bug 434186: 0x80000000/2 != 0x80000000>>1.
76n/a # Worked by accident in Windows release build, but failed in debug build.
77n/a # Failed in all Linux builds.
78n/a x = -1-sys.maxsize
79n/a self.assertEqual(x >> 1, x//2)
80n/a
81n/a x = int('1' * 600)
82n/a self.assertIsInstance(x, int)
83n/a
84n/a
85n/a self.assertRaises(TypeError, int, 1, 12)
86n/a
87n/a self.assertEqual(int('0o123', 0), 83)
88n/a self.assertEqual(int('0x123', 16), 291)
89n/a
90n/a # Bug 1679: "0x" is not a valid hex literal
91n/a self.assertRaises(ValueError, int, "0x", 16)
92n/a self.assertRaises(ValueError, int, "0x", 0)
93n/a
94n/a self.assertRaises(ValueError, int, "0o", 8)
95n/a self.assertRaises(ValueError, int, "0o", 0)
96n/a
97n/a self.assertRaises(ValueError, int, "0b", 2)
98n/a self.assertRaises(ValueError, int, "0b", 0)
99n/a
100n/a # SF bug 1334662: int(string, base) wrong answers
101n/a # Various representations of 2**32 evaluated to 0
102n/a # rather than 2**32 in previous versions
103n/a
104n/a self.assertEqual(int('100000000000000000000000000000000', 2), 4294967296)
105n/a self.assertEqual(int('102002022201221111211', 3), 4294967296)
106n/a self.assertEqual(int('10000000000000000', 4), 4294967296)
107n/a self.assertEqual(int('32244002423141', 5), 4294967296)
108n/a self.assertEqual(int('1550104015504', 6), 4294967296)
109n/a self.assertEqual(int('211301422354', 7), 4294967296)
110n/a self.assertEqual(int('40000000000', 8), 4294967296)
111n/a self.assertEqual(int('12068657454', 9), 4294967296)
112n/a self.assertEqual(int('4294967296', 10), 4294967296)
113n/a self.assertEqual(int('1904440554', 11), 4294967296)
114n/a self.assertEqual(int('9ba461594', 12), 4294967296)
115n/a self.assertEqual(int('535a79889', 13), 4294967296)
116n/a self.assertEqual(int('2ca5b7464', 14), 4294967296)
117n/a self.assertEqual(int('1a20dcd81', 15), 4294967296)
118n/a self.assertEqual(int('100000000', 16), 4294967296)
119n/a self.assertEqual(int('a7ffda91', 17), 4294967296)
120n/a self.assertEqual(int('704he7g4', 18), 4294967296)
121n/a self.assertEqual(int('4f5aff66', 19), 4294967296)
122n/a self.assertEqual(int('3723ai4g', 20), 4294967296)
123n/a self.assertEqual(int('281d55i4', 21), 4294967296)
124n/a self.assertEqual(int('1fj8b184', 22), 4294967296)
125n/a self.assertEqual(int('1606k7ic', 23), 4294967296)
126n/a self.assertEqual(int('mb994ag', 24), 4294967296)
127n/a self.assertEqual(int('hek2mgl', 25), 4294967296)
128n/a self.assertEqual(int('dnchbnm', 26), 4294967296)
129n/a self.assertEqual(int('b28jpdm', 27), 4294967296)
130n/a self.assertEqual(int('8pfgih4', 28), 4294967296)
131n/a self.assertEqual(int('76beigg', 29), 4294967296)
132n/a self.assertEqual(int('5qmcpqg', 30), 4294967296)
133n/a self.assertEqual(int('4q0jto4', 31), 4294967296)
134n/a self.assertEqual(int('4000000', 32), 4294967296)
135n/a self.assertEqual(int('3aokq94', 33), 4294967296)
136n/a self.assertEqual(int('2qhxjli', 34), 4294967296)
137n/a self.assertEqual(int('2br45qb', 35), 4294967296)
138n/a self.assertEqual(int('1z141z4', 36), 4294967296)
139n/a
140n/a # tests with base 0
141n/a # this fails on 3.0, but in 2.x the old octal syntax is allowed
142n/a self.assertEqual(int(' 0o123 ', 0), 83)
143n/a self.assertEqual(int(' 0o123 ', 0), 83)
144n/a self.assertEqual(int('000', 0), 0)
145n/a self.assertEqual(int('0o123', 0), 83)
146n/a self.assertEqual(int('0x123', 0), 291)
147n/a self.assertEqual(int('0b100', 0), 4)
148n/a self.assertEqual(int(' 0O123 ', 0), 83)
149n/a self.assertEqual(int(' 0X123 ', 0), 291)
150n/a self.assertEqual(int(' 0B100 ', 0), 4)
151n/a
152n/a # without base still base 10
153n/a self.assertEqual(int('0123'), 123)
154n/a self.assertEqual(int('0123', 10), 123)
155n/a
156n/a # tests with prefix and base != 0
157n/a self.assertEqual(int('0x123', 16), 291)
158n/a self.assertEqual(int('0o123', 8), 83)
159n/a self.assertEqual(int('0b100', 2), 4)
160n/a self.assertEqual(int('0X123', 16), 291)
161n/a self.assertEqual(int('0O123', 8), 83)
162n/a self.assertEqual(int('0B100', 2), 4)
163n/a
164n/a # the code has special checks for the first character after the
165n/a # type prefix
166n/a self.assertRaises(ValueError, int, '0b2', 2)
167n/a self.assertRaises(ValueError, int, '0b02', 2)
168n/a self.assertRaises(ValueError, int, '0B2', 2)
169n/a self.assertRaises(ValueError, int, '0B02', 2)
170n/a self.assertRaises(ValueError, int, '0o8', 8)
171n/a self.assertRaises(ValueError, int, '0o08', 8)
172n/a self.assertRaises(ValueError, int, '0O8', 8)
173n/a self.assertRaises(ValueError, int, '0O08', 8)
174n/a self.assertRaises(ValueError, int, '0xg', 16)
175n/a self.assertRaises(ValueError, int, '0x0g', 16)
176n/a self.assertRaises(ValueError, int, '0Xg', 16)
177n/a self.assertRaises(ValueError, int, '0X0g', 16)
178n/a
179n/a # SF bug 1334662: int(string, base) wrong answers
180n/a # Checks for proper evaluation of 2**32 + 1
181n/a self.assertEqual(int('100000000000000000000000000000001', 2), 4294967297)
182n/a self.assertEqual(int('102002022201221111212', 3), 4294967297)
183n/a self.assertEqual(int('10000000000000001', 4), 4294967297)
184n/a self.assertEqual(int('32244002423142', 5), 4294967297)
185n/a self.assertEqual(int('1550104015505', 6), 4294967297)
186n/a self.assertEqual(int('211301422355', 7), 4294967297)
187n/a self.assertEqual(int('40000000001', 8), 4294967297)
188n/a self.assertEqual(int('12068657455', 9), 4294967297)
189n/a self.assertEqual(int('4294967297', 10), 4294967297)
190n/a self.assertEqual(int('1904440555', 11), 4294967297)
191n/a self.assertEqual(int('9ba461595', 12), 4294967297)
192n/a self.assertEqual(int('535a7988a', 13), 4294967297)
193n/a self.assertEqual(int('2ca5b7465', 14), 4294967297)
194n/a self.assertEqual(int('1a20dcd82', 15), 4294967297)
195n/a self.assertEqual(int('100000001', 16), 4294967297)
196n/a self.assertEqual(int('a7ffda92', 17), 4294967297)
197n/a self.assertEqual(int('704he7g5', 18), 4294967297)
198n/a self.assertEqual(int('4f5aff67', 19), 4294967297)
199n/a self.assertEqual(int('3723ai4h', 20), 4294967297)
200n/a self.assertEqual(int('281d55i5', 21), 4294967297)
201n/a self.assertEqual(int('1fj8b185', 22), 4294967297)
202n/a self.assertEqual(int('1606k7id', 23), 4294967297)
203n/a self.assertEqual(int('mb994ah', 24), 4294967297)
204n/a self.assertEqual(int('hek2mgm', 25), 4294967297)
205n/a self.assertEqual(int('dnchbnn', 26), 4294967297)
206n/a self.assertEqual(int('b28jpdn', 27), 4294967297)
207n/a self.assertEqual(int('8pfgih5', 28), 4294967297)
208n/a self.assertEqual(int('76beigh', 29), 4294967297)
209n/a self.assertEqual(int('5qmcpqh', 30), 4294967297)
210n/a self.assertEqual(int('4q0jto5', 31), 4294967297)
211n/a self.assertEqual(int('4000001', 32), 4294967297)
212n/a self.assertEqual(int('3aokq95', 33), 4294967297)
213n/a self.assertEqual(int('2qhxjlj', 34), 4294967297)
214n/a self.assertEqual(int('2br45qc', 35), 4294967297)
215n/a self.assertEqual(int('1z141z5', 36), 4294967297)
216n/a
217n/a def test_underscores(self):
218n/a for lit in VALID_UNDERSCORE_LITERALS:
219n/a if any(ch in lit for ch in '.eEjJ'):
220n/a continue
221n/a self.assertEqual(int(lit, 0), eval(lit))
222n/a self.assertEqual(int(lit, 0), int(lit.replace('_', ''), 0))
223n/a for lit in INVALID_UNDERSCORE_LITERALS:
224n/a if any(ch in lit for ch in '.eEjJ'):
225n/a continue
226n/a self.assertRaises(ValueError, int, lit, 0)
227n/a # Additional test cases with bases != 0, only for the constructor:
228n/a self.assertEqual(int("1_00", 3), 9)
229n/a self.assertEqual(int("0_100"), 100) # not valid as a literal!
230n/a self.assertEqual(int(b"1_00"), 100) # byte underscore
231n/a self.assertRaises(ValueError, int, "_100")
232n/a self.assertRaises(ValueError, int, "+_100")
233n/a self.assertRaises(ValueError, int, "1__00")
234n/a self.assertRaises(ValueError, int, "100_")
235n/a
236n/a @support.cpython_only
237n/a def test_small_ints(self):
238n/a # Bug #3236: Return small longs from PyLong_FromString
239n/a self.assertIs(int('10'), 10)
240n/a self.assertIs(int('-1'), -1)
241n/a self.assertIs(int(b'10'), 10)
242n/a self.assertIs(int(b'-1'), -1)
243n/a
244n/a def test_no_args(self):
245n/a self.assertEqual(int(), 0)
246n/a
247n/a def test_keyword_args(self):
248n/a # Test invoking int() using keyword arguments.
249n/a self.assertEqual(int(x=1.2), 1)
250n/a self.assertEqual(int('100', base=2), 4)
251n/a self.assertEqual(int(x='100', base=2), 4)
252n/a self.assertRaises(TypeError, int, base=10)
253n/a self.assertRaises(TypeError, int, base=0)
254n/a
255n/a def test_int_base_limits(self):
256n/a """Testing the supported limits of the int() base parameter."""
257n/a self.assertEqual(int('0', 5), 0)
258n/a with self.assertRaises(ValueError):
259n/a int('0', 1)
260n/a with self.assertRaises(ValueError):
261n/a int('0', 37)
262n/a with self.assertRaises(ValueError):
263n/a int('0', -909) # An old magic value base from Python 2.
264n/a with self.assertRaises(ValueError):
265n/a int('0', base=0-(2**234))
266n/a with self.assertRaises(ValueError):
267n/a int('0', base=2**234)
268n/a # Bases 2 through 36 are supported.
269n/a for base in range(2,37):
270n/a self.assertEqual(int('0', base=base), 0)
271n/a
272n/a def test_int_base_bad_types(self):
273n/a """Not integer types are not valid bases; issue16772."""
274n/a with self.assertRaises(TypeError):
275n/a int('0', 5.5)
276n/a with self.assertRaises(TypeError):
277n/a int('0', 5.0)
278n/a
279n/a def test_int_base_indexable(self):
280n/a class MyIndexable(object):
281n/a def __init__(self, value):
282n/a self.value = value
283n/a def __index__(self):
284n/a return self.value
285n/a
286n/a # Check out of range bases.
287n/a for base in 2**100, -2**100, 1, 37:
288n/a with self.assertRaises(ValueError):
289n/a int('43', base)
290n/a
291n/a # Check in-range bases.
292n/a self.assertEqual(int('101', base=MyIndexable(2)), 5)
293n/a self.assertEqual(int('101', base=MyIndexable(10)), 101)
294n/a self.assertEqual(int('101', base=MyIndexable(36)), 1 + 36**2)
295n/a
296n/a def test_non_numeric_input_types(self):
297n/a # Test possible non-numeric types for the argument x, including
298n/a # subclasses of the explicitly documented accepted types.
299n/a class CustomStr(str): pass
300n/a class CustomBytes(bytes): pass
301n/a class CustomByteArray(bytearray): pass
302n/a
303n/a factories = [
304n/a bytes,
305n/a bytearray,
306n/a lambda b: CustomStr(b.decode()),
307n/a CustomBytes,
308n/a CustomByteArray,
309n/a memoryview,
310n/a ]
311n/a try:
312n/a from array import array
313n/a except ImportError:
314n/a pass
315n/a else:
316n/a factories.append(lambda b: array('B', b))
317n/a
318n/a for f in factories:
319n/a x = f(b'100')
320n/a with self.subTest(type(x)):
321n/a self.assertEqual(int(x), 100)
322n/a if isinstance(x, (str, bytes, bytearray)):
323n/a self.assertEqual(int(x, 2), 4)
324n/a else:
325n/a msg = "can't convert non-string"
326n/a with self.assertRaisesRegex(TypeError, msg):
327n/a int(x, 2)
328n/a with self.assertRaisesRegex(ValueError, 'invalid literal'):
329n/a int(f(b'A' * 0x10))
330n/a
331n/a def test_int_memoryview(self):
332n/a self.assertEqual(int(memoryview(b'123')[1:3]), 23)
333n/a self.assertEqual(int(memoryview(b'123\x00')[1:3]), 23)
334n/a self.assertEqual(int(memoryview(b'123 ')[1:3]), 23)
335n/a self.assertEqual(int(memoryview(b'123A')[1:3]), 23)
336n/a self.assertEqual(int(memoryview(b'1234')[1:3]), 23)
337n/a
338n/a def test_string_float(self):
339n/a self.assertRaises(ValueError, int, '1.2')
340n/a
341n/a def test_intconversion(self):
342n/a # Test __int__()
343n/a class ClassicMissingMethods:
344n/a pass
345n/a self.assertRaises(TypeError, int, ClassicMissingMethods())
346n/a
347n/a class MissingMethods(object):
348n/a pass
349n/a self.assertRaises(TypeError, int, MissingMethods())
350n/a
351n/a class Foo0:
352n/a def __int__(self):
353n/a return 42
354n/a
355n/a self.assertEqual(int(Foo0()), 42)
356n/a
357n/a class Classic:
358n/a pass
359n/a for base in (object, Classic):
360n/a class IntOverridesTrunc(base):
361n/a def __int__(self):
362n/a return 42
363n/a def __trunc__(self):
364n/a return -12
365n/a self.assertEqual(int(IntOverridesTrunc()), 42)
366n/a
367n/a class JustTrunc(base):
368n/a def __trunc__(self):
369n/a return 42
370n/a self.assertEqual(int(JustTrunc()), 42)
371n/a
372n/a class ExceptionalTrunc(base):
373n/a def __trunc__(self):
374n/a 1 / 0
375n/a with self.assertRaises(ZeroDivisionError):
376n/a int(ExceptionalTrunc())
377n/a
378n/a for trunc_result_base in (object, Classic):
379n/a class Integral(trunc_result_base):
380n/a def __int__(self):
381n/a return 42
382n/a
383n/a class TruncReturnsNonInt(base):
384n/a def __trunc__(self):
385n/a return Integral()
386n/a self.assertEqual(int(TruncReturnsNonInt()), 42)
387n/a
388n/a class NonIntegral(trunc_result_base):
389n/a def __trunc__(self):
390n/a # Check that we avoid infinite recursion.
391n/a return NonIntegral()
392n/a
393n/a class TruncReturnsNonIntegral(base):
394n/a def __trunc__(self):
395n/a return NonIntegral()
396n/a try:
397n/a int(TruncReturnsNonIntegral())
398n/a except TypeError as e:
399n/a self.assertEqual(str(e),
400n/a "__trunc__ returned non-Integral"
401n/a " (type NonIntegral)")
402n/a else:
403n/a self.fail("Failed to raise TypeError with %s" %
404n/a ((base, trunc_result_base),))
405n/a
406n/a # Regression test for bugs.python.org/issue16060.
407n/a class BadInt(trunc_result_base):
408n/a def __int__(self):
409n/a return 42.0
410n/a
411n/a class TruncReturnsBadInt(base):
412n/a def __trunc__(self):
413n/a return BadInt()
414n/a
415n/a with self.assertRaises(TypeError):
416n/a int(TruncReturnsBadInt())
417n/a
418n/a def test_int_subclass_with_int(self):
419n/a class MyInt(int):
420n/a def __int__(self):
421n/a return 42
422n/a
423n/a class BadInt(int):
424n/a def __int__(self):
425n/a return 42.0
426n/a
427n/a my_int = MyInt(7)
428n/a self.assertEqual(my_int, 7)
429n/a self.assertEqual(int(my_int), 42)
430n/a
431n/a self.assertRaises(TypeError, int, BadInt())
432n/a
433n/a def test_int_returns_int_subclass(self):
434n/a class BadInt:
435n/a def __int__(self):
436n/a return True
437n/a
438n/a class BadInt2(int):
439n/a def __int__(self):
440n/a return True
441n/a
442n/a class TruncReturnsBadInt:
443n/a def __trunc__(self):
444n/a return BadInt()
445n/a
446n/a class TruncReturnsIntSubclass:
447n/a def __trunc__(self):
448n/a return True
449n/a
450n/a bad_int = BadInt()
451n/a with self.assertWarns(DeprecationWarning):
452n/a n = int(bad_int)
453n/a self.assertEqual(n, 1)
454n/a self.assertIs(type(n), int)
455n/a
456n/a bad_int = BadInt2()
457n/a with self.assertWarns(DeprecationWarning):
458n/a n = int(bad_int)
459n/a self.assertEqual(n, 1)
460n/a self.assertIs(type(n), int)
461n/a
462n/a bad_int = TruncReturnsBadInt()
463n/a with self.assertWarns(DeprecationWarning):
464n/a n = int(bad_int)
465n/a self.assertEqual(n, 1)
466n/a self.assertIs(type(n), int)
467n/a
468n/a good_int = TruncReturnsIntSubclass()
469n/a n = int(good_int)
470n/a self.assertEqual(n, 1)
471n/a self.assertIs(type(n), int)
472n/a n = IntSubclass(good_int)
473n/a self.assertEqual(n, 1)
474n/a self.assertIs(type(n), IntSubclass)
475n/a
476n/a def test_error_message(self):
477n/a def check(s, base=None):
478n/a with self.assertRaises(ValueError,
479n/a msg="int(%r, %r)" % (s, base)) as cm:
480n/a if base is None:
481n/a int(s)
482n/a else:
483n/a int(s, base)
484n/a self.assertEqual(cm.exception.args[0],
485n/a "invalid literal for int() with base %d: %r" %
486n/a (10 if base is None else base, s))
487n/a
488n/a check('\xbd')
489n/a check('123\xbd')
490n/a check(' 123 456 ')
491n/a
492n/a check('123\x00')
493n/a # SF bug 1545497: embedded NULs were not detected with explicit base
494n/a check('123\x00', 10)
495n/a check('123\x00 245', 20)
496n/a check('123\x00 245', 16)
497n/a check('123\x00245', 20)
498n/a check('123\x00245', 16)
499n/a # byte string with embedded NUL
500n/a check(b'123\x00')
501n/a check(b'123\x00', 10)
502n/a # non-UTF-8 byte string
503n/a check(b'123\xbd')
504n/a check(b'123\xbd', 10)
505n/a # lone surrogate in Unicode string
506n/a check('123\ud800')
507n/a check('123\ud800', 10)
508n/a
509n/aif __name__ == "__main__":
510n/a unittest.main()