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

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, 6 months ago
Right Patch Set: Created 7 years, 3 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 161 matching lines...) Expand 10 before | Expand all | Expand 10 after
1020 944
1021 ('g', '0', '0'), 945 ('g', '0', '0'),
1022 ('g', '0.0', '0.0'), 946 ('g', '0.0', '0.0'),
1023 ('g', '0E1', '0e+1'), 947 ('g', '0E1', '0e+1'),
1024 ('G', '0E1', '0E+1'), 948 ('G', '0E1', '0E+1'),
1025 ('g', '0E-5', '0.00000'), 949 ('g', '0E-5', '0.00000'),
1026 ('g', '0E-6', '0.000000'), 950 ('g', '0E-6', '0.000000'),
1027 ('g', '0E-7', '0e-7'), 951 ('g', '0E-7', '0e-7'),
1028 ('g', '-0E2', '-0e+2'), 952 ('g', '-0E2', '-0e+2'),
1029 ('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig 953 ('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig
954 ('.0n', '3.14159265', '3'), # same for 'n'
1030 ('.1g', '3.14159265', '3'), 955 ('.1g', '3.14159265', '3'),
1031 ('.2g', '3.14159265', '3.1'), 956 ('.2g', '3.14159265', '3.1'),
1032 ('.5g', '3.14159265', '3.1416'), 957 ('.5g', '3.14159265', '3.1416'),
1033 ('.7g', '3.14159265', '3.141593'), 958 ('.7g', '3.14159265', '3.141593'),
1034 ('.8g', '3.14159265', '3.1415926'), # round-half-even! 959 ('.8g', '3.14159265', '3.1415926'), # round-half-even!
1035 ('.9g', '3.14159265', '3.14159265'), 960 ('.9g', '3.14159265', '3.14159265'),
1036 ('.10g', '3.14159265', '3.14159265'), # don't pad 961 ('.10g', '3.14159265', '3.14159265'), # don't pad
1037 962
1038 ('%', '0E1', '0%'), 963 ('%', '0E1', '0%'),
1039 ('%', '0E0', '0%'), 964 ('%', '0E0', '0%'),
(...skipping 586 matching lines...) Expand 10 before | Expand all | Expand 10 after
1626 # Test the "threading isolation" of a Context. Also test changing 1551 # Test the "threading isolation" of a Context. Also test changing
1627 # the DefaultContext, which acts as a template for the thread-local 1552 # the DefaultContext, which acts as a template for the thread-local
1628 # contexts. 1553 # contexts.
1629 save_prec = DefaultContext.prec 1554 save_prec = DefaultContext.prec
1630 save_emax = DefaultContext.Emax 1555 save_emax = DefaultContext.Emax
1631 save_emin = DefaultContext.Emin 1556 save_emin = DefaultContext.Emin
1632 DefaultContext.prec = 24 1557 DefaultContext.prec = 24
1633 DefaultContext.Emax = 425000000 1558 DefaultContext.Emax = 425000000
1634 DefaultContext.Emin = -425000000 1559 DefaultContext.Emin = -425000000
1635 1560
1636 with protectfail(): 1561 self.synchro = threading.Event()
1637 self.synchro = threading.Event() 1562 self.finish1 = threading.Event()
1638 self.finish1 = threading.Event() 1563 self.finish2 = threading.Event()
1639 self.finish2 = threading.Event() 1564
1640 1565 th1 = threading.Thread(target=thfunc1, args=(self,))
1641 th1 = threading.Thread(target=thfunc1, args=(self,)) 1566 th2 = threading.Thread(target=thfunc2, args=(self,))
1642 th2 = threading.Thread(target=thfunc2, args=(self,)) 1567
1643 1568 th1.start()
1644 th1.start() 1569 th2.start()
1645 th2.start() 1570
1646 1571 self.finish1.wait()
1647 self.finish1.wait() 1572 self.finish2.wait()
1648 self.finish2.wait()
1649 1573
1650 for sig in Signals[self.decimal]: 1574 for sig in Signals[self.decimal]:
1651 self.assertFalse(DefaultContext.flags[sig]) 1575 self.assertFalse(DefaultContext.flags[sig])
1652 1576
1653 DefaultContext.prec = save_prec 1577 DefaultContext.prec = save_prec
1654 DefaultContext.Emax = save_emax 1578 DefaultContext.Emax = save_emax
1655 DefaultContext.Emin = save_emin 1579 DefaultContext.Emin = save_emin
1656 return 1580 return
1657 1581
1658 @unittest.skipUnless(threading, 'threading required') 1582 @unittest.skipUnless(threading, 'threading required')
1659 class CThreadingTest(ThreadingTest): 1583 class CThreadingTest(ThreadingTest):
1660 decimal = C 1584 decimal = C
1661 @unittest.skipUnless(threading, 'threading required') 1585 @unittest.skipUnless(threading, 'threading required')
1662 class PyThreadingTest(ThreadingTest): 1586 class PyThreadingTest(ThreadingTest):
1663 decimal = P 1587 decimal = P
1664 1588
1665 class UsabilityTest(unittest.TestCase): 1589 class UsabilityTest(unittest.TestCase):
1666 '''Unit tests for Usability cases of Decimal.''' 1590 '''Unit tests for Usability cases of Decimal.'''
1667 1591
1668 def test_comparison_operators(self): 1592 def test_comparison_operators(self):
1669 if hasattr(C, 'setfailpoint'):
1670 random.seed(randseed)
1671 1593
1672 Decimal = self.decimal.Decimal 1594 Decimal = self.decimal.Decimal
1673 1595
1674 da = Decimal('23.42') 1596 da = Decimal('23.42')
1675 db = Decimal('23.42') 1597 db = Decimal('23.42')
1676 dc = Decimal('45') 1598 dc = Decimal('45')
1677 1599
1678 #two Decimals 1600 #two Decimals
1679 self.assertGreater(dc, da) 1601 self.assertGreater(dc, da)
1680 self.assertGreaterEqual(dc, da) 1602 self.assertGreaterEqual(dc, da)
(...skipping 106 matching lines...) Expand 10 before | Expand all | Expand 10 after
1787 def test_copy_and_deepcopy_methods(self): 1709 def test_copy_and_deepcopy_methods(self):
1788 Decimal = self.decimal.Decimal 1710 Decimal = self.decimal.Decimal
1789 1711
1790 d = Decimal('43.24') 1712 d = Decimal('43.24')
1791 c = copy.copy(d) 1713 c = copy.copy(d)
1792 self.assertEqual(id(c), id(d)) 1714 self.assertEqual(id(c), id(d))
1793 dc = copy.deepcopy(d) 1715 dc = copy.deepcopy(d)
1794 self.assertEqual(id(dc), id(d)) 1716 self.assertEqual(id(dc), id(d))
1795 1717
1796 def test_hash_method(self): 1718 def test_hash_method(self):
1797 if hasattr(C, 'setfailpoint'):
1798 random.seed(randseed)
1799 1719
1800 Decimal = self.decimal.Decimal 1720 Decimal = self.decimal.Decimal
1801 localcontext = self.decimal.localcontext 1721 localcontext = self.decimal.localcontext
1802 1722
1803 def hashit(d): 1723 def hashit(d):
1804 a = hash(d) 1724 a = hash(d)
1805 b = d.__hash__() 1725 b = d.__hash__()
1806 self.assertEqual(a, b) 1726 self.assertEqual(a, b)
1807 return a 1727 return a
1808 1728
1809 #just that it's hashable 1729 #just that it's hashable
1810 hashit(Decimal(23)) 1730 hashit(Decimal(23))
1811 hashit(Decimal('Infinity')) 1731 hashit(Decimal('Infinity'))
1812 hashit(Decimal('-Infinity')) 1732 hashit(Decimal('-Infinity'))
1813 hashit(Decimal('nan123')) 1733 hashit(Decimal('nan123'))
1814 hashit(Decimal('-NaN')) 1734 hashit(Decimal('-NaN'))
1815 1735
1816 test_values = [Decimal(sign*(2**m + n)) 1736 test_values = [Decimal(sign*(2**m + n))
1817 for m in [0, 14, 15, 16, 17, 30, 31, 1737 for m in [0, 14, 15, 16, 17, 30, 31,
1818 32, 33, 61, 62, 63, 64, 65, 66] 1738 32, 33, 61, 62, 63, 64, 65, 66]
1819 for n in range(-10, 10) 1739 for n in range(-10, 10)
1820 for sign in [-1, 1]] 1740 for sign in [-1, 1]]
1821 if hasattr(C, 'setfailpoint'):
1822 test_values = random.sample(test_values, 10)
1823 test_values.extend([ 1741 test_values.extend([
1824 Decimal("-1"), # ==> -2 1742 Decimal("-1"), # ==> -2
1825 Decimal("-0"), # zeros 1743 Decimal("-0"), # zeros
1826 Decimal("0.00"), 1744 Decimal("0.00"),
1827 Decimal("-0.000"), 1745 Decimal("-0.000"),
1828 Decimal("0E10"), 1746 Decimal("0E10"),
1829 Decimal("-0E12"), 1747 Decimal("-0E12"),
1830 Decimal("10.0"), # negative exponent 1748 Decimal("10.0"), # negative exponent
1831 Decimal("-23.00000"), 1749 Decimal("-23.00000"),
1832 Decimal("1230E100"), # positive exponent 1750 Decimal("1230E100"), # positive exponent
(...skipping 102 matching lines...) Expand 10 before | Expand all | Expand 10 after
1935 #floor 1853 #floor
1936 test_pairs = [ 1854 test_pairs = [
1937 ('123.00', 123), 1855 ('123.00', 123),
1938 ('3.2', 3), 1856 ('3.2', 3),
1939 ('3.54', 3), 1857 ('3.54', 3),
1940 ('3.899', 3), 1858 ('3.899', 3),
1941 ('-2.3', -3), 1859 ('-2.3', -3),
1942 ('-11.0', -11), 1860 ('-11.0', -11),
1943 ('0.0', 0), 1861 ('0.0', 0),
1944 ('-0E3', 0), 1862 ('-0E3', 0),
1863 ('89891211712379812736.1', 89891211712379812736),
1945 ] 1864 ]
1946 for d, i in test_pairs: 1865 for d, i in test_pairs:
1947 self.assertEqual(math.floor(Decimal(d)), i) 1866 self.assertEqual(math.floor(Decimal(d)), i)
1948 self.assertRaises(ValueError, math.floor, Decimal('-NaN')) 1867 self.assertRaises(ValueError, math.floor, Decimal('-NaN'))
1949 self.assertRaises(ValueError, math.floor, Decimal('sNaN')) 1868 self.assertRaises(ValueError, math.floor, Decimal('sNaN'))
1950 self.assertRaises(ValueError, math.floor, Decimal('NaN123')) 1869 self.assertRaises(ValueError, math.floor, Decimal('NaN123'))
1951 self.assertRaises(OverflowError, math.floor, Decimal('Inf')) 1870 self.assertRaises(OverflowError, math.floor, Decimal('Inf'))
1952 self.assertRaises(OverflowError, math.floor, Decimal('-Inf')) 1871 self.assertRaises(OverflowError, math.floor, Decimal('-Inf'))
1953 1872
1954 #ceiling 1873 #ceiling
1955 test_pairs = [ 1874 test_pairs = [
1956 ('123.00', 123), 1875 ('123.00', 123),
1957 ('3.2', 4), 1876 ('3.2', 4),
1958 ('3.54', 4), 1877 ('3.54', 4),
1959 ('3.899', 4), 1878 ('3.899', 4),
1960 ('-2.3', -2), 1879 ('-2.3', -2),
1961 ('-11.0', -11), 1880 ('-11.0', -11),
1962 ('0.0', 0), 1881 ('0.0', 0),
1963 ('-0E3', 0), 1882 ('-0E3', 0),
1883 ('89891211712379812736.1', 89891211712379812737),
1964 ] 1884 ]
1965 for d, i in test_pairs: 1885 for d, i in test_pairs:
1966 self.assertEqual(math.ceil(Decimal(d)), i) 1886 self.assertEqual(math.ceil(Decimal(d)), i)
1967 self.assertRaises(ValueError, math.ceil, Decimal('-NaN')) 1887 self.assertRaises(ValueError, math.ceil, Decimal('-NaN'))
1968 self.assertRaises(ValueError, math.ceil, Decimal('sNaN')) 1888 self.assertRaises(ValueError, math.ceil, Decimal('sNaN'))
1969 self.assertRaises(ValueError, math.ceil, Decimal('NaN123')) 1889 self.assertRaises(ValueError, math.ceil, Decimal('NaN123'))
1970 self.assertRaises(OverflowError, math.ceil, Decimal('Inf')) 1890 self.assertRaises(OverflowError, math.ceil, Decimal('Inf'))
1971 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf')) 1891 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf'))
1972 1892
1973 #round, single argument 1893 #round, single argument
(...skipping 231 matching lines...) Expand 10 before | Expand all | Expand 10 after
2205 r = pickle.loads(sy) 2125 r = pickle.loads(sy)
2206 self.assertIsInstance(r, C.Decimal) 2126 self.assertIsInstance(r, C.Decimal)
2207 self.assertEqual(r, x) 2127 self.assertEqual(r, x)
2208 2128
2209 sys.modules['decimal'] = savedecimal 2129 sys.modules['decimal'] = savedecimal
2210 2130
2211 def test_int(self): 2131 def test_int(self):
2212 Decimal = self.decimal.Decimal 2132 Decimal = self.decimal.Decimal
2213 ROUND_DOWN = self.decimal.ROUND_DOWN 2133 ROUND_DOWN = self.decimal.ROUND_DOWN
2214 2134
2215 lim = 10 if hasattr(C, 'setfailpoint') else 250 2135 for x in range(-250, 250):
2216 for x in range(-lim, lim):
2217 s = '%0.2f' % (x / 100.0) 2136 s = '%0.2f' % (x / 100.0)
2218 # should work the same as for floats 2137 # should work the same as for floats
2219 self.assertEqual(int(Decimal(s)), int(float(s))) 2138 self.assertEqual(int(Decimal(s)), int(float(s)))
2220 # 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
2221 d = Decimal(s) 2140 d = Decimal(s)
2222 r = d.to_integral(ROUND_DOWN) 2141 r = d.to_integral(ROUND_DOWN)
2223 self.assertEqual(Decimal(int(d)), r) 2142 self.assertEqual(Decimal(int(d)), r)
2224 2143
2225 self.assertRaises(ValueError, int, Decimal('-nan')) 2144 self.assertRaises(ValueError, int, Decimal('-nan'))
2226 self.assertRaises(ValueError, int, Decimal('snan')) 2145 self.assertRaises(ValueError, int, Decimal('snan'))
2227 self.assertRaises(OverflowError, int, Decimal('inf')) 2146 self.assertRaises(OverflowError, int, Decimal('inf'))
2228 self.assertRaises(OverflowError, int, Decimal('-inf')) 2147 self.assertRaises(OverflowError, int, Decimal('-inf'))
2229 2148
2230 def test_trunc(self): 2149 def test_trunc(self):
2231 Decimal = self.decimal.Decimal 2150 Decimal = self.decimal.Decimal
2232 ROUND_DOWN = self.decimal.ROUND_DOWN 2151 ROUND_DOWN = self.decimal.ROUND_DOWN
2233 2152
2234 lim = 10 if hasattr(C, 'setfailpoint') else 250 2153 for x in range(-250, 250):
2235 for x in range(-lim, lim):
2236 s = '%0.2f' % (x / 100.0) 2154 s = '%0.2f' % (x / 100.0)
2237 # should work the same as for floats 2155 # should work the same as for floats
2238 self.assertEqual(int(Decimal(s)), int(float(s))) 2156 self.assertEqual(int(Decimal(s)), int(float(s)))
2239 # 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
2240 d = Decimal(s) 2158 d = Decimal(s)
2241 r = d.to_integral(ROUND_DOWN) 2159 r = d.to_integral(ROUND_DOWN)
2242 self.assertEqual(Decimal(math.trunc(d)), r) 2160 self.assertEqual(Decimal(math.trunc(d)), r)
2243 2161
2244 def test_from_float(self): 2162 def test_from_float(self):
2245 if hasattr(C, 'setfailpoint'):
2246 random.seed(randseed)
2247 2163
2248 Decimal = self.decimal.Decimal 2164 Decimal = self.decimal.Decimal
2249 2165
2250 class MyDecimal(Decimal): 2166 class MyDecimal(Decimal):
2251 pass 2167 pass
2252 2168
2253 self.assertTrue(issubclass(MyDecimal, Decimal)) 2169 self.assertTrue(issubclass(MyDecimal, Decimal))
2254 2170
2255 r = MyDecimal.from_float(0.1) 2171 r = MyDecimal.from_float(0.1)
2256 self.assertEqual(type(r), MyDecimal) 2172 self.assertEqual(type(r), MyDecimal)
2257 self.assertEqual(str(r), 2173 self.assertEqual(str(r),
2258 '0.1000000000000000055511151231257827021181583404541015625') 2174 '0.1000000000000000055511151231257827021181583404541015625')
2259 bigint = 12345678901234567890123456789 2175 bigint = 12345678901234567890123456789
2260 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint)) 2176 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
2261 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan()) 2177 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
2262 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite()) 2178 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
2263 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite()) 2179 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
2264 self.assertEqual(str(MyDecimal.from_float(float('nan'))), 2180 self.assertEqual(str(MyDecimal.from_float(float('nan'))),
2265 str(Decimal('NaN'))) 2181 str(Decimal('NaN')))
2266 self.assertEqual(str(MyDecimal.from_float(float('inf'))), 2182 self.assertEqual(str(MyDecimal.from_float(float('inf'))),
2267 str(Decimal('Infinity'))) 2183 str(Decimal('Infinity')))
2268 self.assertEqual(str(MyDecimal.from_float(float('-inf'))), 2184 self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
2269 str(Decimal('-Infinity'))) 2185 str(Decimal('-Infinity')))
2270 self.assertRaises(TypeError, MyDecimal.from_float, 'abc') 2186 self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
2271 lim = 10 if hasattr(C, 'setfailpoint') else 200 2187 for i in range(200):
2272 for i in range(lim):
2273 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0) 2188 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
2274 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 2189 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip
2275 2190
2276 def test_create_decimal_from_float(self): 2191 def test_create_decimal_from_float(self):
2277 Decimal = self.decimal.Decimal 2192 Decimal = self.decimal.Decimal
2278 Context = self.decimal.Context 2193 Context = self.decimal.Context
2279 ROUND_DOWN = self.decimal.ROUND_DOWN 2194 ROUND_DOWN = self.decimal.ROUND_DOWN
2280 ROUND_UP = self.decimal.ROUND_UP 2195 ROUND_UP = self.decimal.ROUND_UP
2281 Inexact = self.decimal.Inexact 2196 Inexact = self.decimal.Inexact
2282 2197
(...skipping 177 matching lines...) Expand 10 before | Expand all | Expand 10 after
2460 self.assertRaises(TypeError, D("-1").copy_negate, context=xc) 2375 self.assertRaises(TypeError, D("-1").copy_negate, context=xc)
2461 2376
2462 class CPythonAPItests(PythonAPItests): 2377 class CPythonAPItests(PythonAPItests):
2463 decimal = C 2378 decimal = C
2464 class PyPythonAPItests(PythonAPItests): 2379 class PyPythonAPItests(PythonAPItests):
2465 decimal = P 2380 decimal = P
2466 2381
2467 class ContextAPItests(unittest.TestCase): 2382 class ContextAPItests(unittest.TestCase):
2468 2383
2469 def test_pickle(self): 2384 def test_pickle(self):
2470 if hasattr(C, 'setfailpoint'):
2471 random.seed(randseed)
2472 2385
2473 Context = self.decimal.Context 2386 Context = self.decimal.Context
2474 2387
2475 savedecimal = sys.modules['decimal'] 2388 savedecimal = sys.modules['decimal']
2476 2389
2477 # Round trip 2390 # Round trip
2478 sys.modules['decimal'] = self.decimal 2391 sys.modules['decimal'] = self.decimal
2479 c = Context() 2392 c = Context()
2480 e = pickle.loads(pickle.dumps(c)) 2393 e = pickle.loads(pickle.dumps(c))
2481 2394
2482 self.assertEqual(c.prec, e.prec) 2395 self.assertEqual(c.prec, e.prec)
2483 self.assertEqual(c.Emin, e.Emin) 2396 self.assertEqual(c.Emin, e.Emin)
2484 self.assertEqual(c.Emax, e.Emax) 2397 self.assertEqual(c.Emax, e.Emax)
2485 self.assertEqual(c.rounding, e.rounding) 2398 self.assertEqual(c.rounding, e.rounding)
2486 self.assertEqual(c.capitals, e.capitals) 2399 self.assertEqual(c.capitals, e.capitals)
2487 self.assertEqual(c.clamp, e.clamp) 2400 self.assertEqual(c.clamp, e.clamp)
2488 self.assertEqual(c.flags, e.flags) 2401 self.assertEqual(c.flags, e.flags)
2489 self.assertEqual(c.traps, e.traps) 2402 self.assertEqual(c.traps, e.traps)
2490 2403
2491 # Test interchangeability 2404 # Test interchangeability
2492 combinations = [(C, P), (P, C)] if C else [(P, P)] 2405 combinations = [(C, P), (P, C)] if C else [(P, P)]
2493 for dumper, loader in combinations: 2406 for dumper, loader in combinations:
2494 for ri, _ in enumerate(RoundingModes[dumper]): 2407 for ri, _ in enumerate(RoundingModes[dumper]):
2495 if hasattr(C, 'setfailpoint') and ri > 0: continue
2496 for fi, _ in enumerate(OrderedSignals[dumper]): 2408 for fi, _ in enumerate(OrderedSignals[dumper]):
2497 if hasattr(C, 'setfailpoint') and fi > 0: continue
2498 for ti, _ in enumerate(OrderedSignals[dumper]): 2409 for ti, _ in enumerate(OrderedSignals[dumper]):
2499 if hasattr(C, 'setfailpoint') and ti > 0: continue
2500 2410
2501 prec = random.randrange(1, 100) 2411 prec = random.randrange(1, 100)
2502 emin = random.randrange(-100, 0) 2412 emin = random.randrange(-100, 0)
2503 emax = random.randrange(1, 100) 2413 emax = random.randrange(1, 100)
2504 caps = random.randrange(2) 2414 caps = random.randrange(2)
2505 clamp = random.randrange(2) 2415 clamp = random.randrange(2)
2506 2416
2507 # One module dumps 2417 # One module dumps
2508 sys.modules['decimal'] = dumper 2418 sys.modules['decimal'] = dumper
2509 c = dumper.Context( 2419 c = dumper.Context(
(...skipping 941 matching lines...) Expand 10 before | Expand all | Expand 10 after
3451 try: 3361 try:
3452 BasicContext.prec = ExtendedContext.prec = 441 3362 BasicContext.prec = ExtendedContext.prec = 441
3453 for template in BasicContext, ExtendedContext: 3363 for template in BasicContext, ExtendedContext:
3454 setcontext(template) 3364 setcontext(template)
3455 c = getcontext() 3365 c = getcontext()
3456 self.assertIsNot(c, template) 3366 self.assertIsNot(c, template)
3457 self.assertEqual(c.prec, 441) 3367 self.assertEqual(c.prec, 441)
3458 except Exception as e: 3368 except Exception as e:
3459 ex = e.__class__ 3369 ex = e.__class__
3460 finally: 3370 finally:
3461 with protectfail(): 3371 BasicContext.prec = basic_context_prec
3462 BasicContext.prec = basic_context_prec 3372 ExtendedContext.prec = extended_context_prec
3463 ExtendedContext.prec = extended_context_prec 3373 setcontext(savecontext)
3464 setcontext(savecontext)
3465 if ex: 3374 if ex:
3466 raise ex 3375 raise ex
3467 3376
3468 def test_default_context(self): 3377 def test_default_context(self):
3469 DefaultContext = self.decimal.DefaultContext 3378 DefaultContext = self.decimal.DefaultContext
3470 BasicContext = self.decimal.BasicContext 3379 BasicContext = self.decimal.BasicContext
3471 ExtendedContext = self.decimal.ExtendedContext 3380 ExtendedContext = self.decimal.ExtendedContext
3472 getcontext = self.decimal.getcontext 3381 getcontext = self.decimal.getcontext
3473 setcontext = self.decimal.setcontext 3382 setcontext = self.decimal.setcontext
3474 InvalidOperation = self.decimal.InvalidOperation 3383 InvalidOperation = self.decimal.InvalidOperation
(...skipping 19 matching lines...) Expand all
3494 c = getcontext() 3403 c = getcontext()
3495 self.assertEqual(c.prec, saveprec) 3404 self.assertEqual(c.prec, saveprec)
3496 3405
3497 setcontext(DefaultContext) 3406 setcontext(DefaultContext)
3498 c = getcontext() 3407 c = getcontext()
3499 self.assertIsNot(c, DefaultContext) 3408 self.assertIsNot(c, DefaultContext)
3500 self.assertEqual(c.prec, 961) 3409 self.assertEqual(c.prec, 961)
3501 except Exception as e: 3410 except Exception as e:
3502 ex = e.__class__ 3411 ex = e.__class__
3503 finally: 3412 finally:
3504 with protectfail(): 3413 DefaultContext.prec = default_context_prec
3505 DefaultContext.prec = default_context_prec 3414 setcontext(savecontext)
3506 setcontext(savecontext)
3507 if ex: 3415 if ex:
3508 raise ex 3416 raise ex
3509 3417
3510 class CSpecialContexts(SpecialContexts): 3418 class CSpecialContexts(SpecialContexts):
3511 decimal = C 3419 decimal = C
3512 class PySpecialContexts(SpecialContexts): 3420 class PySpecialContexts(SpecialContexts):
3513 decimal = P 3421 decimal = P
3514 3422
3515 class ContextInputValidation(unittest.TestCase): 3423 class ContextInputValidation(unittest.TestCase):
3516 3424
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
3582 self.assertRaises(KeyError, Context, traps=["Q"]) 3490 self.assertRaises(KeyError, Context, traps=["Q"])
3583 3491
3584 # Type error in conversion 3492 # Type error in conversion
3585 self.assertRaises(TypeError, Context, flags=(0,1)) 3493 self.assertRaises(TypeError, Context, flags=(0,1))
3586 self.assertRaises(TypeError, Context, traps=(1,0)) 3494 self.assertRaises(TypeError, Context, traps=(1,0))
3587 3495
3588 class CContextInputValidation(ContextInputValidation): 3496 class CContextInputValidation(ContextInputValidation):
3589 decimal = C 3497 decimal = C
3590 class PyContextInputValidation(ContextInputValidation): 3498 class PyContextInputValidation(ContextInputValidation):
3591 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())
3592 3531
3593 class Coverage(unittest.TestCase): 3532 class Coverage(unittest.TestCase):
3594 3533
3595 def test_adjusted(self): 3534 def test_adjusted(self):
3596 Decimal = self.decimal.Decimal 3535 Decimal = self.decimal.Decimal
3597 3536
3598 self.assertEqual(Decimal('1234e9999').adjusted(), 10002) 3537 self.assertEqual(Decimal('1234e9999').adjusted(), 10002)
3599 # XXX raise? 3538 # XXX raise?
3600 self.assertEqual(Decimal('nan').adjusted(), 0) 3539 self.assertEqual(Decimal('nan').adjusted(), 0)
3601 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
4019 def test_py__round(self): 3958 def test_py__round(self):
4020 # Coverage 3959 # Coverage
4021 Decimal = P.Decimal 3960 Decimal = P.Decimal
4022 ROUND_UP = P.ROUND_UP 3961 ROUND_UP = P.ROUND_UP
4023 3962
4024 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP) 3963 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP)
4025 3964
4026 class CFunctionality(unittest.TestCase): 3965 class CFunctionality(unittest.TestCase):
4027 """Extra functionality in _decimal""" 3966 """Extra functionality in _decimal"""
4028 3967
3968 @requires_extra_functionality
4029 def test_c_ieee_context(self): 3969 def test_c_ieee_context(self):
4030 # issue 8786: Add support for IEEE 754 contexts to decimal module. 3970 # issue 8786: Add support for IEEE 754 contexts to decimal module.
4031 IEEEContext = C.IEEEContext 3971 IEEEContext = C.IEEEContext
4032 DECIMAL32 = C.DECIMAL32 3972 DECIMAL32 = C.DECIMAL32
4033 DECIMAL64 = C.DECIMAL64 3973 DECIMAL64 = C.DECIMAL64
4034 DECIMAL128 = C.DECIMAL128 3974 DECIMAL128 = C.DECIMAL128
4035 3975
4036 def assert_rest(self, context): 3976 def assert_rest(self, context):
4037 self.assertEqual(context.clamp, 1) 3977 self.assertEqual(context.clamp, 1)
4038 assert_signals(self, context, 'traps', []) 3978 assert_signals(self, context, 'traps', [])
(...skipping 138 matching lines...) Expand 10 before | Expand all | Expand 10 after
4177 test_containers(c, sig) 4117 test_containers(c, sig)
4178 4118
4179 c.traps[FloatOperation] = True 4119 c.traps[FloatOperation] = True
4180 doit(c, signal=FloatOperation) 4120 doit(c, signal=FloatOperation)
4181 test_containers(c, FloatOperation) 4121 test_containers(c, FloatOperation)
4182 4122
4183 def test_c_float_operation_default(self): 4123 def test_c_float_operation_default(self):
4184 Decimal = C.Decimal 4124 Decimal = C.Decimal
4185 Context = C.Context 4125 Context = C.Context
4186 Inexact = C.Inexact 4126 Inexact = C.Inexact
4187 DecInexact = C.DecInexact
4188 FloatOperation= C.FloatOperation 4127 FloatOperation= C.FloatOperation
4189 DecFloatOperation= C.DecFloatOperation
4190 4128
4191 context = Context() 4129 context = Context()
4192 self.assertFalse(context.flags[FloatOperation]) 4130 self.assertFalse(context.flags[FloatOperation])
4193 self.assertFalse(context.traps[FloatOperation]) 4131 self.assertFalse(context.traps[FloatOperation])
4194 self.assertFalse(context._flags&DecFloatOperation)
4195 self.assertFalse(context._traps&DecFloatOperation)
4196 4132
4197 context.clear_traps() 4133 context.clear_traps()
4198 context.traps[Inexact] = True 4134 context.traps[Inexact] = True
4199 context.traps[FloatOperation] = True 4135 context.traps[FloatOperation] = True
4200 self.assertEqual(context._traps, DecInexact|DecFloatOperation)
4201 self.assertTrue(context.traps[FloatOperation]) 4136 self.assertTrue(context.traps[FloatOperation])
4202 self.assertTrue(context.traps[Inexact]) 4137 self.assertTrue(context.traps[Inexact])
4203 4138
4139 @requires_extra_functionality
4204 def test_c_context(self): 4140 def test_c_context(self):
4205 Context = C.Context 4141 Context = C.Context
4206 4142
4207 c = Context(flags=C.DecClamped, traps=C.DecRounded) 4143 c = Context(flags=C.DecClamped, traps=C.DecRounded)
4208 self.assertEqual(c._flags, C.DecClamped) 4144 self.assertEqual(c._flags, C.DecClamped)
4209 self.assertEqual(c._traps, C.DecRounded) 4145 self.assertEqual(c._traps, C.DecRounded)
4210 4146
4147 @requires_extra_functionality
4211 def test_constants(self): 4148 def test_constants(self):
4212 # Condition flags 4149 # Condition flags
4213 cond = ( 4150 cond = (
4214 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero, 4151 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero,
4215 C.DecDivisionImpossible, C.DecDivisionUndefined, 4152 C.DecDivisionImpossible, C.DecDivisionUndefined,
4216 C.DecFpuError, C.DecInexact, C.DecInvalidContext, 4153 C.DecFpuError, C.DecInexact, C.DecInvalidContext,
4217 C.DecInvalidOperation, C.DecMallocError, 4154 C.DecInvalidOperation, C.DecMallocError,
4218 C.DecFloatOperation, C.DecOverflow, C.DecRounded, 4155 C.DecFloatOperation, C.DecOverflow, C.DecRounded,
4219 C.DecSubnormal, C.DecUnderflow 4156 C.DecSubnormal, C.DecUnderflow
4220 ) 4157 )
4221 4158
4222 # Architecture dependent context limits
4223 if C.MAX_EMAX > 425000000:
4224 self.assertEqual(C.MAX_PREC, 999999999999999999)
4225 self.assertEqual(C.MAX_EMAX, 999999999999999999)
4226 self.assertEqual(C.MIN_EMIN, -999999999999999999)
4227 self.assertEqual(C.MIN_ETINY, -1999999999999999997)
4228 else:
4229 self.assertEqual(C.MAX_PREC, 425000000)
4230 self.assertEqual(C.MAX_EMAX, 425000000)
4231 self.assertEqual(C.MIN_EMIN, -425000000)
4232 self.assertEqual(C.MIN_ETINY, -849999999)
4233
4234 # IEEEContext 4159 # IEEEContext
4235 self.assertEqual(C.DECIMAL32, 32) 4160 self.assertEqual(C.DECIMAL32, 32)
4236 self.assertEqual(C.DECIMAL64, 64) 4161 self.assertEqual(C.DECIMAL64, 64)
4237 self.assertEqual(C.DECIMAL128, 128) 4162 self.assertEqual(C.DECIMAL128, 128)
4238 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512) 4163 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512)
4239 4164
4240 # Rounding modes 4165 # Rounding modes
4241 for i, v in enumerate(RoundingModes[C]): 4166 for i, v in enumerate(RoundingModes[C]):
4242 self.assertEqual(v, i) 4167 self.assertEqual(v, i)
4243 self.assertEqual(C.ROUND_TRUNC, 8) 4168 self.assertEqual(C.ROUND_TRUNC, 8)
(...skipping 16 matching lines...) Expand all
4260 C.DecDivisionByZero) 4185 C.DecDivisionByZero)
4261 4186
4262 self.assertEqual(C.DecTraps, 4187 self.assertEqual(C.DecTraps,
4263 C.DecErrors|C.DecOverflow|C.DecUnderflow) 4188 C.DecErrors|C.DecOverflow|C.DecUnderflow)
4264 4189
4265 class CWhitebox(unittest.TestCase): 4190 class CWhitebox(unittest.TestCase):
4266 """Whitebox testing for _decimal""" 4191 """Whitebox testing for _decimal"""
4267 4192
4268 def test_bignum(self): 4193 def test_bignum(self):
4269 # Not exactly whitebox, but too slow with pydecimal. 4194 # Not exactly whitebox, but too slow with pydecimal.
4270 if hasattr(C, 'setfailpoint'):
4271 random.seed(randseed)
4272 4195
4273 Decimal = C.Decimal 4196 Decimal = C.Decimal
4274 localcontext = C.localcontext 4197 localcontext = C.localcontext
4275 4198
4276 b1 = 10**35 4199 b1 = 10**35
4277 b2 = 10**36 4200 b2 = 10**36
4278 with localcontext() as c: 4201 with localcontext() as c:
4279 c.prec = 1000000 4202 c.prec = 1000000
4280 r = 1 if hasattr(C, 'setfailpoint') else 5 4203 for i in range(5):
4281 for i in range(r):
4282 a = random.randrange(b1, b2) 4204 a = random.randrange(b1, b2)
4283 b = random.randrange(1000, 1200) 4205 b = random.randrange(1000, 1200)
4284 x = a ** b 4206 x = a ** b
4285 y = Decimal(a) ** Decimal(b) 4207 y = Decimal(a) ** Decimal(b)
4286 self.assertEqual(x, y) 4208 self.assertEqual(x, y)
4287 4209
4288 def test_invalid_construction(self): 4210 def test_invalid_construction(self):
4289 self.assertRaises(TypeError, C.Decimal, 9, "xyz") 4211 self.assertRaises(TypeError, C.Decimal, 9, "xyz")
4290 4212
4291 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
4367 # Overflow in conversion 4289 # Overflow in conversion
4368 self.assertRaises(OverflowError, Context, prec=int_max+1) 4290 self.assertRaises(OverflowError, Context, prec=int_max+1)
4369 self.assertRaises(OverflowError, Context, Emax=int_max+1) 4291 self.assertRaises(OverflowError, Context, Emax=int_max+1)
4370 self.assertRaises(OverflowError, Context, Emin=-int_max-2) 4292 self.assertRaises(OverflowError, Context, Emin=-int_max-2)
4371 self.assertRaises(OverflowError, Context, rounding=int_max+1) 4293 self.assertRaises(OverflowError, Context, rounding=int_max+1)
4372 self.assertRaises(OverflowError, Context, clamp=int_max+1) 4294 self.assertRaises(OverflowError, Context, clamp=int_max+1)
4373 self.assertRaises(OverflowError, Context, capitals=int_max+1) 4295 self.assertRaises(OverflowError, Context, capitals=int_max+1)
4374 self.assertRaises(OverflowError, Context, _allcr=int_max+1) 4296 self.assertRaises(OverflowError, Context, _allcr=int_max+1)
4375 4297
4376 # OverflowError, general ValueError 4298 # OverflowError, general ValueError
4377 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp', '_allcr'): 4299 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp'):
4378 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4300 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4379 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4301 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4380 if sys.platform != 'win32': 4302 if sys.platform != 'win32':
4381 self.assertRaises(ValueError, setattr, c, attr, int_max) 4303 self.assertRaises(ValueError, setattr, c, attr, int_max)
4382 self.assertRaises(ValueError, setattr, c, attr, -int_max-1) 4304 self.assertRaises(ValueError, setattr, c, attr, -int_max-1)
4383 4305
4384 # OverflowError, general TypeError 4306 # OverflowError, general TypeError
4385 for attr in ('rounding', '_flags', '_traps'): 4307 for attr in ('rounding',):
4386 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4308 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4387 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4309 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4388 if sys.platform != 'win32': 4310 if sys.platform != 'win32':
4389 self.assertRaises(TypeError, setattr, c, attr, int_max) 4311 self.assertRaises(TypeError, setattr, c, attr, int_max)
4390 self.assertRaises(TypeError, setattr, c, attr, -int_max-1) 4312 self.assertRaises(TypeError, setattr, c, attr, -int_max-1)
4391 4313
4392 # OverflowError: unsafe_prec, unsafe_emin, unsafe_emax 4314 # OverflowError: _unsafe_setprec, _unsafe_setemin, _unsafe_setemax
4393 self.assertRaises(OverflowError, getattr(c, 'unsafe_setprec'), int_max+1 ) 4315 if C.MAX_PREC == 425000000:
4394 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemax'), int_max+1 ) 4316 self.assertRaises(OverflowError, getattr(c, '_unsafe_setprec'),
4395 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemin'), -int_max- 2) 4317 int_max+1)
4396 4318 self.assertRaises(OverflowError, getattr(c, '_unsafe_setemax'),
4397 # capitals, clamp, _allcr 4319 int_max+1)
4398 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']:
4399 self.assertRaises(ValueError, setattr, c, attr, -1) 4337 self.assertRaises(ValueError, setattr, c, attr, -1)
4400 self.assertRaises(ValueError, setattr, c, attr, 2) 4338 self.assertRaises(ValueError, setattr, c, attr, 2)
4401 self.assertRaises(TypeError, setattr, c, attr, [1,2,3]) 4339 self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
4402 if HAVE_CONFIG_64: 4340 if HAVE_CONFIG_64:
4403 self.assertRaises(ValueError, setattr, c, attr, 2**32) 4341 self.assertRaises(ValueError, setattr, c, attr, 2**32)
4404 self.assertRaises(ValueError, setattr, c, attr, 2**32+1) 4342 self.assertRaises(ValueError, setattr, c, attr, 2**32+1)
4405 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
4406 self.assertRaises(ValueError, Context, _allcr=2) 4391 self.assertRaises(ValueError, Context, _allcr=2)
4407 4392
4408 # _flags, _traps 4393 # _flags, _traps
4409 for attr in ['_flags', '_traps']: 4394 for attr in ['_flags', '_traps']:
4410 self.assertRaises(TypeError, setattr, c, attr, 999999) 4395 self.assertRaises(TypeError, setattr, c, attr, 999999)
4411 self.assertRaises(TypeError, setattr, c, attr, 'x') 4396 self.assertRaises(TypeError, setattr, c, attr, 'x')
4412
4413 # Invalid local context
4414 self.assertRaises(TypeError, exec, 'with localcontext("xyz"): pass',
4415 locals())
4416
4417 # setcontext
4418 saved_context = getcontext()
4419 self.assertRaises(TypeError, setcontext, "xyz")
4420 setcontext(saved_context)
4421 4397
4422 def test_c_valid_context(self): 4398 def test_c_valid_context(self):
4423 # These tests are for code coverage in _decimal. 4399 # These tests are for code coverage in _decimal.
4424 DefaultContext = C.DefaultContext 4400 DefaultContext = C.DefaultContext
4425 ROUND_HALF_UP = C.ROUND_HALF_UP 4401 ROUND_HALF_UP = C.ROUND_HALF_UP
4426 Clamped = C.Clamped 4402 Clamped = C.Clamped
4427 Underflow = C.Underflow 4403 Underflow = C.Underflow
4428 Inexact = C.Inexact 4404 Inexact = C.Inexact
4429 Rounded = C.Rounded 4405 Rounded = C.Rounded
4430 Subnormal = C.Subnormal 4406 Subnormal = C.Subnormal
4431 DecClamped = C.DecClamped
4432 DecUnderflow = C.DecUnderflow
4433 DecInexact = C.DecInexact
4434 DecRounded = C.DecRounded
4435 DecSubnormal = C.DecSubnormal
4436 4407
4437 c = DefaultContext.copy() 4408 c = DefaultContext.copy()
4438 4409
4439 # Exercise all getters and setters 4410 # Exercise all getters and setters
4440 c.prec = 34 4411 c.prec = 34
4441 c.rounding = ROUND_HALF_UP 4412 c.rounding = ROUND_HALF_UP
4442 c.Emax = 3000 4413 c.Emax = 3000
4443 c.Emin = -3000 4414 c.Emin = -3000
4444 c.capitals = 1 4415 c.capitals = 1
4445 c.clamp = 0 4416 c.clamp = 0
4446 c._flags = DecUnderflow
4447 c._traps = DecClamped
4448 c._allcr = 0
4449 4417
4450 self.assertEqual(c.prec, 34) 4418 self.assertEqual(c.prec, 34)
4451 self.assertEqual(c.rounding, ROUND_HALF_UP) 4419 self.assertEqual(c.rounding, ROUND_HALF_UP)
4452 self.assertEqual(c.Emin, -3000) 4420 self.assertEqual(c.Emin, -3000)
4453 self.assertEqual(c.Emax, 3000) 4421 self.assertEqual(c.Emax, 3000)
4454 self.assertEqual(c.capitals, 1) 4422 self.assertEqual(c.capitals, 1)
4455 self.assertEqual(c.clamp, 0) 4423 self.assertEqual(c.clamp, 0)
4456 self.assertEqual(c._flags, DecUnderflow)
4457 self.assertEqual(c._traps, DecClamped)
4458 self.assertEqual(c._allcr, 0)
4459 4424
4460 self.assertEqual(c.Etiny(), -3033) 4425 self.assertEqual(c.Etiny(), -3033)
4461 self.assertEqual(c.Etop(), 2967) 4426 self.assertEqual(c.Etop(), 2967)
4462 4427
4463 # Exercise all unsafe setters 4428 # Exercise all unsafe setters
4464 c.unsafe_setprec(999999999) 4429 if C.MAX_PREC == 425000000:
4465 c.unsafe_setemax(999999999) 4430 c._unsafe_setprec(999999999)
4466 c.unsafe_setemin(-999999999) 4431 c._unsafe_setemax(999999999)
4467 4432 c._unsafe_setemin(-999999999)
4468 self.assertEqual(c.prec, 999999999) 4433 self.assertEqual(c.prec, 999999999)
4469 self.assertEqual(c.Emax, 999999999) 4434 self.assertEqual(c.Emax, 999999999)
4470 self.assertEqual(c.Emin, -999999999) 4435 self.assertEqual(c.Emin, -999999999)
4471 4436
4472 def test_c_round(self): 4437 def test_c_round(self):
4473 # Restricted input. 4438 # Restricted input.
4474 Decimal = C.Decimal 4439 Decimal = C.Decimal
4475 InvalidOperation = C.InvalidOperation 4440 InvalidOperation = C.InvalidOperation
4476 localcontext = C.localcontext 4441 localcontext = C.localcontext
4477 MAX_EMAX = C.MAX_EMAX 4442 MAX_EMAX = C.MAX_EMAX
4478 MIN_ETINY = C.MIN_ETINY 4443 MIN_ETINY = C.MIN_ETINY
4479 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
4480 4445
(...skipping 117 matching lines...) Expand 10 before | Expand all | Expand 10 after
4598 c.clear_flags() 4563 c.clear_flags()
4599 c.traps[InvalidOperation] = True 4564 c.traps[InvalidOperation] = True
4600 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0) 4565 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0)
4601 self.assertRaises(InvalidOperation, c.divmod, 9, 0) 4566 self.assertRaises(InvalidOperation, c.divmod, 9, 0)
4602 self.assertTrue(c.flags[DivisionByZero]) 4567 self.assertTrue(c.flags[DivisionByZero])
4603 4568
4604 c.traps[InvalidOperation] = True 4569 c.traps[InvalidOperation] = True
4605 c.prec = 2 4570 c.prec = 2
4606 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501) 4571 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501)
4607 4572
4573 @requires_extra_functionality
4608 def test_c_context_templates(self): 4574 def test_c_context_templates(self):
4609 self.assertEqual( 4575 self.assertEqual(
4610 C.BasicContext._traps, 4576 C.BasicContext._traps,
4611 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow| 4577 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow|
4612 C.DecUnderflow|C.DecClamped 4578 C.DecUnderflow|C.DecClamped
4613 ) 4579 )
4614 self.assertEqual( 4580 self.assertEqual(
4615 C.DefaultContext._traps, 4581 C.DefaultContext._traps,
4616 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow 4582 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow
4617 ) 4583 )
4618 4584
4585 @requires_extra_functionality
4619 def test_c_signal_dict(self): 4586 def test_c_signal_dict(self):
4620 if hasattr(C, 'setfailpoint'):
4621 random.seed(randseed)
4622 4587
4623 # SignalDict coverage 4588 # SignalDict coverage
4624 Context = C.Context 4589 Context = C.Context
4625 DefaultContext = C.DefaultContext 4590 DefaultContext = C.DefaultContext
4626 4591
4627 InvalidOperation = C.InvalidOperation 4592 InvalidOperation = C.InvalidOperation
4628 DivisionByZero = C.DivisionByZero 4593 DivisionByZero = C.DivisionByZero
4629 Overflow = C.Overflow 4594 Overflow = C.Overflow
4630 Subnormal = C.Subnormal 4595 Subnormal = C.Subnormal
4631 Underflow = C.Underflow 4596 Underflow = C.Underflow
(...skipping 67 matching lines...) Expand 10 before | Expand all | Expand 10 after
4699 Overflow: C.DecOverflow, 4664 Overflow: C.DecOverflow,
4700 DivisionByZero: C.DecDivisionByZero, 4665 DivisionByZero: C.DecDivisionByZero,
4701 InvalidOperation: C.DecIEEEInvalidOperation 4666 InvalidOperation: C.DecIEEEInvalidOperation
4702 } 4667 }
4703 IntCond = [ 4668 IntCond = [
4704 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError, 4669 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError,
4705 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError, 4670 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError,
4706 C.DecConversionSyntax, 4671 C.DecConversionSyntax,
4707 ] 4672 ]
4708 4673
4709 lim = 1 if hasattr(C, 'setfailpoint') else len(OrderedSignals[C]) 4674 lim = len(OrderedSignals[C])
4710 for r in range(lim): 4675 for r in range(lim):
4711 for t in range(lim): 4676 for t in range(lim):
4712 for round in RoundingModes[C]: 4677 for round in RoundingModes[C]:
4713 flags = random.sample(OrderedSignals[C], r) 4678 flags = random.sample(OrderedSignals[C], r)
4714 traps = random.sample(OrderedSignals[C], t) 4679 traps = random.sample(OrderedSignals[C], t)
4715 prec = random.randrange(1, 10000) 4680 prec = random.randrange(1, 10000)
4716 emin = random.randrange(-10000, 0) 4681 emin = random.randrange(-10000, 0)
4717 emax = random.randrange(0, 10000) 4682 emax = random.randrange(0, 10000)
4718 clamp = random.randrange(0, 2) 4683 clamp = random.randrange(0, 2)
4719 caps = random.randrange(0, 2) 4684 caps = random.randrange(0, 2)
(...skipping 22 matching lines...) Expand all
4742 4707
4743 for cond in IntCond: 4708 for cond in IntCond:
4744 c._flags = cond 4709 c._flags = cond
4745 self.assertTrue(c._flags&DecIEEEInvalidOperation) 4710 self.assertTrue(c._flags&DecIEEEInvalidOperation)
4746 assertIsExclusivelySet(InvalidOperation, c.flags) 4711 assertIsExclusivelySet(InvalidOperation, c.flags)
4747 4712
4748 for cond in IntCond: 4713 for cond in IntCond:
4749 c._traps = cond 4714 c._traps = cond
4750 self.assertTrue(c._traps&DecIEEEInvalidOperation) 4715 self.assertTrue(c._traps&DecIEEEInvalidOperation)
4751 assertIsExclusivelySet(InvalidOperation, c.traps) 4716 assertIsExclusivelySet(InvalidOperation, c.traps)
4717
4718 def test_invalid_override(self):
4719 Decimal = C.Decimal
4720
4721 try:
4722 from locale import CHAR_MAX
4723 except ImportError:
4724 return
4725
4726 def make_grouping(lst):
4727 return ''.join([chr(x) for x in lst])
4728
4729 def get_fmt(x, override=None, fmt='n'):
4730 return Decimal(x).__format__(fmt, override)
4731
4732 invalid_grouping = {
4733 'decimal_point' : ',',
4734 'grouping' : make_grouping([255, 255, 0]),
4735 'thousands_sep' : ','
4736 }
4737 invalid_dot = {
4738 'decimal_point' : 'xxxxx',
4739 'grouping' : make_grouping([3, 3, 0]),
4740 'thousands_sep' : ','
4741 }
4742 invalid_sep = {
4743 'decimal_point' : '.',
4744 'grouping' : make_grouping([3, 3, 0]),
4745 'thousands_sep' : 'yyyyy'
4746 }
4747
4748 if CHAR_MAX == 127: # negative grouping in override
4749 self.assertRaises(ValueError, get_fmt, 12345,
4750 invalid_grouping, 'g')
4751
4752 self.assertRaises(ValueError, get_fmt, 12345, invalid_dot, 'g')
4753 self.assertRaises(ValueError, get_fmt, 12345, invalid_sep, 'g')
4752 4754
4753 4755
4754 all_tests = [ 4756 all_tests = [
4755 CExplicitConstructionTest, PyExplicitConstructionTest, 4757 CExplicitConstructionTest, PyExplicitConstructionTest,
4756 CImplicitConstructionTest, PyImplicitConstructionTest, 4758 CImplicitConstructionTest, PyImplicitConstructionTest,
4757 CFormatTest, PyFormatTest, 4759 CFormatTest, PyFormatTest,
4758 CArithmeticOperatorsTest, PyArithmeticOperatorsTest, 4760 CArithmeticOperatorsTest, PyArithmeticOperatorsTest,
4759 CThreadingTest, PyThreadingTest, 4761 CThreadingTest, PyThreadingTest,
4760 CUsabilityTest, PyUsabilityTest, 4762 CUsabilityTest, PyUsabilityTest,
4761 CPythonAPItests, PyPythonAPItests, 4763 CPythonAPItests, PyPythonAPItests,
4762 CContextAPItests, PyContextAPItests, 4764 CContextAPItests, PyContextAPItests,
4763 CContextWithStatement, PyContextWithStatement, 4765 CContextWithStatement, PyContextWithStatement,
4764 CContextFlags, PyContextFlags, 4766 CContextFlags, PyContextFlags,
4765 CSpecialContexts, PySpecialContexts, 4767 CSpecialContexts, PySpecialContexts,
4766 CContextInputValidation, PyContextInputValidation, 4768 CContextInputValidation, PyContextInputValidation,
4767 CCoverage, PyCoverage, 4769 CCoverage, PyCoverage,
4768 CFunctionality, PyFunctionality, 4770 CFunctionality, PyFunctionality,
4769 CWhitebox, PyWhitebox, 4771 CWhitebox, PyWhitebox,
4770 CIBMTestCases, PyIBMTestCases, 4772 CIBMTestCases, PyIBMTestCases,
4771 ] 4773 ]
4772 4774
4773 # Delete C tests if _decimal.so is not present. 4775 # Delete C tests if _decimal.so is not present.
4774 if not C: 4776 if not C:
4775 all_tests = all_tests[1::2] 4777 all_tests = all_tests[1::2]
4776 4778 else:
4777 # Wrap test functions for testing api failures. Doing this in 4779 all_tests.insert(0, CheckAttributes)
4778 # test_main() causes spurious refleaks, so it is done here. 4780
4779 if hasattr(C, 'setapicalls'):
4780 for cls in all_tests:
4781 if cls == CIBMTestCases or cls == PyIBMTestCases:
4782 newfunc = withFailpoint(getattr(cls, 'eval_equation'))
4783 setattr(cls, 'eval_equation', newfunc)
4784 else:
4785 for attr in dir(cls):
4786 if attr.startswith('test_'):
4787 if attr == 'test_threading':
4788 continue
4789 newfunc = withFailpoint(getattr(cls, attr))
4790 setattr(cls, attr, newfunc)
4791 4781
4792 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):
4793 """ Execute the tests. 4783 """ Execute the tests.
4794 4784
4795 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
4796 is enabled in regrtest.py 4786 is enabled in regrtest.py
4797 """ 4787 """
4798 4788
4799 init(C) 4789 init(C)
4800 init(P) 4790 init(P)
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
4850 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')
4851 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')
4852 (opt, args) = p.parse_args() 4842 (opt, args) = p.parse_args()
4853 4843
4854 if opt.skip: 4844 if opt.skip:
4855 test_main(arith=False, verbose=True) 4845 test_main(arith=False, verbose=True)
4856 elif args: 4846 elif args:
4857 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)
4858 else: 4848 else:
4859 test_main(arith=True, verbose=True) 4849 test_main(arith=True, verbose=True)
LEFTRIGHT

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