/Lib/test/test_long.py

http://unladen-swallow.googlecode.com/ · Python · 759 lines · 617 code · 87 blank · 55 comment · 82 complexity · 93fe95a83e1b3361b078198e392c0774 MD5 · raw file

  1. import unittest
  2. from test import test_support
  3. import sys
  4. import random
  5. # Used for lazy formatting of failure messages
  6. class Frm(object):
  7. def __init__(self, format, *args):
  8. self.format = format
  9. self.args = args
  10. def __str__(self):
  11. return self.format % self.args
  12. # SHIFT should match the value in longintrepr.h for best testing.
  13. SHIFT = 15
  14. BASE = 2 ** SHIFT
  15. MASK = BASE - 1
  16. KARATSUBA_CUTOFF = 70 # from longobject.c
  17. # Max number of base BASE digits to use in test cases. Doubling
  18. # this will more than double the runtime.
  19. MAXDIGITS = 15
  20. # build some special values
  21. special = map(long, [0, 1, 2, BASE, BASE >> 1])
  22. special.append(0x5555555555555555L)
  23. special.append(0xaaaaaaaaaaaaaaaaL)
  24. # some solid strings of one bits
  25. p2 = 4L # 0 and 1 already added
  26. for i in range(2*SHIFT):
  27. special.append(p2 - 1)
  28. p2 = p2 << 1
  29. del p2
  30. # add complements & negations
  31. special = special + map(lambda x: ~x, special) + \
  32. map(lambda x: -x, special)
  33. L = [
  34. ('0', 0),
  35. ('1', 1),
  36. ('9', 9),
  37. ('10', 10),
  38. ('99', 99),
  39. ('100', 100),
  40. ('314', 314),
  41. (' 314', 314),
  42. ('314 ', 314),
  43. (' \t\t 314 \t\t ', 314),
  44. (repr(sys.maxint), sys.maxint),
  45. (' 1x', ValueError),
  46. (' 1 ', 1),
  47. (' 1\02 ', ValueError),
  48. ('', ValueError),
  49. (' ', ValueError),
  50. (' \t\t ', ValueError)
  51. ]
  52. if test_support.have_unicode:
  53. L += [
  54. (unicode('0'), 0),
  55. (unicode('1'), 1),
  56. (unicode('9'), 9),
  57. (unicode('10'), 10),
  58. (unicode('99'), 99),
  59. (unicode('100'), 100),
  60. (unicode('314'), 314),
  61. (unicode(' 314'), 314),
  62. (unicode('\u0663\u0661\u0664 ','raw-unicode-escape'), 314),
  63. (unicode(' \t\t 314 \t\t '), 314),
  64. (unicode(' 1x'), ValueError),
  65. (unicode(' 1 '), 1),
  66. (unicode(' 1\02 '), ValueError),
  67. (unicode(''), ValueError),
  68. (unicode(' '), ValueError),
  69. (unicode(' \t\t '), ValueError),
  70. (unichr(0x200), ValueError),
  71. ]
  72. class LongTest(unittest.TestCase):
  73. # Get quasi-random long consisting of ndigits digits (in base BASE).
  74. # quasi == the most-significant digit will not be 0, and the number
  75. # is constructed to contain long strings of 0 and 1 bits. These are
  76. # more likely than random bits to provoke digit-boundary errors.
  77. # The sign of the number is also random.
  78. def getran(self, ndigits):
  79. self.assert_(ndigits > 0)
  80. nbits_hi = ndigits * SHIFT
  81. nbits_lo = nbits_hi - SHIFT + 1
  82. answer = 0L
  83. nbits = 0
  84. r = int(random.random() * (SHIFT * 2)) | 1 # force 1 bits to start
  85. while nbits < nbits_lo:
  86. bits = (r >> 1) + 1
  87. bits = min(bits, nbits_hi - nbits)
  88. self.assert_(1 <= bits <= SHIFT)
  89. nbits = nbits + bits
  90. answer = answer << bits
  91. if r & 1:
  92. answer = answer | ((1 << bits) - 1)
  93. r = int(random.random() * (SHIFT * 2))
  94. self.assert_(nbits_lo <= nbits <= nbits_hi)
  95. if random.random() < 0.5:
  96. answer = -answer
  97. return answer
  98. # Get random long consisting of ndigits random digits (relative to base
  99. # BASE). The sign bit is also random.
  100. def getran2(ndigits):
  101. answer = 0L
  102. for i in xrange(ndigits):
  103. answer = (answer << SHIFT) | random.randint(0, MASK)
  104. if random.random() < 0.5:
  105. answer = -answer
  106. return answer
  107. def check_division(self, x, y):
  108. eq = self.assertEqual
  109. q, r = divmod(x, y)
  110. q2, r2 = x//y, x%y
  111. pab, pba = x*y, y*x
  112. eq(pab, pba, Frm("multiplication does not commute for %r and %r", x, y))
  113. eq(q, q2, Frm("divmod returns different quotient than / for %r and %r", x, y))
  114. eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
  115. eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
  116. if y > 0:
  117. self.assert_(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
  118. else:
  119. self.assert_(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
  120. def test_division(self):
  121. digits = range(1, MAXDIGITS+1) + range(KARATSUBA_CUTOFF,
  122. KARATSUBA_CUTOFF + 14)
  123. digits.append(KARATSUBA_CUTOFF * 3)
  124. for lenx in digits:
  125. x = self.getran(lenx)
  126. for leny in digits:
  127. y = self.getran(leny) or 1L
  128. self.check_division(x, y)
  129. def test_karatsuba(self):
  130. digits = range(1, 5) + range(KARATSUBA_CUTOFF, KARATSUBA_CUTOFF + 10)
  131. digits.extend([KARATSUBA_CUTOFF * 10, KARATSUBA_CUTOFF * 100])
  132. bits = [digit * SHIFT for digit in digits]
  133. # Test products of long strings of 1 bits -- (2**x-1)*(2**y-1) ==
  134. # 2**(x+y) - 2**x - 2**y + 1, so the proper result is easy to check.
  135. for abits in bits:
  136. a = (1L << abits) - 1
  137. for bbits in bits:
  138. if bbits < abits:
  139. continue
  140. b = (1L << bbits) - 1
  141. x = a * b
  142. y = ((1L << (abits + bbits)) -
  143. (1L << abits) -
  144. (1L << bbits) +
  145. 1)
  146. self.assertEqual(x, y,
  147. Frm("bad result for a*b: a=%r, b=%r, x=%r, y=%r", a, b, x, y))
  148. def check_bitop_identities_1(self, x):
  149. eq = self.assertEqual
  150. eq(x & 0, 0, Frm("x & 0 != 0 for x=%r", x))
  151. eq(x | 0, x, Frm("x | 0 != x for x=%r", x))
  152. eq(x ^ 0, x, Frm("x ^ 0 != x for x=%r", x))
  153. eq(x & -1, x, Frm("x & -1 != x for x=%r", x))
  154. eq(x | -1, -1, Frm("x | -1 != -1 for x=%r", x))
  155. eq(x ^ -1, ~x, Frm("x ^ -1 != ~x for x=%r", x))
  156. eq(x, ~~x, Frm("x != ~~x for x=%r", x))
  157. eq(x & x, x, Frm("x & x != x for x=%r", x))
  158. eq(x | x, x, Frm("x | x != x for x=%r", x))
  159. eq(x ^ x, 0, Frm("x ^ x != 0 for x=%r", x))
  160. eq(x & ~x, 0, Frm("x & ~x != 0 for x=%r", x))
  161. eq(x | ~x, -1, Frm("x | ~x != -1 for x=%r", x))
  162. eq(x ^ ~x, -1, Frm("x ^ ~x != -1 for x=%r", x))
  163. eq(-x, 1 + ~x, Frm("not -x == 1 + ~x for x=%r", x))
  164. eq(-x, ~(x-1), Frm("not -x == ~(x-1) forx =%r", x))
  165. for n in xrange(2*SHIFT):
  166. p2 = 2L ** n
  167. eq(x << n >> n, x,
  168. Frm("x << n >> n != x for x=%r, n=%r", (x, n)))
  169. eq(x // p2, x >> n,
  170. Frm("x // p2 != x >> n for x=%r n=%r p2=%r", (x, n, p2)))
  171. eq(x * p2, x << n,
  172. Frm("x * p2 != x << n for x=%r n=%r p2=%r", (x, n, p2)))
  173. eq(x & -p2, x >> n << n,
  174. Frm("not x & -p2 == x >> n << n for x=%r n=%r p2=%r", (x, n, p2)))
  175. eq(x & -p2, x & ~(p2 - 1),
  176. Frm("not x & -p2 == x & ~(p2 - 1) for x=%r n=%r p2=%r", (x, n, p2)))
  177. def check_bitop_identities_2(self, x, y):
  178. eq = self.assertEqual
  179. eq(x & y, y & x, Frm("x & y != y & x for x=%r, y=%r", (x, y)))
  180. eq(x | y, y | x, Frm("x | y != y | x for x=%r, y=%r", (x, y)))
  181. eq(x ^ y, y ^ x, Frm("x ^ y != y ^ x for x=%r, y=%r", (x, y)))
  182. eq(x ^ y ^ x, y, Frm("x ^ y ^ x != y for x=%r, y=%r", (x, y)))
  183. eq(x & y, ~(~x | ~y), Frm("x & y != ~(~x | ~y) for x=%r, y=%r", (x, y)))
  184. eq(x | y, ~(~x & ~y), Frm("x | y != ~(~x & ~y) for x=%r, y=%r", (x, y)))
  185. eq(x ^ y, (x | y) & ~(x & y),
  186. Frm("x ^ y != (x | y) & ~(x & y) for x=%r, y=%r", (x, y)))
  187. eq(x ^ y, (x & ~y) | (~x & y),
  188. Frm("x ^ y == (x & ~y) | (~x & y) for x=%r, y=%r", (x, y)))
  189. eq(x ^ y, (x | y) & (~x | ~y),
  190. Frm("x ^ y == (x | y) & (~x | ~y) for x=%r, y=%r", (x, y)))
  191. def check_bitop_identities_3(self, x, y, z):
  192. eq = self.assertEqual
  193. eq((x & y) & z, x & (y & z),
  194. Frm("(x & y) & z != x & (y & z) for x=%r, y=%r, z=%r", (x, y, z)))
  195. eq((x | y) | z, x | (y | z),
  196. Frm("(x | y) | z != x | (y | z) for x=%r, y=%r, z=%r", (x, y, z)))
  197. eq((x ^ y) ^ z, x ^ (y ^ z),
  198. Frm("(x ^ y) ^ z != x ^ (y ^ z) for x=%r, y=%r, z=%r", (x, y, z)))
  199. eq(x & (y | z), (x & y) | (x & z),
  200. Frm("x & (y | z) != (x & y) | (x & z) for x=%r, y=%r, z=%r", (x, y, z)))
  201. eq(x | (y & z), (x | y) & (x | z),
  202. Frm("x | (y & z) != (x | y) & (x | z) for x=%r, y=%r, z=%r", (x, y, z)))
  203. def test_bitop_identities(self):
  204. for x in special:
  205. self.check_bitop_identities_1(x)
  206. digits = xrange(1, MAXDIGITS+1)
  207. for lenx in digits:
  208. x = self.getran(lenx)
  209. self.check_bitop_identities_1(x)
  210. for leny in digits:
  211. y = self.getran(leny)
  212. self.check_bitop_identities_2(x, y)
  213. self.check_bitop_identities_3(x, y, self.getran((lenx + leny)//2))
  214. def slow_format(self, x, base):
  215. if (x, base) == (0, 8):
  216. # this is an oddball!
  217. return "0L"
  218. digits = []
  219. sign = 0
  220. if x < 0:
  221. sign, x = 1, -x
  222. while x:
  223. x, r = divmod(x, base)
  224. digits.append(int(r))
  225. digits.reverse()
  226. digits = digits or [0]
  227. return '-'[:sign] + \
  228. {8: '0', 10: '', 16: '0x'}[base] + \
  229. "".join(map(lambda i: "0123456789abcdef"[i], digits)) + "L"
  230. def check_format_1(self, x):
  231. for base, mapper in (8, oct), (10, repr), (16, hex):
  232. got = mapper(x)
  233. expected = self.slow_format(x, base)
  234. msg = Frm("%s returned %r but expected %r for %r",
  235. mapper.__name__, got, expected, x)
  236. self.assertEqual(got, expected, msg)
  237. self.assertEqual(long(got, 0), x, Frm('long("%s", 0) != %r', got, x))
  238. # str() has to be checked a little differently since there's no
  239. # trailing "L"
  240. got = str(x)
  241. expected = self.slow_format(x, 10)[:-1]
  242. msg = Frm("%s returned %r but expected %r for %r",
  243. mapper.__name__, got, expected, x)
  244. self.assertEqual(got, expected, msg)
  245. def test_format(self):
  246. for x in special:
  247. self.check_format_1(x)
  248. for i in xrange(10):
  249. for lenx in xrange(1, MAXDIGITS+1):
  250. x = self.getran(lenx)
  251. self.check_format_1(x)
  252. def test_long(self):
  253. self.assertEqual(long(314), 314L)
  254. self.assertEqual(long(3.14), 3L)
  255. self.assertEqual(long(314L), 314L)
  256. # Check that long() of basic types actually returns a long
  257. self.assertEqual(type(long(314)), long)
  258. self.assertEqual(type(long(3.14)), long)
  259. self.assertEqual(type(long(314L)), long)
  260. # Check that conversion from float truncates towards zero
  261. self.assertEqual(long(-3.14), -3L)
  262. self.assertEqual(long(3.9), 3L)
  263. self.assertEqual(long(-3.9), -3L)
  264. self.assertEqual(long(3.5), 3L)
  265. self.assertEqual(long(-3.5), -3L)
  266. self.assertEqual(long("-3"), -3L)
  267. if test_support.have_unicode:
  268. self.assertEqual(long(unicode("-3")), -3L)
  269. # Different base:
  270. self.assertEqual(long("10",16), 16L)
  271. if test_support.have_unicode:
  272. self.assertEqual(long(unicode("10"),16), 16L)
  273. # Check conversions from string (same test set as for int(), and then some)
  274. LL = [
  275. ('1' + '0'*20, 10L**20),
  276. ('1' + '0'*100, 10L**100)
  277. ]
  278. L2 = L[:]
  279. if test_support.have_unicode:
  280. L2 += [
  281. (unicode('1') + unicode('0')*20, 10L**20),
  282. (unicode('1') + unicode('0')*100, 10L**100),
  283. ]
  284. for s, v in L2 + LL:
  285. for sign in "", "+", "-":
  286. for prefix in "", " ", "\t", " \t\t ":
  287. ss = prefix + sign + s
  288. vv = v
  289. if sign == "-" and v is not ValueError:
  290. vv = -v
  291. try:
  292. self.assertEqual(long(ss), long(vv))
  293. except v:
  294. pass
  295. self.assertRaises(ValueError, long, '123\0')
  296. self.assertRaises(ValueError, long, '53', 40)
  297. self.assertRaises(TypeError, long, 1, 12)
  298. # SF patch #1638879: embedded NULs were not detected with
  299. # explicit base
  300. self.assertRaises(ValueError, long, '123\0', 10)
  301. self.assertRaises(ValueError, long, '123\x00 245', 20)
  302. self.assertEqual(long('100000000000000000000000000000000', 2),
  303. 4294967296)
  304. self.assertEqual(long('102002022201221111211', 3), 4294967296)
  305. self.assertEqual(long('10000000000000000', 4), 4294967296)
  306. self.assertEqual(long('32244002423141', 5), 4294967296)
  307. self.assertEqual(long('1550104015504', 6), 4294967296)
  308. self.assertEqual(long('211301422354', 7), 4294967296)
  309. self.assertEqual(long('40000000000', 8), 4294967296)
  310. self.assertEqual(long('12068657454', 9), 4294967296)
  311. self.assertEqual(long('4294967296', 10), 4294967296)
  312. self.assertEqual(long('1904440554', 11), 4294967296)
  313. self.assertEqual(long('9ba461594', 12), 4294967296)
  314. self.assertEqual(long('535a79889', 13), 4294967296)
  315. self.assertEqual(long('2ca5b7464', 14), 4294967296)
  316. self.assertEqual(long('1a20dcd81', 15), 4294967296)
  317. self.assertEqual(long('100000000', 16), 4294967296)
  318. self.assertEqual(long('a7ffda91', 17), 4294967296)
  319. self.assertEqual(long('704he7g4', 18), 4294967296)
  320. self.assertEqual(long('4f5aff66', 19), 4294967296)
  321. self.assertEqual(long('3723ai4g', 20), 4294967296)
  322. self.assertEqual(long('281d55i4', 21), 4294967296)
  323. self.assertEqual(long('1fj8b184', 22), 4294967296)
  324. self.assertEqual(long('1606k7ic', 23), 4294967296)
  325. self.assertEqual(long('mb994ag', 24), 4294967296)
  326. self.assertEqual(long('hek2mgl', 25), 4294967296)
  327. self.assertEqual(long('dnchbnm', 26), 4294967296)
  328. self.assertEqual(long('b28jpdm', 27), 4294967296)
  329. self.assertEqual(long('8pfgih4', 28), 4294967296)
  330. self.assertEqual(long('76beigg', 29), 4294967296)
  331. self.assertEqual(long('5qmcpqg', 30), 4294967296)
  332. self.assertEqual(long('4q0jto4', 31), 4294967296)
  333. self.assertEqual(long('4000000', 32), 4294967296)
  334. self.assertEqual(long('3aokq94', 33), 4294967296)
  335. self.assertEqual(long('2qhxjli', 34), 4294967296)
  336. self.assertEqual(long('2br45qb', 35), 4294967296)
  337. self.assertEqual(long('1z141z4', 36), 4294967296)
  338. self.assertEqual(long('100000000000000000000000000000001', 2),
  339. 4294967297)
  340. self.assertEqual(long('102002022201221111212', 3), 4294967297)
  341. self.assertEqual(long('10000000000000001', 4), 4294967297)
  342. self.assertEqual(long('32244002423142', 5), 4294967297)
  343. self.assertEqual(long('1550104015505', 6), 4294967297)
  344. self.assertEqual(long('211301422355', 7), 4294967297)
  345. self.assertEqual(long('40000000001', 8), 4294967297)
  346. self.assertEqual(long('12068657455', 9), 4294967297)
  347. self.assertEqual(long('4294967297', 10), 4294967297)
  348. self.assertEqual(long('1904440555', 11), 4294967297)
  349. self.assertEqual(long('9ba461595', 12), 4294967297)
  350. self.assertEqual(long('535a7988a', 13), 4294967297)
  351. self.assertEqual(long('2ca5b7465', 14), 4294967297)
  352. self.assertEqual(long('1a20dcd82', 15), 4294967297)
  353. self.assertEqual(long('100000001', 16), 4294967297)
  354. self.assertEqual(long('a7ffda92', 17), 4294967297)
  355. self.assertEqual(long('704he7g5', 18), 4294967297)
  356. self.assertEqual(long('4f5aff67', 19), 4294967297)
  357. self.assertEqual(long('3723ai4h', 20), 4294967297)
  358. self.assertEqual(long('281d55i5', 21), 4294967297)
  359. self.assertEqual(long('1fj8b185', 22), 4294967297)
  360. self.assertEqual(long('1606k7id', 23), 4294967297)
  361. self.assertEqual(long('mb994ah', 24), 4294967297)
  362. self.assertEqual(long('hek2mgm', 25), 4294967297)
  363. self.assertEqual(long('dnchbnn', 26), 4294967297)
  364. self.assertEqual(long('b28jpdn', 27), 4294967297)
  365. self.assertEqual(long('8pfgih5', 28), 4294967297)
  366. self.assertEqual(long('76beigh', 29), 4294967297)
  367. self.assertEqual(long('5qmcpqh', 30), 4294967297)
  368. self.assertEqual(long('4q0jto5', 31), 4294967297)
  369. self.assertEqual(long('4000001', 32), 4294967297)
  370. self.assertEqual(long('3aokq95', 33), 4294967297)
  371. self.assertEqual(long('2qhxjlj', 34), 4294967297)
  372. self.assertEqual(long('2br45qc', 35), 4294967297)
  373. self.assertEqual(long('1z141z5', 36), 4294967297)
  374. def test_conversion(self):
  375. # Test __long__()
  376. class ClassicMissingMethods:
  377. pass
  378. self.assertRaises(AttributeError, long, ClassicMissingMethods())
  379. class MissingMethods(object):
  380. pass
  381. self.assertRaises(TypeError, long, MissingMethods())
  382. class Foo0:
  383. def __long__(self):
  384. return 42L
  385. class Foo1(object):
  386. def __long__(self):
  387. return 42L
  388. class Foo2(long):
  389. def __long__(self):
  390. return 42L
  391. class Foo3(long):
  392. def __long__(self):
  393. return self
  394. class Foo4(long):
  395. def __long__(self):
  396. return 42
  397. class Foo5(long):
  398. def __long__(self):
  399. return 42.
  400. self.assertEqual(long(Foo0()), 42L)
  401. self.assertEqual(long(Foo1()), 42L)
  402. self.assertEqual(long(Foo2()), 42L)
  403. self.assertEqual(long(Foo3()), 0)
  404. self.assertEqual(long(Foo4()), 42)
  405. self.assertRaises(TypeError, long, Foo5())
  406. class Classic:
  407. pass
  408. for base in (object, Classic):
  409. class LongOverridesTrunc(base):
  410. def __long__(self):
  411. return 42
  412. def __trunc__(self):
  413. return -12
  414. self.assertEqual(long(LongOverridesTrunc()), 42)
  415. class JustTrunc(base):
  416. def __trunc__(self):
  417. return 42
  418. self.assertEqual(long(JustTrunc()), 42)
  419. for trunc_result_base in (object, Classic):
  420. class Integral(trunc_result_base):
  421. def __int__(self):
  422. return 42
  423. class TruncReturnsNonLong(base):
  424. def __trunc__(self):
  425. return Integral()
  426. self.assertEqual(long(TruncReturnsNonLong()), 42)
  427. class NonIntegral(trunc_result_base):
  428. def __trunc__(self):
  429. # Check that we avoid infinite recursion.
  430. return NonIntegral()
  431. class TruncReturnsNonIntegral(base):
  432. def __trunc__(self):
  433. return NonIntegral()
  434. try:
  435. long(TruncReturnsNonIntegral())
  436. except TypeError as e:
  437. self.assertEquals(str(e),
  438. "__trunc__ returned non-Integral"
  439. " (type NonIntegral)")
  440. else:
  441. self.fail("Failed to raise TypeError with %s" %
  442. ((base, trunc_result_base),))
  443. def test_misc(self):
  444. # check the extremes in int<->long conversion
  445. hugepos = sys.maxint
  446. hugeneg = -hugepos - 1
  447. hugepos_aslong = long(hugepos)
  448. hugeneg_aslong = long(hugeneg)
  449. self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint")
  450. self.assertEqual(hugeneg, hugeneg_aslong,
  451. "long(-sys.maxint-1) != -sys.maxint-1")
  452. # long -> int should not fail for hugepos_aslong or hugeneg_aslong
  453. x = int(hugepos_aslong)
  454. try:
  455. self.assertEqual(x, hugepos,
  456. "converting sys.maxint to long and back to int fails")
  457. except OverflowError:
  458. self.fail("int(long(sys.maxint)) overflowed!")
  459. if not isinstance(x, int):
  460. raise TestFailed("int(long(sys.maxint)) should have returned int")
  461. x = int(hugeneg_aslong)
  462. try:
  463. self.assertEqual(x, hugeneg,
  464. "converting -sys.maxint-1 to long and back to int fails")
  465. except OverflowError:
  466. self.fail("int(long(-sys.maxint-1)) overflowed!")
  467. if not isinstance(x, int):
  468. raise TestFailed("int(long(-sys.maxint-1)) should have "
  469. "returned int")
  470. # but long -> int should overflow for hugepos+1 and hugeneg-1
  471. x = hugepos_aslong + 1
  472. try:
  473. y = int(x)
  474. except OverflowError:
  475. self.fail("int(long(sys.maxint) + 1) mustn't overflow")
  476. self.assert_(isinstance(y, long),
  477. "int(long(sys.maxint) + 1) should have returned long")
  478. x = hugeneg_aslong - 1
  479. try:
  480. y = int(x)
  481. except OverflowError:
  482. self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow")
  483. self.assert_(isinstance(y, long),
  484. "int(long(-sys.maxint-1) - 1) should have returned long")
  485. class long2(long):
  486. pass
  487. x = long2(1L<<100)
  488. y = int(x)
  489. self.assert_(type(y) is long,
  490. "overflowing int conversion must return long not long subtype")
  491. # long -> Py_ssize_t conversion
  492. class X(object):
  493. def __getslice__(self, i, j):
  494. return i, j
  495. self.assertEqual(X()[-5L:7L], (-5, 7))
  496. # use the clamping effect to test the smallest and largest longs
  497. # that fit a Py_ssize_t
  498. slicemin, slicemax = X()[-2L**100:2L**100]
  499. self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
  500. # ----------------------------------- tests of auto int->long conversion
  501. def test_auto_overflow(self):
  502. import math, sys
  503. special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1]
  504. sqrt = int(math.sqrt(sys.maxint))
  505. special.extend([sqrt-1, sqrt, sqrt+1])
  506. special.extend([-i for i in special])
  507. def checkit(*args):
  508. # Heavy use of nested scopes here!
  509. self.assertEqual(got, expected,
  510. Frm("for %r expected %r got %r", args, expected, got))
  511. for x in special:
  512. longx = long(x)
  513. expected = -longx
  514. got = -x
  515. checkit('-', x)
  516. for y in special:
  517. longy = long(y)
  518. expected = longx + longy
  519. got = x + y
  520. checkit(x, '+', y)
  521. expected = longx - longy
  522. got = x - y
  523. checkit(x, '-', y)
  524. expected = longx * longy
  525. got = x * y
  526. checkit(x, '*', y)
  527. if y:
  528. expected = longx / longy
  529. got = x / y
  530. checkit(x, '/', y)
  531. expected = longx // longy
  532. got = x // y
  533. checkit(x, '//', y)
  534. expected = divmod(longx, longy)
  535. got = divmod(longx, longy)
  536. checkit(x, 'divmod', y)
  537. if abs(y) < 5 and not (x == 0 and y < 0):
  538. expected = longx ** longy
  539. got = x ** y
  540. checkit(x, '**', y)
  541. for z in special:
  542. if z != 0 :
  543. if y >= 0:
  544. expected = pow(longx, longy, long(z))
  545. got = pow(x, y, z)
  546. checkit('pow', x, y, '%', z)
  547. else:
  548. self.assertRaises(TypeError, pow,longx, longy, long(z))
  549. def test_float_overflow(self):
  550. import math
  551. for x in -2.0, -1.0, 0.0, 1.0, 2.0:
  552. self.assertEqual(float(long(x)), x)
  553. shuge = '12345' * 120
  554. huge = 1L << 30000
  555. mhuge = -huge
  556. namespace = {'huge': huge, 'mhuge': mhuge, 'shuge': shuge, 'math': math}
  557. for test in ["float(huge)", "float(mhuge)",
  558. "complex(huge)", "complex(mhuge)",
  559. "complex(huge, 1)", "complex(mhuge, 1)",
  560. "complex(1, huge)", "complex(1, mhuge)",
  561. "1. + huge", "huge + 1.", "1. + mhuge", "mhuge + 1.",
  562. "1. - huge", "huge - 1.", "1. - mhuge", "mhuge - 1.",
  563. "1. * huge", "huge * 1.", "1. * mhuge", "mhuge * 1.",
  564. "1. // huge", "huge // 1.", "1. // mhuge", "mhuge // 1.",
  565. "1. / huge", "huge / 1.", "1. / mhuge", "mhuge / 1.",
  566. "1. ** huge", "huge ** 1.", "1. ** mhuge", "mhuge ** 1.",
  567. "math.sin(huge)", "math.sin(mhuge)",
  568. "math.sqrt(huge)", "math.sqrt(mhuge)", # should do better
  569. "math.floor(huge)", "math.floor(mhuge)"]:
  570. self.assertRaises(OverflowError, eval, test, namespace)
  571. # XXX Perhaps float(shuge) can raise OverflowError on some box?
  572. # The comparison should not.
  573. self.assertNotEqual(float(shuge), int(shuge),
  574. "float(shuge) should not equal int(shuge)")
  575. def test_logs(self):
  576. import math
  577. LOG10E = math.log10(math.e)
  578. for exp in range(10) + [100, 1000, 10000]:
  579. value = 10 ** exp
  580. log10 = math.log10(value)
  581. self.assertAlmostEqual(log10, exp)
  582. # log10(value) == exp, so log(value) == log10(value)/log10(e) ==
  583. # exp/LOG10E
  584. expected = exp / LOG10E
  585. log = math.log(value)
  586. self.assertAlmostEqual(log, expected)
  587. for bad in -(1L << 10000), -2L, 0L:
  588. self.assertRaises(ValueError, math.log, bad)
  589. self.assertRaises(ValueError, math.log10, bad)
  590. def test_mixed_compares(self):
  591. eq = self.assertEqual
  592. import math
  593. # We're mostly concerned with that mixing floats and longs does the
  594. # right stuff, even when longs are too large to fit in a float.
  595. # The safest way to check the results is to use an entirely different
  596. # method, which we do here via a skeletal rational class (which
  597. # represents all Python ints, longs and floats exactly).
  598. class Rat:
  599. def __init__(self, value):
  600. if isinstance(value, (int, long)):
  601. self.n = value
  602. self.d = 1
  603. elif isinstance(value, float):
  604. # Convert to exact rational equivalent.
  605. f, e = math.frexp(abs(value))
  606. assert f == 0 or 0.5 <= f < 1.0
  607. # |value| = f * 2**e exactly
  608. # Suck up CHUNK bits at a time; 28 is enough so that we suck
  609. # up all bits in 2 iterations for all known binary double-
  610. # precision formats, and small enough to fit in an int.
  611. CHUNK = 28
  612. top = 0
  613. # invariant: |value| = (top + f) * 2**e exactly
  614. while f:
  615. f = math.ldexp(f, CHUNK)
  616. digit = int(f)
  617. assert digit >> CHUNK == 0
  618. top = (top << CHUNK) | digit
  619. f -= digit
  620. assert 0.0 <= f < 1.0
  621. e -= CHUNK
  622. # Now |value| = top * 2**e exactly.
  623. if e >= 0:
  624. n = top << e
  625. d = 1
  626. else:
  627. n = top
  628. d = 1 << -e
  629. if value < 0:
  630. n = -n
  631. self.n = n
  632. self.d = d
  633. assert float(n) / float(d) == value
  634. else:
  635. raise TypeError("can't deal with %r" % val)
  636. def __cmp__(self, other):
  637. if not isinstance(other, Rat):
  638. other = Rat(other)
  639. return cmp(self.n * other.d, self.d * other.n)
  640. cases = [0, 0.001, 0.99, 1.0, 1.5, 1e20, 1e200]
  641. # 2**48 is an important boundary in the internals. 2**53 is an
  642. # important boundary for IEEE double precision.
  643. for t in 2.0**48, 2.0**50, 2.0**53:
  644. cases.extend([t - 1.0, t - 0.3, t, t + 0.3, t + 1.0,
  645. long(t-1), long(t), long(t+1)])
  646. cases.extend([0, 1, 2, sys.maxint, float(sys.maxint)])
  647. # 1L<<20000 should exceed all double formats. long(1e200) is to
  648. # check that we get equality with 1e200 above.
  649. t = long(1e200)
  650. cases.extend([0L, 1L, 2L, 1L << 20000, t-1, t, t+1])
  651. cases.extend([-x for x in cases])
  652. for x in cases:
  653. Rx = Rat(x)
  654. for y in cases:
  655. Ry = Rat(y)
  656. Rcmp = cmp(Rx, Ry)
  657. xycmp = cmp(x, y)
  658. eq(Rcmp, xycmp, Frm("%r %r %d %d", x, y, Rcmp, xycmp))
  659. eq(x == y, Rcmp == 0, Frm("%r == %r %d", x, y, Rcmp))
  660. eq(x != y, Rcmp != 0, Frm("%r != %r %d", x, y, Rcmp))
  661. eq(x < y, Rcmp < 0, Frm("%r < %r %d", x, y, Rcmp))
  662. eq(x <= y, Rcmp <= 0, Frm("%r <= %r %d", x, y, Rcmp))
  663. eq(x > y, Rcmp > 0, Frm("%r > %r %d", x, y, Rcmp))
  664. eq(x >= y, Rcmp >= 0, Frm("%r >= %r %d", x, y, Rcmp))
  665. def test_nan_inf(self):
  666. self.assertRaises(OverflowError, long, float('inf'))
  667. self.assertRaises(OverflowError, long, float('-inf'))
  668. self.assertRaises(ValueError, long, float('nan'))
  669. def test_main():
  670. test_support.run_unittest(LongTest)
  671. if __name__ == "__main__":
  672. test_main()