Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(119428)

Delta Between Two Patch Sets: Lib/test/test_decimal.py

Issue 7652: Merge C version of decimal into py3k.
Left Patch Set: Created 7 years, 9 months ago
Right Patch Set: Created 7 years, 8 months ago
Left:
Right:
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
Left: Side by side diff | Download
Right: Side by side diff | Download
« no previous file with change/comment | « Lib/test/support.py ('k') | Lib/test/test_fractions.py » ('j') | no next file with change/comment »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
LEFTRIGHT
1 # Copyright (c) 2004 Python Software Foundation. 1 # Copyright (c) 2004 Python Software Foundation.
2 # All rights reserved. 2 # All rights reserved.
3 3
4 # Written by Eric Price <eprice at tjhsst.edu> 4 # Written by Eric Price <eprice at tjhsst.edu>
5 # and Facundo Batista <facundo at taniquetil.com.ar> 5 # and Facundo Batista <facundo at taniquetil.com.ar>
6 # and Raymond Hettinger <python at rcn.com> 6 # and Raymond Hettinger <python at rcn.com>
7 # and Aahz (aahz at pobox.com) 7 # and Aahz (aahz at pobox.com)
8 # and Tim Peters 8 # and Tim Peters
9 9
10 """ 10 """
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
49 orig_sys_decimal = sys.modules['decimal'] 49 orig_sys_decimal = sys.modules['decimal']
50 50
51 # fractions module must import the correct decimal module. 51 # fractions module must import the correct decimal module.
52 cfractions = import_fresh_module('fractions', fresh=['fractions']) 52 cfractions = import_fresh_module('fractions', fresh=['fractions'])
53 sys.modules['decimal'] = P 53 sys.modules['decimal'] = P
54 pfractions = import_fresh_module('fractions', fresh=['fractions']) 54 pfractions = import_fresh_module('fractions', fresh=['fractions'])
55 sys.modules['decimal'] = C 55 sys.modules['decimal'] = C
56 fractions = {C:cfractions, P:pfractions} 56 fractions = {C:cfractions, P:pfractions}
57 sys.modules['decimal'] = orig_sys_decimal 57 sys.modules['decimal'] = orig_sys_decimal
58 58
59 # Testing all failures of API functions for _decimal. First,
60 # the number of API calls in a test case is determined. Then,
61 # the testcase is run with all possible API failures, checking
62 # that FailAPIException is properly raised.
63 def assertRaises(expEx, func, *args, **kwargs):
64 """assertRaises has to reraise FailAPIException."""
65 try:
66 func(*args, **kwargs)
67 except Exception as e:
68 if e.__class__ is C.FailAPIException:
69 raise C.FailAPIException
70 if not e.__class__ is expEx:
71 raise e
72
73 def withFailpoint(func):
74 """Wrap a function for testing all possible API failures."""
75 def iter_failpoint(testcase, *args):
76 # These tests will not work.
77 setattr(testcase, 'assertRaises', assertRaises)
78 # Determine number of API calls.
79 C.setapicalls(0)
80 C.setfailpoint(0)
81 func(testcase, *args)
82 n = C.getapicalls()
83 # Fail at each possible API call.
84 for i in range(1, n+1):
85 C.setapicalls(0)
86 C.setfailpoint(i)
87 try:
88 func(testcase, *args)
89 except C.FailAPIException:
90 continue
91 # Error: FailAPIException was not raised
92 raise TestFailed("FailAPIException not raised in: %s" % func)
93 C.setapicalls(0)
94 C.setfailpoint(0)
95 return iter_failpoint
96
97 class ProtectFail(object):
98 """Protect code regions that modify global state (e.g. lines
99 that set or restore global context values). Otherwise it
100 would not be possible to rerun a test case several times."""
101 def __enter__(self):
102 if hasattr(C, 'setfailpoint'):
103 self.calls = C.getapicalls()
104 self.fpoint = C.getfailpoint()
105 C.setfailpoint(0)
106 def __exit__(self, *_):
107 if hasattr(C, 'setfailpoint'):
108 C.setfailpoint(self.fpoint)
109 if self.fpoint:
110 if self.calls < self.fpoint <= C.getapicalls():
111 # Pretend that API calls in the protected block failed.
112 raise C.FailAPIException
113
114 def protectfail():
115 return ProtectFail()
116
117 if hasattr(C, 'setfailpoint'):
118 # Functions that are iterated several times must use
119 # the same random sequence each time.
120 randseed = int(time.time())
121 # Implicit initialization of the module context must
122 # be tested first.
123 for i in range(1, 100):
124 C.setapicalls(0)
125 C.setfailpoint(i)
126 try:
127 C.getcontext()
128 except C.FailAPIException as e:
129 continue
130 C.setapicalls(0)
131 C.setfailpoint(0)
132 59
133 # Useful Test Constant 60 # Useful Test Constant
134 Signals = { 61 Signals = {
135 C: tuple(C.getcontext().flags.keys()) if C else None, 62 C: tuple(C.getcontext().flags.keys()) if C else None,
136 P: tuple(P.getcontext().flags.keys()) 63 P: tuple(P.getcontext().flags.keys())
137 } 64 }
138 # Signals ordered with respect to precedence: when an operation 65 # Signals ordered with respect to precedence: when an operation
139 # produces multiple signals, signals occurring later in the list 66 # produces multiple signals, signals occurring later in the list
140 # should be handled before those occurring earlier in the list. 67 # should be handled before those occurring earlier in the list.
141 OrderedSignals = { 68 OrderedSignals = {
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
176 else: 103 else:
177 file = __file__ 104 file = __file__
178 testdir = os.path.dirname(file) or os.curdir 105 testdir = os.path.dirname(file) or os.curdir
179 directory = testdir + os.sep + TESTDATADIR + os.sep 106 directory = testdir + os.sep + TESTDATADIR + os.sep
180 107
181 skip_expected = not os.path.isdir(directory) 108 skip_expected = not os.path.isdir(directory)
182 109
183 # Make sure it actually raises errors when not expected and caught in flags 110 # Make sure it actually raises errors when not expected and caught in flags
184 # Slower, since it runs some things several times. 111 # Slower, since it runs some things several times.
185 EXTENDEDERRORTEST = False 112 EXTENDEDERRORTEST = False
113
114 # Test extra functionality in the C version (-DEXTRA_FUNCTIONALITY).
115 EXTRA_FUNCTIONALITY = True if hasattr(C, 'DecClamped') else False
116 requires_extra_functionality = unittest.skipUnless(
117 EXTRA_FUNCTIONALITY, "test requires build with -DEXTRA_FUNCTIONALITY")
186 118
187 119
188 class IBMTestCases(unittest.TestCase): 120 class IBMTestCases(unittest.TestCase):
189 """Class which tests the Decimal class against the IBM test cases.""" 121 """Class which tests the Decimal class against the IBM test cases."""
190 122
191 def setUp(self): 123 def setUp(self):
192 self.context = self.decimal.Context() 124 self.context = self.decimal.Context()
193 self.readcontext = self.decimal.Context() 125 self.readcontext = self.decimal.Context()
194 self.ignore_list = ['#'] 126 self.ignore_list = ['#']
195 127
(...skipping 133 matching lines...) Expand 10 before | Expand all | Expand 10 after
329 'is_zero', 261 'is_zero',
330 'same_quantum') 262 'same_quantum')
331 263
332 def read_unlimited(self, v, context): 264 def read_unlimited(self, v, context):
333 """Work around the limitations of the 32-bit _decimal version. The 265 """Work around the limitations of the 32-bit _decimal version. The
334 guaranteed maximum values for prec, Emax etc. are 425000000, 266 guaranteed maximum values for prec, Emax etc. are 425000000,
335 but higher values usually work, except for rare corner cases. 267 but higher values usually work, except for rare corner cases.
336 In particular, all of the IBM tests pass with maximum values 268 In particular, all of the IBM tests pass with maximum values
337 of 1070000000.""" 269 of 1070000000."""
338 if self.decimal == C and self.decimal.MAX_EMAX == 425000000: 270 if self.decimal == C and self.decimal.MAX_EMAX == 425000000:
339 self.readcontext.unsafe_setprec(1070000000) 271 self.readcontext._unsafe_setprec(1070000000)
340 self.readcontext.unsafe_setemax(1070000000) 272 self.readcontext._unsafe_setemax(1070000000)
341 self.readcontext.unsafe_setemin(-1070000000) 273 self.readcontext._unsafe_setemin(-1070000000)
342 return self.readcontext.create_decimal(v) 274 return self.readcontext.create_decimal(v)
343 else: 275 else:
344 return self.decimal.Decimal(v, context) 276 return self.decimal.Decimal(v, context)
345 277
346 def eval_file(self, file): 278 def eval_file(self, file):
347 global skip_expected 279 global skip_expected
348 if skip_expected: 280 if skip_expected:
349 raise unittest.SkipTest 281 raise unittest.SkipTest
350 return 282 return
351 with open(file) as f: 283 with open(file) as f:
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
386 try: 318 try:
387 value = int(value) 319 value = int(value)
388 except ValueError: 320 except ValueError:
389 pass 321 pass
390 322
391 funct = self.ChangeDict.get(funct, (lambda *args: None)) 323 funct = self.ChangeDict.get(funct, (lambda *args: None))
392 funct(value) 324 funct(value)
393 325
394 def eval_equation(self, s): 326 def eval_equation(self, s):
395 327
396 if not TEST_ALL and not hasattr(C, 'setfailpoint') and \ 328 if not TEST_ALL and random.random() < 0.90:
397 random.random() < 0.90:
398 return 329 return
399 330
400 with protectfail(): 331 self.context.clear_flags()
401 self.context.clear_flags()
402 332
403 try: 333 try:
404 Sides = s.split('->') 334 Sides = s.split('->')
405 L = Sides[0].strip().split() 335 L = Sides[0].strip().split()
406 id = L[0] 336 id = L[0]
407 if DEBUG: 337 if DEBUG:
408 print("Test ", id, end=" ") 338 print("Test ", id, end=" ")
409 funct = L[1].lower() 339 funct = L[1].lower()
410 valstemp = L[2:] 340 valstemp = L[2:]
411 L = Sides[1].strip().split() 341 L = Sides[1].strip().split()
(...skipping 87 matching lines...) Expand 10 before | Expand all | Expand 10 after
499 429
500 430
501 if DEBUG: 431 if DEBUG:
502 print("--", self.context) 432 print("--", self.context)
503 try: 433 try:
504 result = str(funct(*vals)) 434 result = str(funct(*vals))
505 if fname in self.LogicalFunctions: 435 if fname in self.LogicalFunctions:
506 result = str(int(eval(result))) # 'True', 'False' -> '1', '0' 436 result = str(int(eval(result))) # 'True', 'False' -> '1', '0'
507 except Signals[self.decimal] as error: 437 except Signals[self.decimal] as error:
508 self.fail("Raised %s in %s" % (error, s)) 438 self.fail("Raised %s in %s" % (error, s))
509 except Exception as e: #Catch any error long enough to state the test ca se. 439 except: #Catch any error long enough to state the test case.
510 # Errors are expected with failpoints. 440 print("ERROR:", s)
511 if not hasattr(C, 'setfailpoint'): 441 raise
512 print("ERROR:", s)
513 raise e.__class__
514 442
515 myexceptions = self.getexceptions() 443 myexceptions = self.getexceptions()
516 444
517 myexceptions.sort(key=repr) 445 myexceptions.sort(key=repr)
518 theirexceptions.sort(key=repr) 446 theirexceptions.sort(key=repr)
519 447
520 self.assertEqual(result, ans, 448 self.assertEqual(result, ans,
521 'Incorrect answer for ' + s + ' -- got ' + result) 449 'Incorrect answer for ' + s + ' -- got ' + result)
522 450
523 self.assertEqual(myexceptions, theirexceptions, 451 self.assertEqual(myexceptions, theirexceptions,
524 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) 452 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions))
525 return 453 return
526 454
527 def getexceptions(self): 455 def getexceptions(self):
528 return [e for e in Signals[self.decimal] if self.context.flags[e]] 456 return [e for e in Signals[self.decimal] if self.context.flags[e]]
529 457
530 def change_precision(self, prec): 458 def change_precision(self, prec):
531 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 459 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
532 self.context.unsafe_setprec(prec) 460 self.context._unsafe_setprec(prec)
533 else: 461 else:
534 self.context.prec = prec 462 self.context.prec = prec
535 def change_rounding_method(self, rounding): 463 def change_rounding_method(self, rounding):
536 self.context.rounding = rounding 464 self.context.rounding = rounding
537 def change_min_exponent(self, exp): 465 def change_min_exponent(self, exp):
538 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 466 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
539 self.context.unsafe_setemin(exp) 467 self.context._unsafe_setemin(exp)
540 else: 468 else:
541 self.context.Emin = exp 469 self.context.Emin = exp
542 def change_max_exponent(self, exp): 470 def change_max_exponent(self, exp):
543 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 471 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
544 self.context.unsafe_setemax(exp) 472 self.context._unsafe_setemax(exp)
545 else: 473 else:
546 self.context.Emax = exp 474 self.context.Emax = exp
547 def change_clamp(self, clamp): 475 def change_clamp(self, clamp):
548 self.context.clamp = clamp 476 self.context.clamp = clamp
549 477
550 class CIBMTestCases(IBMTestCases): 478 class CIBMTestCases(IBMTestCases):
551 decimal = C 479 decimal = C
552 class PyIBMTestCases(IBMTestCases): 480 class PyIBMTestCases(IBMTestCases):
553 decimal = P 481 decimal = P
554 482
(...skipping 171 matching lines...) Expand 10 before | Expand all | Expand 10 after
726 e = Decimal(d) 654 e = Decimal(d)
727 self.assertEqual(str(e), '-45') 655 self.assertEqual(str(e), '-45')
728 656
729 #zero 657 #zero
730 d = Decimal(0) 658 d = Decimal(0)
731 e = Decimal(d) 659 e = Decimal(d)
732 self.assertEqual(str(e), '0') 660 self.assertEqual(str(e), '0')
733 661
734 @requires_IEEE_754 662 @requires_IEEE_754
735 def test_explicit_from_float(self): 663 def test_explicit_from_float(self):
736 if hasattr(C, 'setfailpoint'):
737 random.seed(randseed)
738 664
739 Decimal = self.decimal.Decimal 665 Decimal = self.decimal.Decimal
740 666
741 r = Decimal(0.1) 667 r = Decimal(0.1)
742 self.assertEqual(type(r), Decimal) 668 self.assertEqual(type(r), Decimal)
743 self.assertEqual(str(r), 669 self.assertEqual(str(r),
744 '0.1000000000000000055511151231257827021181583404541015625') 670 '0.1000000000000000055511151231257827021181583404541015625')
745 self.assertTrue(Decimal(float('nan')).is_qnan()) 671 self.assertTrue(Decimal(float('nan')).is_qnan())
746 self.assertTrue(Decimal(float('inf')).is_infinite()) 672 self.assertTrue(Decimal(float('inf')).is_infinite())
747 self.assertTrue(Decimal(float('-inf')).is_infinite()) 673 self.assertTrue(Decimal(float('-inf')).is_infinite())
(...skipping 89 matching lines...) Expand 10 before | Expand all | Expand 10 after
837 763
838 nc.traps[InvalidOperation] = False 764 nc.traps[InvalidOperation] = False
839 self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN') 765 self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN')
840 self.assertTrue(nc.flags[InvalidOperation]) 766 self.assertTrue(nc.flags[InvalidOperation])
841 767
842 nc.flags[InvalidOperation] = False 768 nc.flags[InvalidOperation] = False
843 self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN') 769 self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN')
844 self.assertTrue(nc.flags[InvalidOperation]) 770 self.assertTrue(nc.flags[InvalidOperation])
845 771
846 def test_explicit_context_create_from_float(self): 772 def test_explicit_context_create_from_float(self):
847 if hasattr(C, 'setfailpoint'):
848 random.seed(randseed)
849 773
850 Decimal = self.decimal.Decimal 774 Decimal = self.decimal.Decimal
851 775
852 nc = self.decimal.Context() 776 nc = self.decimal.Context()
853 r = nc.create_decimal(0.1) 777 r = nc.create_decimal(0.1)
854 self.assertEqual(type(r), Decimal) 778 self.assertEqual(type(r), Decimal)
855 self.assertEqual(str(r), '0.1000000000000000055511151231') 779 self.assertEqual(str(r), '0.1000000000000000055511151231')
856 self.assertTrue(nc.create_decimal(float('nan')).is_qnan()) 780 self.assertTrue(nc.create_decimal(float('nan')).is_qnan())
857 self.assertTrue(nc.create_decimal(float('inf')).is_infinite()) 781 self.assertTrue(nc.create_decimal(float('inf')).is_infinite())
858 self.assertTrue(nc.create_decimal(float('-inf')).is_infinite()) 782 self.assertTrue(nc.create_decimal(float('-inf')).is_infinite())
(...skipping 768 matching lines...) Expand 10 before | Expand all | Expand 10 after
1627 # Test the "threading isolation" of a Context. Also test changing 1551 # Test the "threading isolation" of a Context. Also test changing
1628 # the DefaultContext, which acts as a template for the thread-local 1552 # the DefaultContext, which acts as a template for the thread-local
1629 # contexts. 1553 # contexts.
1630 save_prec = DefaultContext.prec 1554 save_prec = DefaultContext.prec
1631 save_emax = DefaultContext.Emax 1555 save_emax = DefaultContext.Emax
1632 save_emin = DefaultContext.Emin 1556 save_emin = DefaultContext.Emin
1633 DefaultContext.prec = 24 1557 DefaultContext.prec = 24
1634 DefaultContext.Emax = 425000000 1558 DefaultContext.Emax = 425000000
1635 DefaultContext.Emin = -425000000 1559 DefaultContext.Emin = -425000000
1636 1560
1637 with protectfail(): 1561 self.synchro = threading.Event()
1638 self.synchro = threading.Event() 1562 self.finish1 = threading.Event()
1639 self.finish1 = threading.Event() 1563 self.finish2 = threading.Event()
1640 self.finish2 = threading.Event() 1564
1641 1565 th1 = threading.Thread(target=thfunc1, args=(self,))
1642 th1 = threading.Thread(target=thfunc1, args=(self,)) 1566 th2 = threading.Thread(target=thfunc2, args=(self,))
1643 th2 = threading.Thread(target=thfunc2, args=(self,)) 1567
1644 1568 th1.start()
1645 th1.start() 1569 th2.start()
1646 th2.start() 1570
1647 1571 self.finish1.wait()
1648 self.finish1.wait() 1572 self.finish2.wait()
1649 self.finish2.wait()
1650 1573
1651 for sig in Signals[self.decimal]: 1574 for sig in Signals[self.decimal]:
1652 self.assertFalse(DefaultContext.flags[sig]) 1575 self.assertFalse(DefaultContext.flags[sig])
1653 1576
1654 DefaultContext.prec = save_prec 1577 DefaultContext.prec = save_prec
1655 DefaultContext.Emax = save_emax 1578 DefaultContext.Emax = save_emax
1656 DefaultContext.Emin = save_emin 1579 DefaultContext.Emin = save_emin
1657 return 1580 return
1658 1581
1659 @unittest.skipUnless(threading, 'threading required') 1582 @unittest.skipUnless(threading, 'threading required')
1660 class CThreadingTest(ThreadingTest): 1583 class CThreadingTest(ThreadingTest):
1661 decimal = C 1584 decimal = C
1662 @unittest.skipUnless(threading, 'threading required') 1585 @unittest.skipUnless(threading, 'threading required')
1663 class PyThreadingTest(ThreadingTest): 1586 class PyThreadingTest(ThreadingTest):
1664 decimal = P 1587 decimal = P
1665 1588
1666 class UsabilityTest(unittest.TestCase): 1589 class UsabilityTest(unittest.TestCase):
1667 '''Unit tests for Usability cases of Decimal.''' 1590 '''Unit tests for Usability cases of Decimal.'''
1668 1591
1669 def test_comparison_operators(self): 1592 def test_comparison_operators(self):
1670 if hasattr(C, 'setfailpoint'):
1671 random.seed(randseed)
1672 1593
1673 Decimal = self.decimal.Decimal 1594 Decimal = self.decimal.Decimal
1674 1595
1675 da = Decimal('23.42') 1596 da = Decimal('23.42')
1676 db = Decimal('23.42') 1597 db = Decimal('23.42')
1677 dc = Decimal('45') 1598 dc = Decimal('45')
1678 1599
1679 #two Decimals 1600 #two Decimals
1680 self.assertGreater(dc, da) 1601 self.assertGreater(dc, da)
1681 self.assertGreaterEqual(dc, da) 1602 self.assertGreaterEqual(dc, da)
(...skipping 106 matching lines...) Expand 10 before | Expand all | Expand 10 after
1788 def test_copy_and_deepcopy_methods(self): 1709 def test_copy_and_deepcopy_methods(self):
1789 Decimal = self.decimal.Decimal 1710 Decimal = self.decimal.Decimal
1790 1711
1791 d = Decimal('43.24') 1712 d = Decimal('43.24')
1792 c = copy.copy(d) 1713 c = copy.copy(d)
1793 self.assertEqual(id(c), id(d)) 1714 self.assertEqual(id(c), id(d))
1794 dc = copy.deepcopy(d) 1715 dc = copy.deepcopy(d)
1795 self.assertEqual(id(dc), id(d)) 1716 self.assertEqual(id(dc), id(d))
1796 1717
1797 def test_hash_method(self): 1718 def test_hash_method(self):
1798 if hasattr(C, 'setfailpoint'):
1799 random.seed(randseed)
1800 1719
1801 Decimal = self.decimal.Decimal 1720 Decimal = self.decimal.Decimal
1802 localcontext = self.decimal.localcontext 1721 localcontext = self.decimal.localcontext
1803 1722
1804 def hashit(d): 1723 def hashit(d):
1805 a = hash(d) 1724 a = hash(d)
1806 b = d.__hash__() 1725 b = d.__hash__()
1807 self.assertEqual(a, b) 1726 self.assertEqual(a, b)
1808 return a 1727 return a
1809 1728
1810 #just that it's hashable 1729 #just that it's hashable
1811 hashit(Decimal(23)) 1730 hashit(Decimal(23))
1812 hashit(Decimal('Infinity')) 1731 hashit(Decimal('Infinity'))
1813 hashit(Decimal('-Infinity')) 1732 hashit(Decimal('-Infinity'))
1814 hashit(Decimal('nan123')) 1733 hashit(Decimal('nan123'))
1815 hashit(Decimal('-NaN')) 1734 hashit(Decimal('-NaN'))
1816 1735
1817 test_values = [Decimal(sign*(2**m + n)) 1736 test_values = [Decimal(sign*(2**m + n))
1818 for m in [0, 14, 15, 16, 17, 30, 31, 1737 for m in [0, 14, 15, 16, 17, 30, 31,
1819 32, 33, 61, 62, 63, 64, 65, 66] 1738 32, 33, 61, 62, 63, 64, 65, 66]
1820 for n in range(-10, 10) 1739 for n in range(-10, 10)
1821 for sign in [-1, 1]] 1740 for sign in [-1, 1]]
1822 if hasattr(C, 'setfailpoint'):
1823 test_values = random.sample(test_values, 10)
1824 test_values.extend([ 1741 test_values.extend([
1825 Decimal("-1"), # ==> -2 1742 Decimal("-1"), # ==> -2
1826 Decimal("-0"), # zeros 1743 Decimal("-0"), # zeros
1827 Decimal("0.00"), 1744 Decimal("0.00"),
1828 Decimal("-0.000"), 1745 Decimal("-0.000"),
1829 Decimal("0E10"), 1746 Decimal("0E10"),
1830 Decimal("-0E12"), 1747 Decimal("-0E12"),
1831 Decimal("10.0"), # negative exponent 1748 Decimal("10.0"), # negative exponent
1832 Decimal("-23.00000"), 1749 Decimal("-23.00000"),
1833 Decimal("1230E100"), # positive exponent 1750 Decimal("1230E100"), # positive exponent
(...skipping 102 matching lines...) Expand 10 before | Expand all | Expand 10 after
1936 #floor 1853 #floor
1937 test_pairs = [ 1854 test_pairs = [
1938 ('123.00', 123), 1855 ('123.00', 123),
1939 ('3.2', 3), 1856 ('3.2', 3),
1940 ('3.54', 3), 1857 ('3.54', 3),
1941 ('3.899', 3), 1858 ('3.899', 3),
1942 ('-2.3', -3), 1859 ('-2.3', -3),
1943 ('-11.0', -11), 1860 ('-11.0', -11),
1944 ('0.0', 0), 1861 ('0.0', 0),
1945 ('-0E3', 0), 1862 ('-0E3', 0),
1863 ('89891211712379812736.1', 89891211712379812736),
1946 ] 1864 ]
1947 for d, i in test_pairs: 1865 for d, i in test_pairs:
1948 self.assertEqual(math.floor(Decimal(d)), i) 1866 self.assertEqual(math.floor(Decimal(d)), i)
1949 self.assertRaises(ValueError, math.floor, Decimal('-NaN')) 1867 self.assertRaises(ValueError, math.floor, Decimal('-NaN'))
1950 self.assertRaises(ValueError, math.floor, Decimal('sNaN')) 1868 self.assertRaises(ValueError, math.floor, Decimal('sNaN'))
1951 self.assertRaises(ValueError, math.floor, Decimal('NaN123')) 1869 self.assertRaises(ValueError, math.floor, Decimal('NaN123'))
1952 self.assertRaises(OverflowError, math.floor, Decimal('Inf')) 1870 self.assertRaises(OverflowError, math.floor, Decimal('Inf'))
1953 self.assertRaises(OverflowError, math.floor, Decimal('-Inf')) 1871 self.assertRaises(OverflowError, math.floor, Decimal('-Inf'))
1954 1872
1955 #ceiling 1873 #ceiling
1956 test_pairs = [ 1874 test_pairs = [
1957 ('123.00', 123), 1875 ('123.00', 123),
1958 ('3.2', 4), 1876 ('3.2', 4),
1959 ('3.54', 4), 1877 ('3.54', 4),
1960 ('3.899', 4), 1878 ('3.899', 4),
1961 ('-2.3', -2), 1879 ('-2.3', -2),
1962 ('-11.0', -11), 1880 ('-11.0', -11),
1963 ('0.0', 0), 1881 ('0.0', 0),
1964 ('-0E3', 0), 1882 ('-0E3', 0),
1883 ('89891211712379812736.1', 89891211712379812737),
1965 ] 1884 ]
1966 for d, i in test_pairs: 1885 for d, i in test_pairs:
1967 self.assertEqual(math.ceil(Decimal(d)), i) 1886 self.assertEqual(math.ceil(Decimal(d)), i)
1968 self.assertRaises(ValueError, math.ceil, Decimal('-NaN')) 1887 self.assertRaises(ValueError, math.ceil, Decimal('-NaN'))
1969 self.assertRaises(ValueError, math.ceil, Decimal('sNaN')) 1888 self.assertRaises(ValueError, math.ceil, Decimal('sNaN'))
1970 self.assertRaises(ValueError, math.ceil, Decimal('NaN123')) 1889 self.assertRaises(ValueError, math.ceil, Decimal('NaN123'))
1971 self.assertRaises(OverflowError, math.ceil, Decimal('Inf')) 1890 self.assertRaises(OverflowError, math.ceil, Decimal('Inf'))
1972 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf')) 1891 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf'))
1973 1892
1974 #round, single argument 1893 #round, single argument
(...skipping 231 matching lines...) Expand 10 before | Expand all | Expand 10 after
2206 r = pickle.loads(sy) 2125 r = pickle.loads(sy)
2207 self.assertIsInstance(r, C.Decimal) 2126 self.assertIsInstance(r, C.Decimal)
2208 self.assertEqual(r, x) 2127 self.assertEqual(r, x)
2209 2128
2210 sys.modules['decimal'] = savedecimal 2129 sys.modules['decimal'] = savedecimal
2211 2130
2212 def test_int(self): 2131 def test_int(self):
2213 Decimal = self.decimal.Decimal 2132 Decimal = self.decimal.Decimal
2214 ROUND_DOWN = self.decimal.ROUND_DOWN 2133 ROUND_DOWN = self.decimal.ROUND_DOWN
2215 2134
2216 lim = 10 if hasattr(C, 'setfailpoint') else 250 2135 for x in range(-250, 250):
2217 for x in range(-lim, lim):
2218 s = '%0.2f' % (x / 100.0) 2136 s = '%0.2f' % (x / 100.0)
2219 # should work the same as for floats 2137 # should work the same as for floats
2220 self.assertEqual(int(Decimal(s)), int(float(s))) 2138 self.assertEqual(int(Decimal(s)), int(float(s)))
2221 # should work the same as to_integral in the ROUND_DOWN mode 2139 # should work the same as to_integral in the ROUND_DOWN mode
2222 d = Decimal(s) 2140 d = Decimal(s)
2223 r = d.to_integral(ROUND_DOWN) 2141 r = d.to_integral(ROUND_DOWN)
2224 self.assertEqual(Decimal(int(d)), r) 2142 self.assertEqual(Decimal(int(d)), r)
2225 2143
2226 self.assertRaises(ValueError, int, Decimal('-nan')) 2144 self.assertRaises(ValueError, int, Decimal('-nan'))
2227 self.assertRaises(ValueError, int, Decimal('snan')) 2145 self.assertRaises(ValueError, int, Decimal('snan'))
2228 self.assertRaises(OverflowError, int, Decimal('inf')) 2146 self.assertRaises(OverflowError, int, Decimal('inf'))
2229 self.assertRaises(OverflowError, int, Decimal('-inf')) 2147 self.assertRaises(OverflowError, int, Decimal('-inf'))
2230 2148
2231 def test_trunc(self): 2149 def test_trunc(self):
2232 Decimal = self.decimal.Decimal 2150 Decimal = self.decimal.Decimal
2233 ROUND_DOWN = self.decimal.ROUND_DOWN 2151 ROUND_DOWN = self.decimal.ROUND_DOWN
2234 2152
2235 lim = 10 if hasattr(C, 'setfailpoint') else 250 2153 for x in range(-250, 250):
2236 for x in range(-lim, lim):
2237 s = '%0.2f' % (x / 100.0) 2154 s = '%0.2f' % (x / 100.0)
2238 # should work the same as for floats 2155 # should work the same as for floats
2239 self.assertEqual(int(Decimal(s)), int(float(s))) 2156 self.assertEqual(int(Decimal(s)), int(float(s)))
2240 # should work the same as to_integral in the ROUND_DOWN mode 2157 # should work the same as to_integral in the ROUND_DOWN mode
2241 d = Decimal(s) 2158 d = Decimal(s)
2242 r = d.to_integral(ROUND_DOWN) 2159 r = d.to_integral(ROUND_DOWN)
2243 self.assertEqual(Decimal(math.trunc(d)), r) 2160 self.assertEqual(Decimal(math.trunc(d)), r)
2244 2161
2245 def test_from_float(self): 2162 def test_from_float(self):
2246 if hasattr(C, 'setfailpoint'):
2247 random.seed(randseed)
2248 2163
2249 Decimal = self.decimal.Decimal 2164 Decimal = self.decimal.Decimal
2250 2165
2251 class MyDecimal(Decimal): 2166 class MyDecimal(Decimal):
2252 pass 2167 pass
2253 2168
2254 self.assertTrue(issubclass(MyDecimal, Decimal)) 2169 self.assertTrue(issubclass(MyDecimal, Decimal))
2255 2170
2256 r = MyDecimal.from_float(0.1) 2171 r = MyDecimal.from_float(0.1)
2257 self.assertEqual(type(r), MyDecimal) 2172 self.assertEqual(type(r), MyDecimal)
2258 self.assertEqual(str(r), 2173 self.assertEqual(str(r),
2259 '0.1000000000000000055511151231257827021181583404541015625') 2174 '0.1000000000000000055511151231257827021181583404541015625')
2260 bigint = 12345678901234567890123456789 2175 bigint = 12345678901234567890123456789
2261 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint)) 2176 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
2262 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan()) 2177 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
2263 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite()) 2178 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
2264 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite()) 2179 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
2265 self.assertEqual(str(MyDecimal.from_float(float('nan'))), 2180 self.assertEqual(str(MyDecimal.from_float(float('nan'))),
2266 str(Decimal('NaN'))) 2181 str(Decimal('NaN')))
2267 self.assertEqual(str(MyDecimal.from_float(float('inf'))), 2182 self.assertEqual(str(MyDecimal.from_float(float('inf'))),
2268 str(Decimal('Infinity'))) 2183 str(Decimal('Infinity')))
2269 self.assertEqual(str(MyDecimal.from_float(float('-inf'))), 2184 self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
2270 str(Decimal('-Infinity'))) 2185 str(Decimal('-Infinity')))
2271 self.assertRaises(TypeError, MyDecimal.from_float, 'abc') 2186 self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
2272 lim = 10 if hasattr(C, 'setfailpoint') else 200 2187 for i in range(200):
2273 for i in range(lim):
2274 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0) 2188 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
2275 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 2189 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip
2276 2190
2277 def test_create_decimal_from_float(self): 2191 def test_create_decimal_from_float(self):
2278 Decimal = self.decimal.Decimal 2192 Decimal = self.decimal.Decimal
2279 Context = self.decimal.Context 2193 Context = self.decimal.Context
2280 ROUND_DOWN = self.decimal.ROUND_DOWN 2194 ROUND_DOWN = self.decimal.ROUND_DOWN
2281 ROUND_UP = self.decimal.ROUND_UP 2195 ROUND_UP = self.decimal.ROUND_UP
2282 Inexact = self.decimal.Inexact 2196 Inexact = self.decimal.Inexact
2283 2197
(...skipping 177 matching lines...) Expand 10 before | Expand all | Expand 10 after
2461 self.assertRaises(TypeError, D("-1").copy_negate, context=xc) 2375 self.assertRaises(TypeError, D("-1").copy_negate, context=xc)
2462 2376
2463 class CPythonAPItests(PythonAPItests): 2377 class CPythonAPItests(PythonAPItests):
2464 decimal = C 2378 decimal = C
2465 class PyPythonAPItests(PythonAPItests): 2379 class PyPythonAPItests(PythonAPItests):
2466 decimal = P 2380 decimal = P
2467 2381
2468 class ContextAPItests(unittest.TestCase): 2382 class ContextAPItests(unittest.TestCase):
2469 2383
2470 def test_pickle(self): 2384 def test_pickle(self):
2471 if hasattr(C, 'setfailpoint'):
2472 random.seed(randseed)
2473 2385
2474 Context = self.decimal.Context 2386 Context = self.decimal.Context
2475 2387
2476 savedecimal = sys.modules['decimal'] 2388 savedecimal = sys.modules['decimal']
2477 2389
2478 # Round trip 2390 # Round trip
2479 sys.modules['decimal'] = self.decimal 2391 sys.modules['decimal'] = self.decimal
2480 c = Context() 2392 c = Context()
2481 e = pickle.loads(pickle.dumps(c)) 2393 e = pickle.loads(pickle.dumps(c))
2482 2394
2483 self.assertEqual(c.prec, e.prec) 2395 self.assertEqual(c.prec, e.prec)
2484 self.assertEqual(c.Emin, e.Emin) 2396 self.assertEqual(c.Emin, e.Emin)
2485 self.assertEqual(c.Emax, e.Emax) 2397 self.assertEqual(c.Emax, e.Emax)
2486 self.assertEqual(c.rounding, e.rounding) 2398 self.assertEqual(c.rounding, e.rounding)
2487 self.assertEqual(c.capitals, e.capitals) 2399 self.assertEqual(c.capitals, e.capitals)
2488 self.assertEqual(c.clamp, e.clamp) 2400 self.assertEqual(c.clamp, e.clamp)
2489 self.assertEqual(c.flags, e.flags) 2401 self.assertEqual(c.flags, e.flags)
2490 self.assertEqual(c.traps, e.traps) 2402 self.assertEqual(c.traps, e.traps)
2491 2403
2492 # Test interchangeability 2404 # Test interchangeability
2493 combinations = [(C, P), (P, C)] if C else [(P, P)] 2405 combinations = [(C, P), (P, C)] if C else [(P, P)]
2494 for dumper, loader in combinations: 2406 for dumper, loader in combinations:
2495 for ri, _ in enumerate(RoundingModes[dumper]): 2407 for ri, _ in enumerate(RoundingModes[dumper]):
2496 if hasattr(C, 'setfailpoint') and ri > 0: continue
2497 for fi, _ in enumerate(OrderedSignals[dumper]): 2408 for fi, _ in enumerate(OrderedSignals[dumper]):
2498 if hasattr(C, 'setfailpoint') and fi > 0: continue
2499 for ti, _ in enumerate(OrderedSignals[dumper]): 2409 for ti, _ in enumerate(OrderedSignals[dumper]):
2500 if hasattr(C, 'setfailpoint') and ti > 0: continue
2501 2410
2502 prec = random.randrange(1, 100) 2411 prec = random.randrange(1, 100)
2503 emin = random.randrange(-100, 0) 2412 emin = random.randrange(-100, 0)
2504 emax = random.randrange(1, 100) 2413 emax = random.randrange(1, 100)
2505 caps = random.randrange(2) 2414 caps = random.randrange(2)
2506 clamp = random.randrange(2) 2415 clamp = random.randrange(2)
2507 2416
2508 # One module dumps 2417 # One module dumps
2509 sys.modules['decimal'] = dumper 2418 sys.modules['decimal'] = dumper
2510 c = dumper.Context( 2419 c = dumper.Context(
(...skipping 941 matching lines...) Expand 10 before | Expand all | Expand 10 after
3452 try: 3361 try:
3453 BasicContext.prec = ExtendedContext.prec = 441 3362 BasicContext.prec = ExtendedContext.prec = 441
3454 for template in BasicContext, ExtendedContext: 3363 for template in BasicContext, ExtendedContext:
3455 setcontext(template) 3364 setcontext(template)
3456 c = getcontext() 3365 c = getcontext()
3457 self.assertIsNot(c, template) 3366 self.assertIsNot(c, template)
3458 self.assertEqual(c.prec, 441) 3367 self.assertEqual(c.prec, 441)
3459 except Exception as e: 3368 except Exception as e:
3460 ex = e.__class__ 3369 ex = e.__class__
3461 finally: 3370 finally:
3462 with protectfail(): 3371 BasicContext.prec = basic_context_prec
3463 BasicContext.prec = basic_context_prec 3372 ExtendedContext.prec = extended_context_prec
3464 ExtendedContext.prec = extended_context_prec 3373 setcontext(savecontext)
3465 setcontext(savecontext)
3466 if ex: 3374 if ex:
3467 raise ex 3375 raise ex
3468 3376
3469 def test_default_context(self): 3377 def test_default_context(self):
3470 DefaultContext = self.decimal.DefaultContext 3378 DefaultContext = self.decimal.DefaultContext
3471 BasicContext = self.decimal.BasicContext 3379 BasicContext = self.decimal.BasicContext
3472 ExtendedContext = self.decimal.ExtendedContext 3380 ExtendedContext = self.decimal.ExtendedContext
3473 getcontext = self.decimal.getcontext 3381 getcontext = self.decimal.getcontext
3474 setcontext = self.decimal.setcontext 3382 setcontext = self.decimal.setcontext
3475 InvalidOperation = self.decimal.InvalidOperation 3383 InvalidOperation = self.decimal.InvalidOperation
(...skipping 19 matching lines...) Expand all
3495 c = getcontext() 3403 c = getcontext()
3496 self.assertEqual(c.prec, saveprec) 3404 self.assertEqual(c.prec, saveprec)
3497 3405
3498 setcontext(DefaultContext) 3406 setcontext(DefaultContext)
3499 c = getcontext() 3407 c = getcontext()
3500 self.assertIsNot(c, DefaultContext) 3408 self.assertIsNot(c, DefaultContext)
3501 self.assertEqual(c.prec, 961) 3409 self.assertEqual(c.prec, 961)
3502 except Exception as e: 3410 except Exception as e:
3503 ex = e.__class__ 3411 ex = e.__class__
3504 finally: 3412 finally:
3505 with protectfail(): 3413 DefaultContext.prec = default_context_prec
3506 DefaultContext.prec = default_context_prec 3414 setcontext(savecontext)
3507 setcontext(savecontext)
3508 if ex: 3415 if ex:
3509 raise ex 3416 raise ex
3510 3417
3511 class CSpecialContexts(SpecialContexts): 3418 class CSpecialContexts(SpecialContexts):
3512 decimal = C 3419 decimal = C
3513 class PySpecialContexts(SpecialContexts): 3420 class PySpecialContexts(SpecialContexts):
3514 decimal = P 3421 decimal = P
3515 3422
3516 class ContextInputValidation(unittest.TestCase): 3423 class ContextInputValidation(unittest.TestCase):
3517 3424
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
3583 self.assertRaises(KeyError, Context, traps=["Q"]) 3490 self.assertRaises(KeyError, Context, traps=["Q"])
3584 3491
3585 # Type error in conversion 3492 # Type error in conversion
3586 self.assertRaises(TypeError, Context, flags=(0,1)) 3493 self.assertRaises(TypeError, Context, flags=(0,1))
3587 self.assertRaises(TypeError, Context, traps=(1,0)) 3494 self.assertRaises(TypeError, Context, traps=(1,0))
3588 3495
3589 class CContextInputValidation(ContextInputValidation): 3496 class CContextInputValidation(ContextInputValidation):
3590 decimal = C 3497 decimal = C
3591 class PyContextInputValidation(ContextInputValidation): 3498 class PyContextInputValidation(ContextInputValidation):
3592 decimal = P 3499 decimal = P
3500
3501 class CheckAttributes(unittest.TestCase):
3502
3503 def test_module_attributes(self):
3504
3505 # Architecture dependent context limits
3506 self.assertEqual(C.MAX_PREC, P.MAX_PREC)
3507 self.assertEqual(C.MAX_EMAX, P.MAX_EMAX)
3508 self.assertEqual(C.MIN_EMIN, P.MIN_EMIN)
3509 self.assertEqual(C.MIN_ETINY, P.MIN_ETINY)
3510
3511 self.assertTrue(C.HAVE_THREADS is True or C.HAVE_THREADS is False)
3512 self.assertTrue(P.HAVE_THREADS is True or P.HAVE_THREADS is False)
3513
3514 self.assertEqual(C.__version__, P.__version__)
3515
3516 x = dir(C)
3517 y = [s for s in dir(P) if '__' in s or not s.startswith('_')]
3518 self.assertEqual(set(x) - set(y), {'MallocError', 'FloatOperation'})
3519
3520 def test_context_attributes(self):
3521
3522 x = [s for s in dir(C.Context()) if '__' in s or not s.startswith('_')]
3523 y = [s for s in dir(P.Context()) if '__' in s or not s.startswith('_')]
3524 self.assertEqual(set(x) - set(y), set())
3525
3526 def test_decimal_attributes(self):
3527
3528 x = [s for s in dir(C.Decimal(9)) if '__' in s or not s.startswith('_')]
3529 y = [s for s in dir(C.Decimal(9)) if '__' in s or not s.startswith('_')]
3530 self.assertEqual(set(x) - set(y), set())
3593 3531
3594 class Coverage(unittest.TestCase): 3532 class Coverage(unittest.TestCase):
3595 3533
3596 def test_adjusted(self): 3534 def test_adjusted(self):
3597 Decimal = self.decimal.Decimal 3535 Decimal = self.decimal.Decimal
3598 3536
3599 self.assertEqual(Decimal('1234e9999').adjusted(), 10002) 3537 self.assertEqual(Decimal('1234e9999').adjusted(), 10002)
3600 # XXX raise? 3538 # XXX raise?
3601 self.assertEqual(Decimal('nan').adjusted(), 0) 3539 self.assertEqual(Decimal('nan').adjusted(), 0)
3602 self.assertEqual(Decimal('inf').adjusted(), 0) 3540 self.assertEqual(Decimal('inf').adjusted(), 0)
(...skipping 417 matching lines...) Expand 10 before | Expand all | Expand 10 after
4020 def test_py__round(self): 3958 def test_py__round(self):
4021 # Coverage 3959 # Coverage
4022 Decimal = P.Decimal 3960 Decimal = P.Decimal
4023 ROUND_UP = P.ROUND_UP 3961 ROUND_UP = P.ROUND_UP
4024 3962
4025 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP) 3963 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP)
4026 3964
4027 class CFunctionality(unittest.TestCase): 3965 class CFunctionality(unittest.TestCase):
4028 """Extra functionality in _decimal""" 3966 """Extra functionality in _decimal"""
4029 3967
3968 @requires_extra_functionality
4030 def test_c_ieee_context(self): 3969 def test_c_ieee_context(self):
4031 # issue 8786: Add support for IEEE 754 contexts to decimal module. 3970 # issue 8786: Add support for IEEE 754 contexts to decimal module.
4032 IEEEContext = C.IEEEContext 3971 IEEEContext = C.IEEEContext
4033 DECIMAL32 = C.DECIMAL32 3972 DECIMAL32 = C.DECIMAL32
4034 DECIMAL64 = C.DECIMAL64 3973 DECIMAL64 = C.DECIMAL64
4035 DECIMAL128 = C.DECIMAL128 3974 DECIMAL128 = C.DECIMAL128
4036 3975
4037 def assert_rest(self, context): 3976 def assert_rest(self, context):
4038 self.assertEqual(context.clamp, 1) 3977 self.assertEqual(context.clamp, 1)
4039 assert_signals(self, context, 'traps', []) 3978 assert_signals(self, context, 'traps', [])
(...skipping 138 matching lines...) Expand 10 before | Expand all | Expand 10 after
4178 test_containers(c, sig) 4117 test_containers(c, sig)
4179 4118
4180 c.traps[FloatOperation] = True 4119 c.traps[FloatOperation] = True
4181 doit(c, signal=FloatOperation) 4120 doit(c, signal=FloatOperation)
4182 test_containers(c, FloatOperation) 4121 test_containers(c, FloatOperation)
4183 4122
4184 def test_c_float_operation_default(self): 4123 def test_c_float_operation_default(self):
4185 Decimal = C.Decimal 4124 Decimal = C.Decimal
4186 Context = C.Context 4125 Context = C.Context
4187 Inexact = C.Inexact 4126 Inexact = C.Inexact
4188 DecInexact = C.DecInexact
4189 FloatOperation= C.FloatOperation 4127 FloatOperation= C.FloatOperation
4190 DecFloatOperation= C.DecFloatOperation
4191 4128
4192 context = Context() 4129 context = Context()
4193 self.assertFalse(context.flags[FloatOperation]) 4130 self.assertFalse(context.flags[FloatOperation])
4194 self.assertFalse(context.traps[FloatOperation]) 4131 self.assertFalse(context.traps[FloatOperation])
4195 self.assertFalse(context._flags&DecFloatOperation)
4196 self.assertFalse(context._traps&DecFloatOperation)
4197 4132
4198 context.clear_traps() 4133 context.clear_traps()
4199 context.traps[Inexact] = True 4134 context.traps[Inexact] = True
4200 context.traps[FloatOperation] = True 4135 context.traps[FloatOperation] = True
4201 self.assertEqual(context._traps, DecInexact|DecFloatOperation)
4202 self.assertTrue(context.traps[FloatOperation]) 4136 self.assertTrue(context.traps[FloatOperation])
4203 self.assertTrue(context.traps[Inexact]) 4137 self.assertTrue(context.traps[Inexact])
4204 4138
4139 @requires_extra_functionality
4205 def test_c_context(self): 4140 def test_c_context(self):
4206 Context = C.Context 4141 Context = C.Context
4207 4142
4208 c = Context(flags=C.DecClamped, traps=C.DecRounded) 4143 c = Context(flags=C.DecClamped, traps=C.DecRounded)
4209 self.assertEqual(c._flags, C.DecClamped) 4144 self.assertEqual(c._flags, C.DecClamped)
4210 self.assertEqual(c._traps, C.DecRounded) 4145 self.assertEqual(c._traps, C.DecRounded)
4211 4146
4147 @requires_extra_functionality
4212 def test_constants(self): 4148 def test_constants(self):
4213 # Condition flags 4149 # Condition flags
4214 cond = ( 4150 cond = (
4215 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero, 4151 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero,
4216 C.DecDivisionImpossible, C.DecDivisionUndefined, 4152 C.DecDivisionImpossible, C.DecDivisionUndefined,
4217 C.DecFpuError, C.DecInexact, C.DecInvalidContext, 4153 C.DecFpuError, C.DecInexact, C.DecInvalidContext,
4218 C.DecInvalidOperation, C.DecMallocError, 4154 C.DecInvalidOperation, C.DecMallocError,
4219 C.DecFloatOperation, C.DecOverflow, C.DecRounded, 4155 C.DecFloatOperation, C.DecOverflow, C.DecRounded,
4220 C.DecSubnormal, C.DecUnderflow 4156 C.DecSubnormal, C.DecUnderflow
4221 ) 4157 )
4222 4158
4223 # Architecture dependent context limits
4224 if C.MAX_EMAX > 425000000:
4225 self.assertEqual(C.MAX_PREC, 999999999999999999)
4226 self.assertEqual(C.MAX_EMAX, 999999999999999999)
4227 self.assertEqual(C.MIN_EMIN, -999999999999999999)
4228 self.assertEqual(C.MIN_ETINY, -1999999999999999997)
4229 else:
4230 self.assertEqual(C.MAX_PREC, 425000000)
4231 self.assertEqual(C.MAX_EMAX, 425000000)
4232 self.assertEqual(C.MIN_EMIN, -425000000)
4233 self.assertEqual(C.MIN_ETINY, -849999999)
4234
4235 # IEEEContext 4159 # IEEEContext
4236 self.assertEqual(C.DECIMAL32, 32) 4160 self.assertEqual(C.DECIMAL32, 32)
4237 self.assertEqual(C.DECIMAL64, 64) 4161 self.assertEqual(C.DECIMAL64, 64)
4238 self.assertEqual(C.DECIMAL128, 128) 4162 self.assertEqual(C.DECIMAL128, 128)
4239 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512) 4163 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512)
4240 4164
4241 # Rounding modes 4165 # Rounding modes
4242 for i, v in enumerate(RoundingModes[C]): 4166 for i, v in enumerate(RoundingModes[C]):
4243 self.assertEqual(v, i) 4167 self.assertEqual(v, i)
4244 self.assertEqual(C.ROUND_TRUNC, 8) 4168 self.assertEqual(C.ROUND_TRUNC, 8)
(...skipping 16 matching lines...) Expand all
4261 C.DecDivisionByZero) 4185 C.DecDivisionByZero)
4262 4186
4263 self.assertEqual(C.DecTraps, 4187 self.assertEqual(C.DecTraps,
4264 C.DecErrors|C.DecOverflow|C.DecUnderflow) 4188 C.DecErrors|C.DecOverflow|C.DecUnderflow)
4265 4189
4266 class CWhitebox(unittest.TestCase): 4190 class CWhitebox(unittest.TestCase):
4267 """Whitebox testing for _decimal""" 4191 """Whitebox testing for _decimal"""
4268 4192
4269 def test_bignum(self): 4193 def test_bignum(self):
4270 # Not exactly whitebox, but too slow with pydecimal. 4194 # Not exactly whitebox, but too slow with pydecimal.
4271 if hasattr(C, 'setfailpoint'):
4272 random.seed(randseed)
4273 4195
4274 Decimal = C.Decimal 4196 Decimal = C.Decimal
4275 localcontext = C.localcontext 4197 localcontext = C.localcontext
4276 4198
4277 b1 = 10**35 4199 b1 = 10**35
4278 b2 = 10**36 4200 b2 = 10**36
4279 with localcontext() as c: 4201 with localcontext() as c:
4280 c.prec = 1000000 4202 c.prec = 1000000
4281 r = 1 if hasattr(C, 'setfailpoint') else 5 4203 for i in range(5):
4282 for i in range(r):
4283 a = random.randrange(b1, b2) 4204 a = random.randrange(b1, b2)
4284 b = random.randrange(1000, 1200) 4205 b = random.randrange(1000, 1200)
4285 x = a ** b 4206 x = a ** b
4286 y = Decimal(a) ** Decimal(b) 4207 y = Decimal(a) ** Decimal(b)
4287 self.assertEqual(x, y) 4208 self.assertEqual(x, y)
4288 4209
4289 def test_invalid_construction(self): 4210 def test_invalid_construction(self):
4290 self.assertRaises(TypeError, C.Decimal, 9, "xyz") 4211 self.assertRaises(TypeError, C.Decimal, 9, "xyz")
4291 4212
4292 def test_c_input_restriction(self): 4213 def test_c_input_restriction(self):
(...skipping 75 matching lines...) Expand 10 before | Expand all | Expand 10 after
4368 # Overflow in conversion 4289 # Overflow in conversion
4369 self.assertRaises(OverflowError, Context, prec=int_max+1) 4290 self.assertRaises(OverflowError, Context, prec=int_max+1)
4370 self.assertRaises(OverflowError, Context, Emax=int_max+1) 4291 self.assertRaises(OverflowError, Context, Emax=int_max+1)
4371 self.assertRaises(OverflowError, Context, Emin=-int_max-2) 4292 self.assertRaises(OverflowError, Context, Emin=-int_max-2)
4372 self.assertRaises(OverflowError, Context, rounding=int_max+1) 4293 self.assertRaises(OverflowError, Context, rounding=int_max+1)
4373 self.assertRaises(OverflowError, Context, clamp=int_max+1) 4294 self.assertRaises(OverflowError, Context, clamp=int_max+1)
4374 self.assertRaises(OverflowError, Context, capitals=int_max+1) 4295 self.assertRaises(OverflowError, Context, capitals=int_max+1)
4375 self.assertRaises(OverflowError, Context, _allcr=int_max+1) 4296 self.assertRaises(OverflowError, Context, _allcr=int_max+1)
4376 4297
4377 # OverflowError, general ValueError 4298 # OverflowError, general ValueError
4378 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp', '_allcr'): 4299 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp'):
4379 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4300 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4380 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4301 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4381 if sys.platform != 'win32': 4302 if sys.platform != 'win32':
4382 self.assertRaises(ValueError, setattr, c, attr, int_max) 4303 self.assertRaises(ValueError, setattr, c, attr, int_max)
4383 self.assertRaises(ValueError, setattr, c, attr, -int_max-1) 4304 self.assertRaises(ValueError, setattr, c, attr, -int_max-1)
4384 4305
4385 # OverflowError, general TypeError 4306 # OverflowError, general TypeError
4386 for attr in ('rounding', '_flags', '_traps'): 4307 for attr in ('rounding',):
4387 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4308 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4388 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4309 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4389 if sys.platform != 'win32': 4310 if sys.platform != 'win32':
4390 self.assertRaises(TypeError, setattr, c, attr, int_max) 4311 self.assertRaises(TypeError, setattr, c, attr, int_max)
4391 self.assertRaises(TypeError, setattr, c, attr, -int_max-1) 4312 self.assertRaises(TypeError, setattr, c, attr, -int_max-1)
4392 4313
4393 # OverflowError: unsafe_prec, unsafe_emin, unsafe_emax 4314 # OverflowError: _unsafe_setprec, _unsafe_setemin, _unsafe_setemax
4394 self.assertRaises(OverflowError, getattr(c, 'unsafe_setprec'), int_max+1 ) 4315 if C.MAX_PREC == 425000000:
4395 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemax'), int_max+1 ) 4316 self.assertRaises(OverflowError, getattr(c, '_unsafe_setprec'),
4396 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemin'), -int_max- 2) 4317 int_max+1)
4397 4318 self.assertRaises(OverflowError, getattr(c, '_unsafe_setemax'),
4398 # capitals, clamp, _allcr 4319 int_max+1)
4399 for attr in ['capitals', 'clamp', '_allcr']: 4320 self.assertRaises(OverflowError, getattr(c, '_unsafe_setemin'),
4321 -int_max-2)
4322
4323 # ValueError: _unsafe_setprec, _unsafe_setemin, _unsafe_setemax
4324 if C.MAX_PREC == 425000000:
4325 self.assertRaises(ValueError, getattr(c, '_unsafe_setprec'), 0)
4326 self.assertRaises(ValueError, getattr(c, '_unsafe_setprec'),
4327 1070000001)
4328 self.assertRaises(ValueError, getattr(c, '_unsafe_setemax'), -1)
4329 self.assertRaises(ValueError, getattr(c, '_unsafe_setemax'),
4330 1070000001)
4331 self.assertRaises(ValueError, getattr(c, '_unsafe_setemin'),
4332 -1070000001)
4333 self.assertRaises(ValueError, getattr(c, '_unsafe_setemin'), 1)
4334
4335 # capitals, clamp
4336 for attr in ['capitals', 'clamp']:
4400 self.assertRaises(ValueError, setattr, c, attr, -1) 4337 self.assertRaises(ValueError, setattr, c, attr, -1)
4401 self.assertRaises(ValueError, setattr, c, attr, 2) 4338 self.assertRaises(ValueError, setattr, c, attr, 2)
4402 self.assertRaises(TypeError, setattr, c, attr, [1,2,3]) 4339 self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
4403 if HAVE_CONFIG_64: 4340 if HAVE_CONFIG_64:
4404 self.assertRaises(ValueError, setattr, c, attr, 2**32) 4341 self.assertRaises(ValueError, setattr, c, attr, 2**32)
4405 self.assertRaises(ValueError, setattr, c, attr, 2**32+1) 4342 self.assertRaises(ValueError, setattr, c, attr, 2**32+1)
4406 4343
4344 # Invalid local context
4345 self.assertRaises(TypeError, exec, 'with localcontext("xyz"): pass',
4346 locals())
4347
4348 # setcontext
4349 saved_context = getcontext()
4350 self.assertRaises(TypeError, setcontext, "xyz")
4351 setcontext(saved_context)
4352
4353 @requires_extra_functionality
4354 def test_c_context_errors_extra(self):
4355 Context = C.Context
4356 InvalidOperation = C.InvalidOperation
4357 Overflow = C.Overflow
4358 localcontext = C.localcontext
4359 getcontext = C.getcontext
4360 setcontext = C.setcontext
4361 HAVE_CONFIG_64 = (C.MAX_PREC > 425000000)
4362
4363 c = Context()
4364
4365 # Input corner cases
4366 int_max = 2**63-1 if HAVE_CONFIG_64 else 2**31-1
4367
4368 # OverflowError, general ValueError
4369 self.assertRaises(OverflowError, setattr, c, '_allcr', int_max+1)
4370 self.assertRaises(OverflowError, setattr, c, '_allcr', -int_max-2)
4371 if sys.platform != 'win32':
4372 self.assertRaises(ValueError, setattr, c, '_allcr', int_max)
4373 self.assertRaises(ValueError, setattr, c, '_allcr', -int_max-1)
4374
4375 # OverflowError, general TypeError
4376 for attr in ('_flags', '_traps'):
4377 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4378 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4379 if sys.platform != 'win32':
4380 self.assertRaises(TypeError, setattr, c, attr, int_max)
4381 self.assertRaises(TypeError, setattr, c, attr, -int_max-1)
4382
4383 # _allcr
4384 self.assertRaises(ValueError, setattr, c, '_allcr', -1)
4385 self.assertRaises(ValueError, setattr, c, '_allcr', 2)
4386 self.assertRaises(TypeError, setattr, c, '_allcr', [1,2,3])
4387 if HAVE_CONFIG_64:
4388 self.assertRaises(ValueError, setattr, c, '_allcr', 2**32)
4389 self.assertRaises(ValueError, setattr, c, '_allcr', 2**32+1)
4390
4407 self.assertRaises(ValueError, Context, _allcr=2) 4391 self.assertRaises(ValueError, Context, _allcr=2)
4408 4392
4409 # _flags, _traps 4393 # _flags, _traps
4410 for attr in ['_flags', '_traps']: 4394 for attr in ['_flags', '_traps']:
4411 self.assertRaises(TypeError, setattr, c, attr, 999999) 4395 self.assertRaises(TypeError, setattr, c, attr, 999999)
4412 self.assertRaises(TypeError, setattr, c, attr, 'x') 4396 self.assertRaises(TypeError, setattr, c, attr, 'x')
4413
4414 # Invalid local context
4415 self.assertRaises(TypeError, exec, 'with localcontext("xyz"): pass',
4416 locals())
4417
4418 # setcontext
4419 saved_context = getcontext()
4420 self.assertRaises(TypeError, setcontext, "xyz")
4421 setcontext(saved_context)
4422 4397
4423 def test_c_valid_context(self): 4398 def test_c_valid_context(self):
4424 # These tests are for code coverage in _decimal. 4399 # These tests are for code coverage in _decimal.
4425 DefaultContext = C.DefaultContext 4400 DefaultContext = C.DefaultContext
4426 ROUND_HALF_UP = C.ROUND_HALF_UP 4401 ROUND_HALF_UP = C.ROUND_HALF_UP
4427 Clamped = C.Clamped 4402 Clamped = C.Clamped
4428 Underflow = C.Underflow 4403 Underflow = C.Underflow
4429 Inexact = C.Inexact 4404 Inexact = C.Inexact
4430 Rounded = C.Rounded 4405 Rounded = C.Rounded
4431 Subnormal = C.Subnormal 4406 Subnormal = C.Subnormal
4432 DecClamped = C.DecClamped
4433 DecUnderflow = C.DecUnderflow
4434 DecInexact = C.DecInexact
4435 DecRounded = C.DecRounded
4436 DecSubnormal = C.DecSubnormal
4437 4407
4438 c = DefaultContext.copy() 4408 c = DefaultContext.copy()
4439 4409
4440 # Exercise all getters and setters 4410 # Exercise all getters and setters
4441 c.prec = 34 4411 c.prec = 34
4442 c.rounding = ROUND_HALF_UP 4412 c.rounding = ROUND_HALF_UP
4443 c.Emax = 3000 4413 c.Emax = 3000
4444 c.Emin = -3000 4414 c.Emin = -3000
4445 c.capitals = 1 4415 c.capitals = 1
4446 c.clamp = 0 4416 c.clamp = 0
4447 c._flags = DecUnderflow
4448 c._traps = DecClamped
4449 c._allcr = 0
4450 4417
4451 self.assertEqual(c.prec, 34) 4418 self.assertEqual(c.prec, 34)
4452 self.assertEqual(c.rounding, ROUND_HALF_UP) 4419 self.assertEqual(c.rounding, ROUND_HALF_UP)
4453 self.assertEqual(c.Emin, -3000) 4420 self.assertEqual(c.Emin, -3000)
4454 self.assertEqual(c.Emax, 3000) 4421 self.assertEqual(c.Emax, 3000)
4455 self.assertEqual(c.capitals, 1) 4422 self.assertEqual(c.capitals, 1)
4456 self.assertEqual(c.clamp, 0) 4423 self.assertEqual(c.clamp, 0)
4457 self.assertEqual(c._flags, DecUnderflow)
4458 self.assertEqual(c._traps, DecClamped)
4459 self.assertEqual(c._allcr, 0)
4460 4424
4461 self.assertEqual(c.Etiny(), -3033) 4425 self.assertEqual(c.Etiny(), -3033)
4462 self.assertEqual(c.Etop(), 2967) 4426 self.assertEqual(c.Etop(), 2967)
4463 4427
4464 # Exercise all unsafe setters 4428 # Exercise all unsafe setters
4465 c.unsafe_setprec(999999999) 4429 if C.MAX_PREC == 425000000:
4466 c.unsafe_setemax(999999999) 4430 c._unsafe_setprec(999999999)
4467 c.unsafe_setemin(-999999999) 4431 c._unsafe_setemax(999999999)
4468 4432 c._unsafe_setemin(-999999999)
4469 self.assertEqual(c.prec, 999999999) 4433 self.assertEqual(c.prec, 999999999)
4470 self.assertEqual(c.Emax, 999999999) 4434 self.assertEqual(c.Emax, 999999999)
4471 self.assertEqual(c.Emin, -999999999) 4435 self.assertEqual(c.Emin, -999999999)
4472 4436
4473 def test_c_round(self): 4437 def test_c_round(self):
4474 # Restricted input. 4438 # Restricted input.
4475 Decimal = C.Decimal 4439 Decimal = C.Decimal
4476 InvalidOperation = C.InvalidOperation 4440 InvalidOperation = C.InvalidOperation
4477 localcontext = C.localcontext 4441 localcontext = C.localcontext
4478 MAX_EMAX = C.MAX_EMAX 4442 MAX_EMAX = C.MAX_EMAX
4479 MIN_ETINY = C.MIN_ETINY 4443 MIN_ETINY = C.MIN_ETINY
4480 int_max = 2**63-1 if C.MAX_PREC > 425000000 else 2**31-1 4444 int_max = 2**63-1 if C.MAX_PREC > 425000000 else 2**31-1
4481 4445
(...skipping 117 matching lines...) Expand 10 before | Expand all | Expand 10 after
4599 c.clear_flags() 4563 c.clear_flags()
4600 c.traps[InvalidOperation] = True 4564 c.traps[InvalidOperation] = True
4601 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0) 4565 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0)
4602 self.assertRaises(InvalidOperation, c.divmod, 9, 0) 4566 self.assertRaises(InvalidOperation, c.divmod, 9, 0)
4603 self.assertTrue(c.flags[DivisionByZero]) 4567 self.assertTrue(c.flags[DivisionByZero])
4604 4568
4605 c.traps[InvalidOperation] = True 4569 c.traps[InvalidOperation] = True
4606 c.prec = 2 4570 c.prec = 2
4607 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501) 4571 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501)
4608 4572
4573 @requires_extra_functionality
4609 def test_c_context_templates(self): 4574 def test_c_context_templates(self):
4610 self.assertEqual( 4575 self.assertEqual(
4611 C.BasicContext._traps, 4576 C.BasicContext._traps,
4612 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow| 4577 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow|
4613 C.DecUnderflow|C.DecClamped 4578 C.DecUnderflow|C.DecClamped
4614 ) 4579 )
4615 self.assertEqual( 4580 self.assertEqual(
4616 C.DefaultContext._traps, 4581 C.DefaultContext._traps,
4617 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow 4582 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow
4618 ) 4583 )
4619 4584
4585 @requires_extra_functionality
4620 def test_c_signal_dict(self): 4586 def test_c_signal_dict(self):
4621 if hasattr(C, 'setfailpoint'):
4622 random.seed(randseed)
4623 4587
4624 # SignalDict coverage 4588 # SignalDict coverage
4625 Context = C.Context 4589 Context = C.Context
4626 DefaultContext = C.DefaultContext 4590 DefaultContext = C.DefaultContext
4627 4591
4628 InvalidOperation = C.InvalidOperation 4592 InvalidOperation = C.InvalidOperation
4629 DivisionByZero = C.DivisionByZero 4593 DivisionByZero = C.DivisionByZero
4630 Overflow = C.Overflow 4594 Overflow = C.Overflow
4631 Subnormal = C.Subnormal 4595 Subnormal = C.Subnormal
4632 Underflow = C.Underflow 4596 Underflow = C.Underflow
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
4700 Overflow: C.DecOverflow, 4664 Overflow: C.DecOverflow,
4701 DivisionByZero: C.DecDivisionByZero, 4665 DivisionByZero: C.DecDivisionByZero,
4702 InvalidOperation: C.DecIEEEInvalidOperation 4666 InvalidOperation: C.DecIEEEInvalidOperation
4703 } 4667 }
4704 IntCond = [ 4668 IntCond = [
4705 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError, 4669 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError,
4706 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError, 4670 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError,
4707 C.DecConversionSyntax, 4671 C.DecConversionSyntax,
4708 ] 4672 ]
4709 4673
4710 lim = 1 if hasattr(C, 'setfailpoint') else len(OrderedSignals[C]) 4674 lim = len(OrderedSignals[C])
4711 for r in range(lim): 4675 for r in range(lim):
4712 for t in range(lim): 4676 for t in range(lim):
4713 for round in RoundingModes[C]: 4677 for round in RoundingModes[C]:
4714 flags = random.sample(OrderedSignals[C], r) 4678 flags = random.sample(OrderedSignals[C], r)
4715 traps = random.sample(OrderedSignals[C], t) 4679 traps = random.sample(OrderedSignals[C], t)
4716 prec = random.randrange(1, 10000) 4680 prec = random.randrange(1, 10000)
4717 emin = random.randrange(-10000, 0) 4681 emin = random.randrange(-10000, 0)
4718 emax = random.randrange(0, 10000) 4682 emax = random.randrange(0, 10000)
4719 clamp = random.randrange(0, 2) 4683 clamp = random.randrange(0, 2)
4720 caps = random.randrange(0, 2) 4684 caps = random.randrange(0, 2)
(...skipping 83 matching lines...) Expand 10 before | Expand all | Expand 10 after
4804 CContextInputValidation, PyContextInputValidation, 4768 CContextInputValidation, PyContextInputValidation,
4805 CCoverage, PyCoverage, 4769 CCoverage, PyCoverage,
4806 CFunctionality, PyFunctionality, 4770 CFunctionality, PyFunctionality,
4807 CWhitebox, PyWhitebox, 4771 CWhitebox, PyWhitebox,
4808 CIBMTestCases, PyIBMTestCases, 4772 CIBMTestCases, PyIBMTestCases,
4809 ] 4773 ]
4810 4774
4811 # Delete C tests if _decimal.so is not present. 4775 # Delete C tests if _decimal.so is not present.
4812 if not C: 4776 if not C:
4813 all_tests = all_tests[1::2] 4777 all_tests = all_tests[1::2]
4814 4778 else:
4815 # Wrap test functions for testing api failures. Doing this in 4779 all_tests.insert(0, CheckAttributes)
4816 # test_main() causes spurious refleaks, so it is done here. 4780
4817 if hasattr(C, 'setapicalls'):
4818 for cls in all_tests:
4819 if cls == CIBMTestCases or cls == PyIBMTestCases:
4820 newfunc = withFailpoint(getattr(cls, 'eval_equation'))
4821 setattr(cls, 'eval_equation', newfunc)
4822 else:
4823 for attr in dir(cls):
4824 if attr.startswith('test_'):
4825 if attr == 'test_threading':
4826 continue
4827 newfunc = withFailpoint(getattr(cls, attr))
4828 setattr(cls, attr, newfunc)
4829 4781
4830 def test_main(arith=False, verbose=None, todo_tests=None, debug=None): 4782 def test_main(arith=False, verbose=None, todo_tests=None, debug=None):
4831 """ Execute the tests. 4783 """ Execute the tests.
4832 4784
4833 Runs all arithmetic tests if arith is True or if the "decimal" resource 4785 Runs all arithmetic tests if arith is True or if the "decimal" resource
4834 is enabled in regrtest.py 4786 is enabled in regrtest.py
4835 """ 4787 """
4836 4788
4837 init(C) 4789 init(C)
4838 init(P) 4790 init(P)
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
4888 p.add_option('--debug', '-d', action='store_true', help='shows the test numb er and context before each test') 4840 p.add_option('--debug', '-d', action='store_true', help='shows the test numb er and context before each test')
4889 p.add_option('--skip', '-s', action='store_true', help='skip over 90% of th e arithmetic tests') 4841 p.add_option('--skip', '-s', action='store_true', help='skip over 90% of th e arithmetic tests')
4890 (opt, args) = p.parse_args() 4842 (opt, args) = p.parse_args()
4891 4843
4892 if opt.skip: 4844 if opt.skip:
4893 test_main(arith=False, verbose=True) 4845 test_main(arith=False, verbose=True)
4894 elif args: 4846 elif args:
4895 test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug) 4847 test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug)
4896 else: 4848 else:
4897 test_main(arith=True, verbose=True) 4849 test_main(arith=True, verbose=True)
LEFTRIGHT

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+