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

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

Issue 7652: Merge C version of decimal into py3k.
Left Patch Set: Created 8 years, 5 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 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
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
186 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")
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
196 # List of individual .decTest test ids that correspond to tests that 128 # List of individual .decTest test ids that correspond to tests that
197 # we're skipping for one reason or another. 129 # we're skipping for one reason or another.
198 self.skipped_test_ids = set([ 130 self.skipped_test_ids = set([
199 # Skip implementation-specific scaleb tests. 131 # Skip implementation-specific scaleb tests.
200 'scbx164', 132 'scbx164',
201 'scbx165', 133 'scbx165',
202 134
203 # For some operations (currently exp, ln, log10, power), the decNumb er 135 # For some operations (currently exp, ln, log10, power), the decNumb er
204 # reference implementation imposes additional restrictions on the co ntext 136 # reference implementation imposes additional restrictions on the co ntext
205 # and operands. These restrictions are not part of the specificatio n; 137 # and operands. These restrictions are not part of the specificatio n;
206 # however, the effect of these restrictions does show up in some of the 138 # however, the effect of these restrictions does show up in some of the
207 # testcases. We skip testcases that violate these restrictions, sin ce 139 # testcases. We skip testcases that violate these restrictions, sin ce
208 # Decimal behaves differently from decNumber for these testcases so these 140 # Decimal behaves differently from decNumber for these testcases so these
209 # testcases would otherwise fail. 141 # testcases would otherwise fail.
210 'expx901', 142 'expx901',
211 'expx902', 143 'expx902',
212 'expx903', 144 'expx903',
(...skipping 116 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 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
459 else: 389 else:
460 self.fail("Did not raise %s in %s" % (error, s)) 390 self.fail("Did not raise %s in %s" % (error, s))
461 self.context.traps[error] = 0 391 self.context.traps[error] = 0
462 v = self.context.create_decimal(v) 392 v = self.context.create_decimal(v)
463 else: 393 else:
464 v = self.read_unlimited(v, self.context) 394 v = self.read_unlimited(v, self.context)
465 vals.append(v) 395 vals.append(v)
466 396
467 ans = FixQuotes(ans) 397 ans = FixQuotes(ans)
468 398
469 # three argument power/powmod (deprecated)
470 if self.decimal == C:
471 if fname == 'power' and len(vals) == 3:
472 # name is different
473 fname = 'powmod'
474 funct = getattr(self.context, fname)
475
476 if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string') : 399 if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string') :
477 for error in theirexceptions: 400 for error in theirexceptions:
478 self.context.traps[error] = 1 401 self.context.traps[error] = 1
479 try: 402 try:
480 funct(*vals) 403 funct(*vals)
481 except error: 404 except error:
482 pass 405 pass
483 except Signals[self.decimal] as e: 406 except Signals[self.decimal] as e:
484 self.fail("Raised %s in %s when %s disabled" % \ 407 self.fail("Raised %s in %s when %s disabled" % \
485 (e, s, error)) 408 (e, s, error))
(...skipping 20 matching lines...) Expand all
506 429
507 430
508 if DEBUG: 431 if DEBUG:
509 print("--", self.context) 432 print("--", self.context)
510 try: 433 try:
511 result = str(funct(*vals)) 434 result = str(funct(*vals))
512 if fname in self.LogicalFunctions: 435 if fname in self.LogicalFunctions:
513 result = str(int(eval(result))) # 'True', 'False' -> '1', '0' 436 result = str(int(eval(result))) # 'True', 'False' -> '1', '0'
514 except Signals[self.decimal] as error: 437 except Signals[self.decimal] as error:
515 self.fail("Raised %s in %s" % (error, s)) 438 self.fail("Raised %s in %s" % (error, s))
516 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.
517 # Errors are expected with failpoints. 440 print("ERROR:", s)
518 if not hasattr(C, 'setfailpoint'): 441 raise
519 print("ERROR:", s)
520 raise e.__class__
521 442
522 myexceptions = self.getexceptions() 443 myexceptions = self.getexceptions()
523 444
524 myexceptions.sort(key=repr) 445 myexceptions.sort(key=repr)
525 theirexceptions.sort(key=repr) 446 theirexceptions.sort(key=repr)
526 447
527 self.assertEqual(result, ans, 448 self.assertEqual(result, ans,
528 'Incorrect answer for ' + s + ' -- got ' + result) 449 'Incorrect answer for ' + s + ' -- got ' + result)
529 450
530 self.assertEqual(myexceptions, theirexceptions, 451 self.assertEqual(myexceptions, theirexceptions,
531 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) 452 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions))
532 return 453 return
533 454
534 def getexceptions(self): 455 def getexceptions(self):
535 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]]
536 457
537 def change_precision(self, prec): 458 def change_precision(self, prec):
538 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 459 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
539 self.context.unsafe_setprec(prec) 460 self.context._unsafe_setprec(prec)
540 else: 461 else:
541 self.context.prec = prec 462 self.context.prec = prec
542 def change_rounding_method(self, rounding): 463 def change_rounding_method(self, rounding):
543 self.context.rounding = rounding 464 self.context.rounding = rounding
544 def change_min_exponent(self, exp): 465 def change_min_exponent(self, exp):
545 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 466 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
546 self.context.unsafe_setemin(exp) 467 self.context._unsafe_setemin(exp)
547 else: 468 else:
548 self.context.Emin = exp 469 self.context.Emin = exp
549 def change_max_exponent(self, exp): 470 def change_max_exponent(self, exp):
550 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 471 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
551 self.context.unsafe_setemax(exp) 472 self.context._unsafe_setemax(exp)
552 else: 473 else:
553 self.context.Emax = exp 474 self.context.Emax = exp
554 def change_clamp(self, clamp): 475 def change_clamp(self, clamp):
555 self.context.clamp = clamp 476 self.context.clamp = clamp
556 477
557 class CIBMTestCases(IBMTestCases): 478 class CIBMTestCases(IBMTestCases):
558 decimal = C 479 decimal = C
559 class PyIBMTestCases(IBMTestCases): 480 class PyIBMTestCases(IBMTestCases):
560 decimal = P 481 decimal = P
561 482
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
617 self.assertEqual(str(Decimal('45e2')), '4.5E+3') 538 self.assertEqual(str(Decimal('45e2')), '4.5E+3')
618 539
619 #just not a number 540 #just not a number
620 self.assertEqual(str(Decimal('ugly')), 'NaN') 541 self.assertEqual(str(Decimal('ugly')), 'NaN')
621 542
622 #leading and trailing whitespace permitted 543 #leading and trailing whitespace permitted
623 self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4') 544 self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4')
624 self.assertEqual(str(Decimal(' -7.89')), '-7.89') 545 self.assertEqual(str(Decimal(' -7.89')), '-7.89')
625 self.assertEqual(str(Decimal(" 3.45679 ")), '3.45679') 546 self.assertEqual(str(Decimal(" 3.45679 ")), '3.45679')
626 547
548 # unicode whitespace
549 for lead in ["", ' ', '\u00a0', '\u205f']:
550 for trail in ["", ' ', '\u00a0', '\u205f']:
551 self.assertEqual(str(Decimal(lead + '9.311E+28' + trail)),
552 '9.311E+28')
553
627 with localcontext() as c: 554 with localcontext() as c:
628 c.traps[InvalidOperation] = True 555 c.traps[InvalidOperation] = True
629 # Invalid string 556 # Invalid string
630 self.assertRaises(InvalidOperation, Decimal, "xyz") 557 self.assertRaises(InvalidOperation, Decimal, "xyz")
631 # Two arguments max 558 # Two arguments max
632 self.assertRaises(TypeError, Decimal, "1234", "x", "y") 559 self.assertRaises(TypeError, Decimal, "1234", "x", "y")
633 560
561 # space within the numeric part
562 self.assertRaises(InvalidOperation, Decimal, "1\u00a02\u00a03")
563 self.assertRaises(InvalidOperation, Decimal, "\u00a01\u00a02\u00a0")
564
565 # unicode whitespace
566 self.assertRaises(InvalidOperation, Decimal, "\u00a0")
567 self.assertRaises(InvalidOperation, Decimal, "\u00a0\u00a0")
568
569 # embedded NUL
570 self.assertRaises(InvalidOperation, Decimal, "12\u00003")
571
572
634 def test_explicit_from_tuples(self): 573 def test_explicit_from_tuples(self):
635 Decimal = self.decimal.Decimal 574 Decimal = self.decimal.Decimal
636 575
637 #zero 576 #zero
638 d = Decimal( (0, (0,), 0) ) 577 d = Decimal( (0, (0,), 0) )
639 self.assertEqual(str(d), '0') 578 self.assertEqual(str(d), '0')
640 579
641 #int 580 #int
642 d = Decimal( (1, (4, 5), 0) ) 581 d = Decimal( (1, (4, 5), 0) )
643 self.assertEqual(str(d), '-45') 582 self.assertEqual(str(d), '-45')
(...skipping 23 matching lines...) Expand all
667 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) ) 606 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) )
668 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') ) 607 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') )
669 608
670 #bad coefficients 609 #bad coefficients
671 self.assertRaises(ValueError, Decimal, (1, "xyz", 2) ) 610 self.assertRaises(ValueError, Decimal, (1, "xyz", 2) )
672 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) ) 611 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) )
673 self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) ) 612 self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) )
674 self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) ) 613 self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) )
675 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) ) 614 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) )
676 615
616 def test_explicit_from_list(self):
617 Decimal = self.decimal.Decimal
618
619 d = Decimal([0, [0], 0])
620 self.assertEqual(str(d), '0')
621
622 d = Decimal([1, [4, 3, 4, 9, 1, 3, 5, 3, 4], -25])
623 self.assertEqual(str(d), '-4.34913534E-17')
624
625 d = Decimal([1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25])
626 self.assertEqual(str(d), '-4.34913534E-17')
627
628 d = Decimal((1, [4, 3, 4, 9, 1, 3, 5, 3, 4], -25))
629 self.assertEqual(str(d), '-4.34913534E-17')
630
677 def test_explicit_from_bool(self): 631 def test_explicit_from_bool(self):
678 Decimal = self.decimal.Decimal 632 Decimal = self.decimal.Decimal
679 633
680 self.assertIs(bool(Decimal(0)), False) 634 self.assertIs(bool(Decimal(0)), False)
681 self.assertIs(bool(Decimal(1)), True) 635 self.assertIs(bool(Decimal(1)), True)
682 self.assertEqual(Decimal(False), Decimal(0)) 636 self.assertEqual(Decimal(False), Decimal(0))
683 self.assertEqual(Decimal(True), Decimal(1)) 637 self.assertEqual(Decimal(True), Decimal(1))
684 638
685 def test_explicit_from_Decimal(self): 639 def test_explicit_from_Decimal(self):
686 Decimal = self.decimal.Decimal 640 Decimal = self.decimal.Decimal
(...skipping 13 matching lines...) Expand all
700 e = Decimal(d) 654 e = Decimal(d)
701 self.assertEqual(str(e), '-45') 655 self.assertEqual(str(e), '-45')
702 656
703 #zero 657 #zero
704 d = Decimal(0) 658 d = Decimal(0)
705 e = Decimal(d) 659 e = Decimal(d)
706 self.assertEqual(str(e), '0') 660 self.assertEqual(str(e), '0')
707 661
708 @requires_IEEE_754 662 @requires_IEEE_754
709 def test_explicit_from_float(self): 663 def test_explicit_from_float(self):
710 if hasattr(C, 'setfailpoint'):
711 random.seed(randseed)
712 664
713 Decimal = self.decimal.Decimal 665 Decimal = self.decimal.Decimal
714 666
715 r = Decimal(0.1) 667 r = Decimal(0.1)
716 self.assertEqual(type(r), Decimal) 668 self.assertEqual(type(r), Decimal)
717 self.assertEqual(str(r), 669 self.assertEqual(str(r),
718 '0.1000000000000000055511151231257827021181583404541015625') 670 '0.1000000000000000055511151231257827021181583404541015625')
719 self.assertTrue(Decimal(float('nan')).is_qnan()) 671 self.assertTrue(Decimal(float('nan')).is_qnan())
720 self.assertTrue(Decimal(float('inf')).is_infinite()) 672 self.assertTrue(Decimal(float('inf')).is_infinite())
721 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
811 763
812 nc.traps[InvalidOperation] = False 764 nc.traps[InvalidOperation] = False
813 self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN') 765 self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN')
814 self.assertTrue(nc.flags[InvalidOperation]) 766 self.assertTrue(nc.flags[InvalidOperation])
815 767
816 nc.flags[InvalidOperation] = False 768 nc.flags[InvalidOperation] = False
817 self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN') 769 self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN')
818 self.assertTrue(nc.flags[InvalidOperation]) 770 self.assertTrue(nc.flags[InvalidOperation])
819 771
820 def test_explicit_context_create_from_float(self): 772 def test_explicit_context_create_from_float(self):
821 if hasattr(C, 'setfailpoint'):
822 random.seed(randseed)
823 773
824 Decimal = self.decimal.Decimal 774 Decimal = self.decimal.Decimal
825 775
826 nc = self.decimal.Context() 776 nc = self.decimal.Context()
827 r = nc.create_decimal(0.1) 777 r = nc.create_decimal(0.1)
828 self.assertEqual(type(r), Decimal) 778 self.assertEqual(type(r), Decimal)
829 self.assertEqual(str(r), '0.1000000000000000055511151231') 779 self.assertEqual(str(r), '0.1000000000000000055511151231')
830 self.assertTrue(nc.create_decimal(float('nan')).is_qnan()) 780 self.assertTrue(nc.create_decimal(float('nan')).is_qnan())
831 self.assertTrue(nc.create_decimal(float('inf')).is_infinite()) 781 self.assertTrue(nc.create_decimal(float('inf')).is_infinite())
832 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
994 944
995 ('g', '0', '0'), 945 ('g', '0', '0'),
996 ('g', '0.0', '0.0'), 946 ('g', '0.0', '0.0'),
997 ('g', '0E1', '0e+1'), 947 ('g', '0E1', '0e+1'),
998 ('G', '0E1', '0E+1'), 948 ('G', '0E1', '0E+1'),
999 ('g', '0E-5', '0.00000'), 949 ('g', '0E-5', '0.00000'),
1000 ('g', '0E-6', '0.000000'), 950 ('g', '0E-6', '0.000000'),
1001 ('g', '0E-7', '0e-7'), 951 ('g', '0E-7', '0e-7'),
1002 ('g', '-0E2', '-0e+2'), 952 ('g', '-0E2', '-0e+2'),
1003 ('.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'
1004 ('.1g', '3.14159265', '3'), 955 ('.1g', '3.14159265', '3'),
1005 ('.2g', '3.14159265', '3.1'), 956 ('.2g', '3.14159265', '3.1'),
1006 ('.5g', '3.14159265', '3.1416'), 957 ('.5g', '3.14159265', '3.1416'),
1007 ('.7g', '3.14159265', '3.141593'), 958 ('.7g', '3.14159265', '3.141593'),
1008 ('.8g', '3.14159265', '3.1415926'), # round-half-even! 959 ('.8g', '3.14159265', '3.1415926'), # round-half-even!
1009 ('.9g', '3.14159265', '3.14159265'), 960 ('.9g', '3.14159265', '3.14159265'),
1010 ('.10g', '3.14159265', '3.14159265'), # don't pad 961 ('.10g', '3.14159265', '3.14159265'), # don't pad
1011 962
1012 ('%', '0E1', '0%'), 963 ('%', '0E1', '0%'),
1013 ('%', '0E0', '0%'), 964 ('%', '0E0', '0%'),
(...skipping 158 matching lines...) Expand 10 before | Expand all | Expand 10 after
1172 self.assertEqual(get_fmt(123456, crazy, '07n'), '1-2345-6') 1123 self.assertEqual(get_fmt(123456, crazy, '07n'), '1-2345-6')
1173 self.assertEqual(get_fmt(123456, crazy, '08n'), '1-2345-6') 1124 self.assertEqual(get_fmt(123456, crazy, '08n'), '1-2345-6')
1174 self.assertEqual(get_fmt(123456, crazy, '09n'), '01-2345-6') 1125 self.assertEqual(get_fmt(123456, crazy, '09n'), '01-2345-6')
1175 self.assertEqual(get_fmt(123456, crazy, '010n'), '0-01-2345-6') 1126 self.assertEqual(get_fmt(123456, crazy, '010n'), '0-01-2345-6')
1176 self.assertEqual(get_fmt(123456, crazy, '011n'), '0-01-2345-6') 1127 self.assertEqual(get_fmt(123456, crazy, '011n'), '0-01-2345-6')
1177 self.assertEqual(get_fmt(123456, crazy, '012n'), '00-01-2345-6') 1128 self.assertEqual(get_fmt(123456, crazy, '012n'), '00-01-2345-6')
1178 self.assertEqual(get_fmt(123456, crazy, '013n'), '000-01-2345-6') 1129 self.assertEqual(get_fmt(123456, crazy, '013n'), '000-01-2345-6')
1179 1130
1180 # wide char separator and decimal point 1131 # wide char separator and decimal point
1181 self.assertEqual(get_fmt(Decimal('-1.5'), dotsep_wide, '020n'), 1132 self.assertEqual(get_fmt(Decimal('-1.5'), dotsep_wide, '020n'),
1182 '-0´000´000´000´001¿5') 1133 '-0\u00b4000\u00b4000\u00b4000\u00b4001\u00bf5')
1183 1134
1184 def test_wide_char_separator_decimal_point(self): 1135 def test_wide_char_separator_decimal_point(self):
1185 # locale with wide char separator and decimal point 1136 # locale with wide char separator and decimal point
1186 Decimal = self.decimal.Decimal 1137 Decimal = self.decimal.Decimal
1187 1138
1188 try: 1139 try:
1189 locale.setlocale(locale.LC_ALL, 'ps_AF') 1140 locale.setlocale(locale.LC_ALL, 'ps_AF')
1190 except locale.Error: 1141 except locale.Error:
1191 return 1142 return
1192 1143
1193 self.assertEqual(format(Decimal('100000000.123'), 'n'), 1144 self.assertEqual(format(Decimal('100000000.123'), 'n'),
1194 '100٬000٬000٫123') 1145 '100\u066c000\u066c000\u066b123')
1195 locale.resetlocale() 1146 locale.resetlocale()
1196 1147
1197 class CFormatTest(FormatTest): 1148 class CFormatTest(FormatTest):
1198 decimal = C 1149 decimal = C
1199 class PyFormatTest(FormatTest): 1150 class PyFormatTest(FormatTest):
1200 decimal = P 1151 decimal = P
1201 1152
1202 class ArithmeticOperatorsTest(unittest.TestCase): 1153 class ArithmeticOperatorsTest(unittest.TestCase):
1203 '''Unit tests for all arithmetic operators, binary and unary.''' 1154 '''Unit tests for all arithmetic operators, binary and unary.'''
1204 1155
(...skipping 395 matching lines...) Expand 10 before | Expand all | Expand 10 after
1600 # Test the "threading isolation" of a Context. Also test changing 1551 # Test the "threading isolation" of a Context. Also test changing
1601 # the DefaultContext, which acts as a template for the thread-local 1552 # the DefaultContext, which acts as a template for the thread-local
1602 # contexts. 1553 # contexts.
1603 save_prec = DefaultContext.prec 1554 save_prec = DefaultContext.prec
1604 save_emax = DefaultContext.Emax 1555 save_emax = DefaultContext.Emax
1605 save_emin = DefaultContext.Emin 1556 save_emin = DefaultContext.Emin
1606 DefaultContext.prec = 24 1557 DefaultContext.prec = 24
1607 DefaultContext.Emax = 425000000 1558 DefaultContext.Emax = 425000000
1608 DefaultContext.Emin = -425000000 1559 DefaultContext.Emin = -425000000
1609 1560
1610 with protectfail(): 1561 self.synchro = threading.Event()
1611 self.synchro = threading.Event() 1562 self.finish1 = threading.Event()
1612 self.finish1 = threading.Event() 1563 self.finish2 = threading.Event()
1613 self.finish2 = threading.Event() 1564
1614 1565 th1 = threading.Thread(target=thfunc1, args=(self,))
1615 th1 = threading.Thread(target=thfunc1, args=(self,)) 1566 th2 = threading.Thread(target=thfunc2, args=(self,))
1616 th2 = threading.Thread(target=thfunc2, args=(self,)) 1567
1617 1568 th1.start()
1618 th1.start() 1569 th2.start()
1619 th2.start() 1570
1620 1571 self.finish1.wait()
1621 self.finish1.wait() 1572 self.finish2.wait()
1622 self.finish2.wait()
1623 1573
1624 for sig in Signals[self.decimal]: 1574 for sig in Signals[self.decimal]:
1625 self.assertFalse(DefaultContext.flags[sig]) 1575 self.assertFalse(DefaultContext.flags[sig])
1626 1576
1627 DefaultContext.prec = save_prec 1577 DefaultContext.prec = save_prec
1628 DefaultContext.Emax = save_emax 1578 DefaultContext.Emax = save_emax
1629 DefaultContext.Emin = save_emin 1579 DefaultContext.Emin = save_emin
1630 return 1580 return
1631 1581
1632 @unittest.skipUnless(threading, 'threading required') 1582 @unittest.skipUnless(threading, 'threading required')
1633 class CThreadingTest(ThreadingTest): 1583 class CThreadingTest(ThreadingTest):
1634 decimal = C 1584 decimal = C
1635 @unittest.skipUnless(threading, 'threading required') 1585 @unittest.skipUnless(threading, 'threading required')
1636 class PyThreadingTest(ThreadingTest): 1586 class PyThreadingTest(ThreadingTest):
1637 decimal = P 1587 decimal = P
1638 1588
1639 class UsabilityTest(unittest.TestCase): 1589 class UsabilityTest(unittest.TestCase):
1640 '''Unit tests for Usability cases of Decimal.''' 1590 '''Unit tests for Usability cases of Decimal.'''
1641 1591
1642 def test_comparison_operators(self): 1592 def test_comparison_operators(self):
1643 if hasattr(C, 'setfailpoint'):
1644 random.seed(randseed)
1645 1593
1646 Decimal = self.decimal.Decimal 1594 Decimal = self.decimal.Decimal
1647 1595
1648 da = Decimal('23.42') 1596 da = Decimal('23.42')
1649 db = Decimal('23.42') 1597 db = Decimal('23.42')
1650 dc = Decimal('45') 1598 dc = Decimal('45')
1651 1599
1652 #two Decimals 1600 #two Decimals
1653 self.assertGreater(dc, da) 1601 self.assertGreater(dc, da)
1654 self.assertGreaterEqual(dc, da) 1602 self.assertGreaterEqual(dc, da)
(...skipping 106 matching lines...) Expand 10 before | Expand all | Expand 10 after
1761 def test_copy_and_deepcopy_methods(self): 1709 def test_copy_and_deepcopy_methods(self):
1762 Decimal = self.decimal.Decimal 1710 Decimal = self.decimal.Decimal
1763 1711
1764 d = Decimal('43.24') 1712 d = Decimal('43.24')
1765 c = copy.copy(d) 1713 c = copy.copy(d)
1766 self.assertEqual(id(c), id(d)) 1714 self.assertEqual(id(c), id(d))
1767 dc = copy.deepcopy(d) 1715 dc = copy.deepcopy(d)
1768 self.assertEqual(id(dc), id(d)) 1716 self.assertEqual(id(dc), id(d))
1769 1717
1770 def test_hash_method(self): 1718 def test_hash_method(self):
1771 if hasattr(C, 'setfailpoint'):
1772 random.seed(randseed)
1773 1719
1774 Decimal = self.decimal.Decimal 1720 Decimal = self.decimal.Decimal
1775 localcontext = self.decimal.localcontext 1721 localcontext = self.decimal.localcontext
1776 1722
1777 def hashit(d): 1723 def hashit(d):
1778 a = hash(d) 1724 a = hash(d)
1779 b = d.__hash__() 1725 b = d.__hash__()
1780 self.assertEqual(a, b) 1726 self.assertEqual(a, b)
1781 return a 1727 return a
1782 1728
1783 #just that it's hashable 1729 #just that it's hashable
1784 hashit(Decimal(23)) 1730 hashit(Decimal(23))
1785 hashit(Decimal('Infinity')) 1731 hashit(Decimal('Infinity'))
1786 hashit(Decimal('-Infinity')) 1732 hashit(Decimal('-Infinity'))
1787 hashit(Decimal('nan123')) 1733 hashit(Decimal('nan123'))
1788 hashit(Decimal('-NaN')) 1734 hashit(Decimal('-NaN'))
1789 1735
1790 test_values = [Decimal(sign*(2**m + n)) 1736 test_values = [Decimal(sign*(2**m + n))
1791 for m in [0, 14, 15, 16, 17, 30, 31, 1737 for m in [0, 14, 15, 16, 17, 30, 31,
1792 32, 33, 61, 62, 63, 64, 65, 66] 1738 32, 33, 61, 62, 63, 64, 65, 66]
1793 for n in range(-10, 10) 1739 for n in range(-10, 10)
1794 for sign in [-1, 1]] 1740 for sign in [-1, 1]]
1795 if hasattr(C, 'setfailpoint'):
1796 test_values = random.sample(test_values, 10)
1797 test_values.extend([ 1741 test_values.extend([
1798 Decimal("-1"), # ==> -2 1742 Decimal("-1"), # ==> -2
1799 Decimal("-0"), # zeros 1743 Decimal("-0"), # zeros
1800 Decimal("0.00"), 1744 Decimal("0.00"),
1801 Decimal("-0.000"), 1745 Decimal("-0.000"),
1802 Decimal("0E10"), 1746 Decimal("0E10"),
1803 Decimal("-0E12"), 1747 Decimal("-0E12"),
1804 Decimal("10.0"), # negative exponent 1748 Decimal("10.0"), # negative exponent
1805 Decimal("-23.00000"), 1749 Decimal("-23.00000"),
1806 Decimal("1230E100"), # positive exponent 1750 Decimal("1230E100"), # positive exponent
(...skipping 102 matching lines...) Expand 10 before | Expand all | Expand 10 after
1909 #floor 1853 #floor
1910 test_pairs = [ 1854 test_pairs = [
1911 ('123.00', 123), 1855 ('123.00', 123),
1912 ('3.2', 3), 1856 ('3.2', 3),
1913 ('3.54', 3), 1857 ('3.54', 3),
1914 ('3.899', 3), 1858 ('3.899', 3),
1915 ('-2.3', -3), 1859 ('-2.3', -3),
1916 ('-11.0', -11), 1860 ('-11.0', -11),
1917 ('0.0', 0), 1861 ('0.0', 0),
1918 ('-0E3', 0), 1862 ('-0E3', 0),
1863 ('89891211712379812736.1', 89891211712379812736),
1919 ] 1864 ]
1920 for d, i in test_pairs: 1865 for d, i in test_pairs:
1921 self.assertEqual(math.floor(Decimal(d)), i) 1866 self.assertEqual(math.floor(Decimal(d)), i)
1922 self.assertRaises(ValueError, math.floor, Decimal('-NaN')) 1867 self.assertRaises(ValueError, math.floor, Decimal('-NaN'))
1923 self.assertRaises(ValueError, math.floor, Decimal('sNaN')) 1868 self.assertRaises(ValueError, math.floor, Decimal('sNaN'))
1924 self.assertRaises(ValueError, math.floor, Decimal('NaN123')) 1869 self.assertRaises(ValueError, math.floor, Decimal('NaN123'))
1925 self.assertRaises(OverflowError, math.floor, Decimal('Inf')) 1870 self.assertRaises(OverflowError, math.floor, Decimal('Inf'))
1926 self.assertRaises(OverflowError, math.floor, Decimal('-Inf')) 1871 self.assertRaises(OverflowError, math.floor, Decimal('-Inf'))
1927 1872
1928 #ceiling 1873 #ceiling
1929 test_pairs = [ 1874 test_pairs = [
1930 ('123.00', 123), 1875 ('123.00', 123),
1931 ('3.2', 4), 1876 ('3.2', 4),
1932 ('3.54', 4), 1877 ('3.54', 4),
1933 ('3.899', 4), 1878 ('3.899', 4),
1934 ('-2.3', -2), 1879 ('-2.3', -2),
1935 ('-11.0', -11), 1880 ('-11.0', -11),
1936 ('0.0', 0), 1881 ('0.0', 0),
1937 ('-0E3', 0), 1882 ('-0E3', 0),
1883 ('89891211712379812736.1', 89891211712379812737),
1938 ] 1884 ]
1939 for d, i in test_pairs: 1885 for d, i in test_pairs:
1940 self.assertEqual(math.ceil(Decimal(d)), i) 1886 self.assertEqual(math.ceil(Decimal(d)), i)
1941 self.assertRaises(ValueError, math.ceil, Decimal('-NaN')) 1887 self.assertRaises(ValueError, math.ceil, Decimal('-NaN'))
1942 self.assertRaises(ValueError, math.ceil, Decimal('sNaN')) 1888 self.assertRaises(ValueError, math.ceil, Decimal('sNaN'))
1943 self.assertRaises(ValueError, math.ceil, Decimal('NaN123')) 1889 self.assertRaises(ValueError, math.ceil, Decimal('NaN123'))
1944 self.assertRaises(OverflowError, math.ceil, Decimal('Inf')) 1890 self.assertRaises(OverflowError, math.ceil, Decimal('Inf'))
1945 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf')) 1891 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf'))
1946 1892
1947 #round, single argument 1893 #round, single argument
(...skipping 231 matching lines...) Expand 10 before | Expand all | Expand 10 after
2179 r = pickle.loads(sy) 2125 r = pickle.loads(sy)
2180 self.assertIsInstance(r, C.Decimal) 2126 self.assertIsInstance(r, C.Decimal)
2181 self.assertEqual(r, x) 2127 self.assertEqual(r, x)
2182 2128
2183 sys.modules['decimal'] = savedecimal 2129 sys.modules['decimal'] = savedecimal
2184 2130
2185 def test_int(self): 2131 def test_int(self):
2186 Decimal = self.decimal.Decimal 2132 Decimal = self.decimal.Decimal
2187 ROUND_DOWN = self.decimal.ROUND_DOWN 2133 ROUND_DOWN = self.decimal.ROUND_DOWN
2188 2134
2189 lim = 10 if hasattr(C, 'setfailpoint') else 250 2135 for x in range(-250, 250):
2190 for x in range(-lim, lim):
2191 s = '%0.2f' % (x / 100.0) 2136 s = '%0.2f' % (x / 100.0)
2192 # should work the same as for floats 2137 # should work the same as for floats
2193 self.assertEqual(int(Decimal(s)), int(float(s))) 2138 self.assertEqual(int(Decimal(s)), int(float(s)))
2194 # 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
2195 d = Decimal(s) 2140 d = Decimal(s)
2196 r = d.to_integral(ROUND_DOWN) 2141 r = d.to_integral(ROUND_DOWN)
2197 self.assertEqual(Decimal(int(d)), r) 2142 self.assertEqual(Decimal(int(d)), r)
2198 2143
2199 self.assertRaises(ValueError, int, Decimal('-nan')) 2144 self.assertRaises(ValueError, int, Decimal('-nan'))
2200 self.assertRaises(ValueError, int, Decimal('snan')) 2145 self.assertRaises(ValueError, int, Decimal('snan'))
2201 self.assertRaises(OverflowError, int, Decimal('inf')) 2146 self.assertRaises(OverflowError, int, Decimal('inf'))
2202 self.assertRaises(OverflowError, int, Decimal('-inf')) 2147 self.assertRaises(OverflowError, int, Decimal('-inf'))
2203 2148
2204 def test_trunc(self): 2149 def test_trunc(self):
2205 Decimal = self.decimal.Decimal 2150 Decimal = self.decimal.Decimal
2206 ROUND_DOWN = self.decimal.ROUND_DOWN 2151 ROUND_DOWN = self.decimal.ROUND_DOWN
2207 2152
2208 lim = 10 if hasattr(C, 'setfailpoint') else 250 2153 for x in range(-250, 250):
2209 for x in range(-lim, lim):
2210 s = '%0.2f' % (x / 100.0) 2154 s = '%0.2f' % (x / 100.0)
2211 # should work the same as for floats 2155 # should work the same as for floats
2212 self.assertEqual(int(Decimal(s)), int(float(s))) 2156 self.assertEqual(int(Decimal(s)), int(float(s)))
2213 # 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
2214 d = Decimal(s) 2158 d = Decimal(s)
2215 r = d.to_integral(ROUND_DOWN) 2159 r = d.to_integral(ROUND_DOWN)
2216 self.assertEqual(Decimal(math.trunc(d)), r) 2160 self.assertEqual(Decimal(math.trunc(d)), r)
2217 2161
2218 def test_from_float(self): 2162 def test_from_float(self):
2219 if hasattr(C, 'setfailpoint'):
2220 random.seed(randseed)
2221 2163
2222 Decimal = self.decimal.Decimal 2164 Decimal = self.decimal.Decimal
2223 2165
2224 class MyDecimal(Decimal): 2166 class MyDecimal(Decimal):
2225 pass 2167 pass
2226 2168
2227 self.assertTrue(issubclass(MyDecimal, Decimal)) 2169 self.assertTrue(issubclass(MyDecimal, Decimal))
2228 2170
2229 r = MyDecimal.from_float(0.1) 2171 r = MyDecimal.from_float(0.1)
2230 self.assertEqual(type(r), MyDecimal) 2172 self.assertEqual(type(r), MyDecimal)
2231 self.assertEqual(str(r), 2173 self.assertEqual(str(r),
2232 '0.1000000000000000055511151231257827021181583404541015625') 2174 '0.1000000000000000055511151231257827021181583404541015625')
2233 bigint = 12345678901234567890123456789 2175 bigint = 12345678901234567890123456789
2234 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint)) 2176 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
2235 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan()) 2177 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
2236 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite()) 2178 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
2237 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite()) 2179 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
2238 self.assertEqual(str(MyDecimal.from_float(float('nan'))), 2180 self.assertEqual(str(MyDecimal.from_float(float('nan'))),
2239 str(Decimal('NaN'))) 2181 str(Decimal('NaN')))
2240 self.assertEqual(str(MyDecimal.from_float(float('inf'))), 2182 self.assertEqual(str(MyDecimal.from_float(float('inf'))),
2241 str(Decimal('Infinity'))) 2183 str(Decimal('Infinity')))
2242 self.assertEqual(str(MyDecimal.from_float(float('-inf'))), 2184 self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
2243 str(Decimal('-Infinity'))) 2185 str(Decimal('-Infinity')))
2244 self.assertRaises(TypeError, MyDecimal.from_float, 'abc') 2186 self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
2245 lim = 10 if hasattr(C, 'setfailpoint') else 200 2187 for i in range(200):
2246 for i in range(lim):
2247 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0) 2188 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
2248 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 2189 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip
2249 2190
2250 def test_create_decimal_from_float(self): 2191 def test_create_decimal_from_float(self):
2251 Decimal = self.decimal.Decimal 2192 Decimal = self.decimal.Decimal
2252 Context = self.decimal.Context 2193 Context = self.decimal.Context
2253 ROUND_DOWN = self.decimal.ROUND_DOWN 2194 ROUND_DOWN = self.decimal.ROUND_DOWN
2254 ROUND_UP = self.decimal.ROUND_UP 2195 ROUND_UP = self.decimal.ROUND_UP
2255 Inexact = self.decimal.Inexact 2196 Inexact = self.decimal.Inexact
2256 2197
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
2311 self.assertEqual(x.conjugate(), x) 2252 self.assertEqual(x.conjugate(), x)
2312 2253
2313 x = Decimal("1") 2254 x = Decimal("1")
2314 self.assertEqual(complex(x), complex(float(1))) 2255 self.assertEqual(complex(x), complex(float(1)))
2315 2256
2316 self.assertRaises(AttributeError, setattr, x, 'real', 100) 2257 self.assertRaises(AttributeError, setattr, x, 'real', 100)
2317 self.assertRaises(AttributeError, setattr, x, 'imag', 100) 2258 self.assertRaises(AttributeError, setattr, x, 'imag', 100)
2318 self.assertRaises(AttributeError, setattr, x, 'conjugate', 100) 2259 self.assertRaises(AttributeError, setattr, x, 'conjugate', 100)
2319 self.assertRaises(AttributeError, setattr, x, '__complex__', 100) 2260 self.assertRaises(AttributeError, setattr, x, '__complex__', 100)
2320 2261
2262 def test_named_parameters(self):
2263 D = self.decimal.Decimal
2264 Context = self.decimal.Context
2265 localcontext = self.decimal.localcontext
2266 InvalidOperation = self.decimal.InvalidOperation
2267 Overflow = self.decimal.Overflow
2268
2269 xc = Context()
2270 xc.prec = 1
2271 xc.Emax = 1
2272 xc.Emin = -1
2273
2274 with localcontext() as c:
2275 c.clear_flags()
2276
2277 self.assertEqual(D(9, xc), 9)
2278 self.assertEqual(D(9, context=xc), 9)
2279 self.assertEqual(D(context=xc, value=9), 9)
2280 self.assertEqual(D(context=xc), 0)
2281 xc.clear_flags()
2282 self.assertRaises(InvalidOperation, D, "xyz", context=xc)
2283 self.assertTrue(xc.flags[InvalidOperation])
2284 self.assertFalse(c.flags[InvalidOperation])
2285
2286 xc.clear_flags()
2287 self.assertEqual(D(2).exp(context=xc), 7)
2288 self.assertRaises(Overflow, D(8).exp, context=xc)
2289 self.assertTrue(xc.flags[Overflow])
2290 self.assertFalse(c.flags[Overflow])
2291
2292 xc.clear_flags()
2293 self.assertEqual(D(2).ln(context=xc), D('0.7'))
2294 self.assertRaises(InvalidOperation, D(-1).ln, context=xc)
2295 self.assertTrue(xc.flags[InvalidOperation])
2296 self.assertFalse(c.flags[InvalidOperation])
2297
2298 self.assertEqual(D(0).log10(context=xc), D('-inf'))
2299 self.assertEqual(D(-1).next_minus(context=xc), -2)
2300 self.assertEqual(D(-1).next_plus(context=xc), D('-0.9'))
2301 self.assertEqual(D("9.73").normalize(context=xc), D('1E+1'))
2302 self.assertEqual(D("9999").to_integral(context=xc), 9999)
2303 self.assertEqual(D("-2000").to_integral_exact(context=xc), -2000)
2304 self.assertEqual(D("123").to_integral_value(context=xc), 123)
2305 self.assertEqual(D("0.0625").sqrt(context=xc), D('0.2'))
2306
2307 self.assertEqual(D("0.0625").compare(context=xc, other=3), -1)
2308 xc.clear_flags()
2309 self.assertRaises(InvalidOperation,
2310 D("0").compare_signal, D('nan'), context=xc)
2311 self.assertTrue(xc.flags[InvalidOperation])
2312 self.assertFalse(c.flags[InvalidOperation])
2313 self.assertEqual(D("0.01").max(D('0.0101'), context=xc), D('0.0'))
2314 self.assertEqual(D("0.01").max(D('0.0101'), context=xc), D('0.0'))
2315 self.assertEqual(D("0.2").max_mag(D('-0.3'), context=xc),
2316 D('-0.3'))
2317 self.assertEqual(D("0.02").min(D('-0.03'), context=xc), D('-0.0'))
2318 self.assertEqual(D("0.02").min_mag(D('-0.03'), context=xc),
2319 D('0.0'))
2320 self.assertEqual(D("0.2").next_toward(D('-1'), context=xc), D('0.1') )
2321 xc.clear_flags()
2322 self.assertRaises(InvalidOperation,
2323 D("0.2").quantize, D('1e10'), context=xc)
2324 self.assertTrue(xc.flags[InvalidOperation])
2325 self.assertFalse(c.flags[InvalidOperation])
2326 self.assertEqual(D("9.99").remainder_near(D('1.5'), context=xc),
2327 D('-0.5'))
2328
2329 self.assertEqual(D("9.9").fma(third=D('0.9'), context=xc, other=7),
2330 D('7E+1'))
2331
2332 self.assertRaises(TypeError, D(1).is_canonical, context=xc)
2333 self.assertRaises(TypeError, D(1).is_finite, context=xc)
2334 self.assertRaises(TypeError, D(1).is_infinite, context=xc)
2335 self.assertRaises(TypeError, D(1).is_nan, context=xc)
2336 self.assertRaises(TypeError, D(1).is_qnan, context=xc)
2337 self.assertRaises(TypeError, D(1).is_snan, context=xc)
2338 self.assertRaises(TypeError, D(1).is_signed, context=xc)
2339 self.assertRaises(TypeError, D(1).is_zero, context=xc)
2340
2341 self.assertFalse(D("0.01").is_normal(context=xc))
2342 self.assertTrue(D("0.01").is_subnormal(context=xc))
2343
2344 self.assertRaises(TypeError, D(1).adjusted, context=xc)
2345 self.assertRaises(TypeError, D(1).conjugate, context=xc)
2346 self.assertRaises(TypeError, D(1).radix, context=xc)
2347
2348 self.assertEqual(D(-111).logb(context=xc), 2)
2349 self.assertEqual(D(0).logical_invert(context=xc), 1)
2350 self.assertEqual(D('0.01').number_class(context=xc), '+Subnormal')
2351 self.assertEqual(D('0.21').to_eng_string(context=xc), '0.21')
2352
2353 self.assertEqual(D('11').logical_and(D('10'), context=xc), 0)
2354 self.assertEqual(D('11').logical_or(D('10'), context=xc), 1)
2355 self.assertEqual(D('01').logical_xor(D('10'), context=xc), 1)
2356 self.assertEqual(D('23').rotate(1, context=xc), 3)
2357 self.assertEqual(D('23').rotate(1, context=xc), 3)
2358 xc.clear_flags()
2359 self.assertRaises(Overflow,
2360 D('23').scaleb, 1, context=xc)
2361 self.assertTrue(xc.flags[Overflow])
2362 self.assertFalse(c.flags[Overflow])
2363 self.assertEqual(D('23').shift(-1, context=xc), 0)
2364
2365 self.assertRaises(TypeError, D.from_float, 1.1, context=xc)
2366 self.assertRaises(TypeError, D(0).as_tuple, context=xc)
2367
2368 if (self.decimal == C):
2369 self.assertRaises(TypeError, D(1).canonical, context=xc)
2370 self.assertEqual(D("-1").copy_abs(context=xc), 1)
2371 self.assertEqual(D("1").copy_negate(context=xc), -1)
2372 else:
2373 self.assertEqual(D(1).canonical(context=xc), 1)
2374 self.assertRaises(TypeError, D("-1").copy_abs, context=xc)
2375 self.assertRaises(TypeError, D("-1").copy_negate, context=xc)
2376
2321 class CPythonAPItests(PythonAPItests): 2377 class CPythonAPItests(PythonAPItests):
2322 decimal = C 2378 decimal = C
2323 class PyPythonAPItests(PythonAPItests): 2379 class PyPythonAPItests(PythonAPItests):
2324 decimal = P 2380 decimal = P
2325 2381
2326 class ContextAPItests(unittest.TestCase): 2382 class ContextAPItests(unittest.TestCase):
2327 2383
2328 def test_pickle(self): 2384 def test_pickle(self):
2329 if hasattr(C, 'setfailpoint'):
2330 random.seed(randseed)
2331 2385
2332 Context = self.decimal.Context 2386 Context = self.decimal.Context
2333 2387
2334 savedecimal = sys.modules['decimal'] 2388 savedecimal = sys.modules['decimal']
2335 2389
2336 # Round trip 2390 # Round trip
2337 sys.modules['decimal'] = self.decimal 2391 sys.modules['decimal'] = self.decimal
2338 c = Context() 2392 c = Context()
2339 e = pickle.loads(pickle.dumps(c)) 2393 e = pickle.loads(pickle.dumps(c))
2340 2394
2341 self.assertEqual(c.prec, e.prec) 2395 self.assertEqual(c.prec, e.prec)
2342 self.assertEqual(c.Emin, e.Emin) 2396 self.assertEqual(c.Emin, e.Emin)
2343 self.assertEqual(c.Emax, e.Emax) 2397 self.assertEqual(c.Emax, e.Emax)
2344 self.assertEqual(c.rounding, e.rounding) 2398 self.assertEqual(c.rounding, e.rounding)
2345 self.assertEqual(c.capitals, e.capitals) 2399 self.assertEqual(c.capitals, e.capitals)
2346 self.assertEqual(c.clamp, e.clamp) 2400 self.assertEqual(c.clamp, e.clamp)
2347 self.assertEqual(c.flags, e.flags) 2401 self.assertEqual(c.flags, e.flags)
2348 self.assertEqual(c.traps, e.traps) 2402 self.assertEqual(c.traps, e.traps)
2349 2403
2350 # Test interchangeability 2404 # Test interchangeability
2351 combinations = [(C, P), (P, C)] if C else [(P, P)] 2405 combinations = [(C, P), (P, C)] if C else [(P, P)]
2352 for dumper, loader in combinations: 2406 for dumper, loader in combinations:
2353 for ri, _ in enumerate(RoundingModes[dumper]): 2407 for ri, _ in enumerate(RoundingModes[dumper]):
2354 if hasattr(C, 'setfailpoint') and ri > 0: continue
2355 for fi, _ in enumerate(OrderedSignals[dumper]): 2408 for fi, _ in enumerate(OrderedSignals[dumper]):
2356 if hasattr(C, 'setfailpoint') and fi > 0: continue
2357 for ti, _ in enumerate(OrderedSignals[dumper]): 2409 for ti, _ in enumerate(OrderedSignals[dumper]):
2358 if hasattr(C, 'setfailpoint') and ti > 0: continue
2359 2410
2360 prec = random.randrange(1, 100) 2411 prec = random.randrange(1, 100)
2361 emin = random.randrange(-100, 0) 2412 emin = random.randrange(-100, 0)
2362 emax = random.randrange(1, 100) 2413 emax = random.randrange(1, 100)
2363 caps = random.randrange(2) 2414 caps = random.randrange(2)
2364 clamp = random.randrange(2) 2415 clamp = random.randrange(2)
2365 2416
2366 # One module dumps 2417 # One module dumps
2367 sys.modules['decimal'] = dumper 2418 sys.modules['decimal'] = dumper
2368 c = dumper.Context( 2419 c = dumper.Context(
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
2404 c = Context() 2455 c = Context()
2405 d = c.copy() 2456 d = c.copy()
2406 self.assertNotEqual(id(c), id(d)) 2457 self.assertNotEqual(id(c), id(d))
2407 self.assertNotEqual(id(c.flags), id(d.flags)) 2458 self.assertNotEqual(id(c.flags), id(d.flags))
2408 self.assertNotEqual(id(c.traps), id(d.traps)) 2459 self.assertNotEqual(id(c.traps), id(d.traps))
2409 k1 = set(c.flags.keys()) 2460 k1 = set(c.flags.keys())
2410 k2 = set(d.flags.keys()) 2461 k2 = set(d.flags.keys())
2411 self.assertEqual(k1, k2) 2462 self.assertEqual(k1, k2)
2412 self.assertEqual(c.flags, d.flags) 2463 self.assertEqual(c.flags, d.flags)
2413 2464
2465 def test__clamp(self):
2466 # In Python 3.2, the private attribute `_clamp` was made
2467 # public (issue 8540), with the old `_clamp` becoming a
2468 # property wrapping `clamp`. For the duration of Python 3.2
2469 # only, the attribute should be gettable/settable via both
2470 # `clamp` and `_clamp`; in Python 3.3, `_clamp` should be
2471 # removed.
2472 Context = self.decimal.Context
2473 c = Context()
2474 self.assertRaises(AttributeError, getattr, c, '_clamp')
2475
2414 def test_abs(self): 2476 def test_abs(self):
2415 Decimal = self.decimal.Decimal 2477 Decimal = self.decimal.Decimal
2416 Context = self.decimal.Context 2478 Context = self.decimal.Context
2417 2479
2418 c = Context() 2480 c = Context()
2419 d = c.abs(Decimal(-1)) 2481 d = c.abs(Decimal(-1))
2420 self.assertEqual(c.abs(-1), d) 2482 self.assertEqual(c.abs(-1), d)
2421 self.assertRaises(TypeError, c.abs, '-1') 2483 self.assertRaises(TypeError, c.abs, '-1')
2422 2484
2423 def test_add(self): 2485 def test_add(self):
(...skipping 450 matching lines...) Expand 10 before | Expand all | Expand 10 after
2874 Context = self.decimal.Context 2936 Context = self.decimal.Context
2875 2937
2876 c = Context() 2938 c = Context()
2877 d = c.power(Decimal(1), Decimal(4)) 2939 d = c.power(Decimal(1), Decimal(4))
2878 self.assertEqual(c.power(1, 4), d) 2940 self.assertEqual(c.power(1, 4), d)
2879 self.assertEqual(c.power(Decimal(1), 4), d) 2941 self.assertEqual(c.power(Decimal(1), 4), d)
2880 self.assertEqual(c.power(1, Decimal(4)), d) 2942 self.assertEqual(c.power(1, Decimal(4)), d)
2881 self.assertEqual(c.power(Decimal(1), Decimal(4)), d) 2943 self.assertEqual(c.power(Decimal(1), Decimal(4)), d)
2882 self.assertRaises(TypeError, c.power, '1', 4) 2944 self.assertRaises(TypeError, c.power, '1', 4)
2883 self.assertRaises(TypeError, c.power, 1, '4') 2945 self.assertRaises(TypeError, c.power, 1, '4')
2946 self.assertEqual(c.power(modulo=5, b=8, a=2), 1)
2884 2947
2885 def test_quantize(self): 2948 def test_quantize(self):
2886 Decimal = self.decimal.Decimal 2949 Decimal = self.decimal.Decimal
2887 Context = self.decimal.Context 2950 Context = self.decimal.Context
2888 2951
2889 c = Context() 2952 c = Context()
2890 d = c.quantize(Decimal(1), Decimal(2)) 2953 d = c.quantize(Decimal(1), Decimal(2))
2891 self.assertEqual(c.quantize(1, 2), d) 2954 self.assertEqual(c.quantize(1, 2), d)
2892 self.assertEqual(c.quantize(Decimal(1), 2), d) 2955 self.assertEqual(c.quantize(Decimal(1), 2), d)
2893 self.assertEqual(c.quantize(1, Decimal(2)), d) 2956 self.assertEqual(c.quantize(1, Decimal(2)), d)
(...skipping 260 matching lines...) Expand 10 before | Expand all | Expand 10 after
3154 with localcontext() as c4: 3217 with localcontext() as c4:
3155 self.assertEqual(c4.prec, 4) 3218 self.assertEqual(c4.prec, 4)
3156 del c4 3219 del c4
3157 3220
3158 class CContextWithStatement(ContextWithStatement): 3221 class CContextWithStatement(ContextWithStatement):
3159 decimal = C 3222 decimal = C
3160 class PyContextWithStatement(ContextWithStatement): 3223 class PyContextWithStatement(ContextWithStatement):
3161 decimal = P 3224 decimal = P
3162 3225
3163 class ContextFlags(unittest.TestCase): 3226 class ContextFlags(unittest.TestCase):
3227
3164 def test_flags_irrelevant(self): 3228 def test_flags_irrelevant(self):
3165 # check that the result (numeric result + flags raised) of an 3229 # check that the result (numeric result + flags raised) of an
3166 # arithmetic operation doesn't depend on the current flags 3230 # arithmetic operation doesn't depend on the current flags
3167 Decimal = self.decimal.Decimal 3231 Decimal = self.decimal.Decimal
3168 Context = self.decimal.Context 3232 Context = self.decimal.Context
3169 Inexact = self.decimal.Inexact 3233 Inexact = self.decimal.Inexact
3170 Rounded = self.decimal.Rounded 3234 Rounded = self.decimal.Rounded
3171 Underflow = self.decimal.Underflow 3235 Underflow = self.decimal.Underflow
3172 Clamped = self.decimal.Clamped 3236 Clamped = self.decimal.Clamped
3173 Subnormal = self.decimal.Subnormal 3237 Subnormal = self.decimal.Subnormal
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
3220 # flags we actually got 3284 # flags we actually got
3221 new_flags = [k for k,v in context.flags.items() if v] 3285 new_flags = [k for k,v in context.flags.items() if v]
3222 new_flags.sort(key=id) 3286 new_flags.sort(key=id)
3223 3287
3224 self.assertEqual(ans, new_ans, 3288 self.assertEqual(ans, new_ans,
3225 "operation produces different answers depending on flags set: " + 3289 "operation produces different answers depending on flags set: " +
3226 "expected %s, got %s." % (ans, new_ans)) 3290 "expected %s, got %s." % (ans, new_ans))
3227 self.assertEqual(new_flags, expected_flags, 3291 self.assertEqual(new_flags, expected_flags,
3228 "operation raises different flags depending on flags set: " + 3292 "operation raises different flags depending on flags set: " +
3229 "expected %s, got %s" % (expected_flags, new_f lags)) 3293 "expected %s, got %s" % (expected_flags, new_f lags))
3294
3295 def test_flag_comparisons(self):
3296 Context = self.decimal.Context
3297 Inexact = self.decimal.Inexact
3298 Rounded = self.decimal.Rounded
3299
3300 c = Context()
3301
3302 # Valid SignalDict
3303 self.assertNotEqual(c.flags, c.traps)
3304 self.assertNotEqual(c.traps, c.flags)
3305
3306 c.flags = c.traps
3307 self.assertEqual(c.flags, c.traps)
3308 self.assertEqual(c.traps, c.flags)
3309
3310 c.flags[Rounded] = True
3311 c.traps = c.flags
3312 self.assertEqual(c.flags, c.traps)
3313 self.assertEqual(c.traps, c.flags)
3314
3315 d = {}
3316 d.update(c.flags)
3317 self.assertEqual(d, c.flags)
3318 self.assertEqual(c.flags, d)
3319
3320 d[Inexact] = True
3321 self.assertNotEqual(d, c.flags)
3322 self.assertNotEqual(c.flags, d)
3323
3324 # Invalid SignalDict
3325 d = {Inexact:False}
3326 self.assertNotEqual(d, c.flags)
3327 self.assertNotEqual(c.flags, d)
3328
3329 d = ["xyz"]
3330 self.assertNotEqual(d, c.flags)
3331 self.assertNotEqual(c.flags, d)
3230 3332
3231 class CContextFlags(ContextFlags): 3333 class CContextFlags(ContextFlags):
3232 decimal = C 3334 decimal = C
3233 class PyContextFlags(ContextFlags): 3335 class PyContextFlags(ContextFlags):
3234 decimal = P 3336 decimal = P
3235 3337
3236 class SpecialContexts(unittest.TestCase): 3338 class SpecialContexts(unittest.TestCase):
3237 """Test the context templates.""" 3339 """Test the context templates."""
3238 3340
3239 def test_context_templates(self): 3341 def test_context_templates(self):
(...skipping 19 matching lines...) Expand all
3259 try: 3361 try:
3260 BasicContext.prec = ExtendedContext.prec = 441 3362 BasicContext.prec = ExtendedContext.prec = 441
3261 for template in BasicContext, ExtendedContext: 3363 for template in BasicContext, ExtendedContext:
3262 setcontext(template) 3364 setcontext(template)
3263 c = getcontext() 3365 c = getcontext()
3264 self.assertIsNot(c, template) 3366 self.assertIsNot(c, template)
3265 self.assertEqual(c.prec, 441) 3367 self.assertEqual(c.prec, 441)
3266 except Exception as e: 3368 except Exception as e:
3267 ex = e.__class__ 3369 ex = e.__class__
3268 finally: 3370 finally:
3269 with protectfail(): 3371 BasicContext.prec = basic_context_prec
3270 BasicContext.prec = basic_context_prec 3372 ExtendedContext.prec = extended_context_prec
3271 ExtendedContext.prec = extended_context_prec 3373 setcontext(savecontext)
3272 setcontext(savecontext)
3273 if ex: 3374 if ex:
3274 raise ex 3375 raise ex
3275 3376
3276 def test_default_context(self): 3377 def test_default_context(self):
3277 DefaultContext = self.decimal.DefaultContext 3378 DefaultContext = self.decimal.DefaultContext
3278 BasicContext = self.decimal.BasicContext 3379 BasicContext = self.decimal.BasicContext
3279 ExtendedContext = self.decimal.ExtendedContext 3380 ExtendedContext = self.decimal.ExtendedContext
3280 getcontext = self.decimal.getcontext 3381 getcontext = self.decimal.getcontext
3281 setcontext = self.decimal.setcontext 3382 setcontext = self.decimal.setcontext
3282 InvalidOperation = self.decimal.InvalidOperation 3383 InvalidOperation = self.decimal.InvalidOperation
(...skipping 19 matching lines...) Expand all
3302 c = getcontext() 3403 c = getcontext()
3303 self.assertEqual(c.prec, saveprec) 3404 self.assertEqual(c.prec, saveprec)
3304 3405
3305 setcontext(DefaultContext) 3406 setcontext(DefaultContext)
3306 c = getcontext() 3407 c = getcontext()
3307 self.assertIsNot(c, DefaultContext) 3408 self.assertIsNot(c, DefaultContext)
3308 self.assertEqual(c.prec, 961) 3409 self.assertEqual(c.prec, 961)
3309 except Exception as e: 3410 except Exception as e:
3310 ex = e.__class__ 3411 ex = e.__class__
3311 finally: 3412 finally:
3312 with protectfail(): 3413 DefaultContext.prec = default_context_prec
3313 DefaultContext.prec = default_context_prec 3414 setcontext(savecontext)
3314 setcontext(savecontext)
3315 if ex: 3415 if ex:
3316 raise ex 3416 raise ex
3317 3417
3318 class CSpecialContexts(SpecialContexts): 3418 class CSpecialContexts(SpecialContexts):
3319 decimal = C 3419 decimal = C
3320 class PySpecialContexts(SpecialContexts): 3420 class PySpecialContexts(SpecialContexts):
3321 decimal = P 3421 decimal = P
3322 3422
3323 class ContextInputValidation(unittest.TestCase): 3423 class ContextInputValidation(unittest.TestCase):
3324 3424
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
3361 for attr in ['capitals', 'clamp']: 3461 for attr in ['capitals', 'clamp']:
3362 self.assertRaises(ValueError, setattr, c, attr, -1) 3462 self.assertRaises(ValueError, setattr, c, attr, -1)
3363 self.assertRaises(ValueError, setattr, c, attr, 2) 3463 self.assertRaises(ValueError, setattr, c, attr, 2)
3364 self.assertRaises(TypeError, setattr, c, attr, [1,2,3]) 3464 self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
3365 3465
3366 # Invalid attribute 3466 # Invalid attribute
3367 self.assertRaises(AttributeError, setattr, c, 'emax', 100) 3467 self.assertRaises(AttributeError, setattr, c, 'emax', 100)
3368 3468
3369 # Invalid signal dict 3469 # Invalid signal dict
3370 self.assertRaises(TypeError, setattr, c, 'flags', []) 3470 self.assertRaises(TypeError, setattr, c, 'flags', [])
3371 self.assertRaises(TypeError, setattr, c, 'flags', {}) 3471 self.assertRaises(KeyError, setattr, c, 'flags', {})
3372 self.assertRaises(TypeError, setattr, c, 'traps', 3472 self.assertRaises(KeyError, setattr, c, 'traps',
3373 {'InvalidOperation':0}) 3473 {'InvalidOperation':0})
3374 3474
3375 # Attributes cannot be deleted 3475 # Attributes cannot be deleted
3376 for attr in ['prec', 'Emax', 'Emin', 'rounding', 'capitals', 'clamp', 3476 for attr in ['prec', 'Emax', 'Emin', 'rounding', 'capitals', 'clamp',
3377 'flags', 'traps']: 3477 'flags', 'traps']:
3378 self.assertRaises(AttributeError, c.__delattr__, attr) 3478 self.assertRaises(AttributeError, c.__delattr__, attr)
3379 3479
3380 # Invalid attributes 3480 # Invalid attributes
3381 self.assertRaises(TypeError, getattr, c, 9) 3481 self.assertRaises(TypeError, getattr, c, 9)
3382 self.assertRaises(TypeError, setattr, c, 9) 3482 self.assertRaises(TypeError, setattr, c, 9)
3383 3483
3384 # Invalid values in constructor 3484 # Invalid values in constructor
3385 self.assertRaises(TypeError, Context, rounding=999999) 3485 self.assertRaises(TypeError, Context, rounding=999999)
3386 self.assertRaises(TypeError, Context, rounding='xyz') 3486 self.assertRaises(TypeError, Context, rounding='xyz')
3387 self.assertRaises(ValueError, Context, clamp=2) 3487 self.assertRaises(ValueError, Context, clamp=2)
3388 self.assertRaises(ValueError, Context, capitals=-1) 3488 self.assertRaises(ValueError, Context, capitals=-1)
3389 self.assertRaises(TypeError, Context, flags=["P"]) 3489 self.assertRaises(KeyError, Context, flags=["P"])
3390 self.assertRaises(TypeError, Context, traps=["Q"]) 3490 self.assertRaises(KeyError, Context, traps=["Q"])
3391 3491
3392 # Type error in conversion 3492 # Type error in conversion
3393 self.assertRaises(TypeError, Context, flags=(0,1)) 3493 self.assertRaises(TypeError, Context, flags=(0,1))
3394 self.assertRaises(TypeError, Context, traps=(1,0)) 3494 self.assertRaises(TypeError, Context, traps=(1,0))
3395 3495
3396 class CContextInputValidation(ContextInputValidation): 3496 class CContextInputValidation(ContextInputValidation):
3397 decimal = C 3497 decimal = C
3398 class PyContextInputValidation(ContextInputValidation): 3498 class PyContextInputValidation(ContextInputValidation):
3399 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())
3400 3531
3401 class Coverage(unittest.TestCase): 3532 class Coverage(unittest.TestCase):
3402 3533
3403 def test_adjusted(self): 3534 def test_adjusted(self):
3404 Decimal = self.decimal.Decimal 3535 Decimal = self.decimal.Decimal
3405 3536
3406 self.assertEqual(Decimal('1234e9999').adjusted(), 10002) 3537 self.assertEqual(Decimal('1234e9999').adjusted(), 10002)
3407 # XXX raise? 3538 # XXX raise?
3408 self.assertEqual(Decimal('nan').adjusted(), 0) 3539 self.assertEqual(Decimal('nan').adjusted(), 0)
3409 self.assertEqual(Decimal('inf').adjusted(), 0) 3540 self.assertEqual(Decimal('inf').adjusted(), 0)
(...skipping 130 matching lines...) Expand 10 before | Expand all | Expand 10 after
3540 c.traps[InvalidOperation] = False 3671 c.traps[InvalidOperation] = False
3541 c.clear_flags() 3672 c.clear_flags()
3542 q, r = divmod(Decimal("inf"), Decimal("inf")) 3673 q, r = divmod(Decimal("inf"), Decimal("inf"))
3543 self.assertTrue(q.is_nan() and r.is_nan()) 3674 self.assertTrue(q.is_nan() and r.is_nan())
3544 self.assertTrue(c.flags[InvalidOperation]) 3675 self.assertTrue(c.flags[InvalidOperation])
3545 3676
3546 c.clear_flags() 3677 c.clear_flags()
3547 q, r = divmod(Decimal("inf"), 101) 3678 q, r = divmod(Decimal("inf"), 101)
3548 self.assertTrue(q.is_infinite() and r.is_nan()) 3679 self.assertTrue(q.is_infinite() and r.is_nan())
3549 self.assertTrue(c.flags[InvalidOperation]) 3680 self.assertTrue(c.flags[InvalidOperation])
3550 3681
3551 c.clear_flags() 3682 c.clear_flags()
3552 q, r = divmod(Decimal(0), 0) 3683 q, r = divmod(Decimal(0), 0)
3553 self.assertTrue(q.is_nan() and r.is_nan()) 3684 self.assertTrue(q.is_nan() and r.is_nan())
3554 self.assertTrue(c.flags[InvalidOperation]) 3685 self.assertTrue(c.flags[InvalidOperation])
3555 3686
3556 c.traps[DivisionByZero] = False 3687 c.traps[DivisionByZero] = False
3557 c.clear_flags() 3688 c.clear_flags()
3558 q, r = divmod(Decimal(11), 0) 3689 q, r = divmod(Decimal(11), 0)
3559 self.assertTrue(q.is_infinite() and r.is_nan()) 3690 self.assertTrue(q.is_infinite() and r.is_nan())
3560 self.assertTrue(c.flags[InvalidOperation] and 3691 self.assertTrue(c.flags[InvalidOperation] and
3561 c.flags[DivisionByZero]) 3692 c.flags[DivisionByZero])
3562 3693
3563 def test_power(self): 3694 def test_power(self):
3564 Decimal = self.decimal.Decimal 3695 Decimal = self.decimal.Decimal
3565 localcontext = self.decimal.localcontext 3696 localcontext = self.decimal.localcontext
(...skipping 27 matching lines...) Expand all
3593 x = Decimal(99).quantize(Decimal("1e1")) 3724 x = Decimal(99).quantize(Decimal("1e1"))
3594 self.assertTrue(x.is_nan()) 3725 self.assertTrue(x.is_nan())
3595 3726
3596 def test_radix(self): 3727 def test_radix(self):
3597 Decimal = self.decimal.Decimal 3728 Decimal = self.decimal.Decimal
3598 getcontext = self.decimal.getcontext 3729 getcontext = self.decimal.getcontext
3599 3730
3600 c = getcontext() 3731 c = getcontext()
3601 self.assertEqual(Decimal("1").radix(), 10) 3732 self.assertEqual(Decimal("1").radix(), 10)
3602 self.assertEqual(c.radix(), 10) 3733 self.assertEqual(c.radix(), 10)
3603 3734
3604 def test_rop(self): 3735 def test_rop(self):
3605 Decimal = self.decimal.Decimal 3736 Decimal = self.decimal.Decimal
3606 3737
3607 for attr in ('__radd__', '__rsub__', '__rmul__', '__rtruediv__', 3738 for attr in ('__radd__', '__rsub__', '__rmul__', '__rtruediv__',
3608 '__rdivmod__', '__rmod__', '__rfloordiv__', '__rpow__'): 3739 '__rdivmod__', '__rmod__', '__rfloordiv__', '__rpow__'):
3609 self.assertIs(getattr(Decimal("1"), attr)("xyz"), NotImplemented) 3740 self.assertIs(getattr(Decimal("1"), attr)("xyz"), NotImplemented)
3610 3741
3611 def test_round(self): 3742 def test_round(self):
3612 # Python3 behavior: round() returns Decimal 3743 # Python3 behavior: round() returns Decimal
3613 Decimal = self.decimal.Decimal 3744 Decimal = self.decimal.Decimal
(...skipping 213 matching lines...) Expand 10 before | Expand all | Expand 10 after
3827 def test_py__round(self): 3958 def test_py__round(self):
3828 # Coverage 3959 # Coverage
3829 Decimal = P.Decimal 3960 Decimal = P.Decimal
3830 ROUND_UP = P.ROUND_UP 3961 ROUND_UP = P.ROUND_UP
3831 3962
3832 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP) 3963 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP)
3833 3964
3834 class CFunctionality(unittest.TestCase): 3965 class CFunctionality(unittest.TestCase):
3835 """Extra functionality in _decimal""" 3966 """Extra functionality in _decimal"""
3836 3967
3968 @requires_extra_functionality
3837 def test_c_ieee_context(self): 3969 def test_c_ieee_context(self):
3838 # issue 8786: Add support for IEEE 754 contexts to decimal module. 3970 # issue 8786: Add support for IEEE 754 contexts to decimal module.
3839 IEEEContext = C.IEEEContext 3971 IEEEContext = C.IEEEContext
3840 DECIMAL32 = C.DECIMAL32 3972 DECIMAL32 = C.DECIMAL32
3841 DECIMAL64 = C.DECIMAL64 3973 DECIMAL64 = C.DECIMAL64
3842 DECIMAL128 = C.DECIMAL128 3974 DECIMAL128 = C.DECIMAL128
3843 3975
3844 def assert_rest(self, context): 3976 def assert_rest(self, context):
3845 self.assertEqual(context.clamp, 1) 3977 self.assertEqual(context.clamp, 1)
3846 assert_signals(self, context, 'traps', []) 3978 assert_signals(self, context, 'traps', [])
(...skipping 14 matching lines...) Expand all
3861 c = IEEEContext(DECIMAL128) 3993 c = IEEEContext(DECIMAL128)
3862 self.assertEqual(c.prec, 34) 3994 self.assertEqual(c.prec, 34)
3863 self.assertEqual(c.Emax, 6144) 3995 self.assertEqual(c.Emax, 6144)
3864 self.assertEqual(c.Emin, -6143) 3996 self.assertEqual(c.Emin, -6143)
3865 assert_rest(self, c) 3997 assert_rest(self, c)
3866 3998
3867 # Invalid values 3999 # Invalid values
3868 self.assertRaises(OverflowError, IEEEContext, 2**63) 4000 self.assertRaises(OverflowError, IEEEContext, 2**63)
3869 self.assertRaises(ValueError, IEEEContext, -1) 4001 self.assertRaises(ValueError, IEEEContext, -1)
3870 self.assertRaises(ValueError, IEEEContext, 1024) 4002 self.assertRaises(ValueError, IEEEContext, 1024)
3871
3872 def test_apply(self):
3873 # Decimal("9.9999999").apply() applies the current context.
3874 Decimal = C.Decimal
3875 localcontext = C.localcontext
3876
3877 with localcontext() as c:
3878 c.prec = 5
3879 c.Emax = 99999
3880 c.Emin = -99999
3881
3882 d = c.copy()
3883 d.prec = 4
3884
3885 x = Decimal("123456")
3886 self.assertEqual(str(x.apply()), "1.2346E+5")
3887 self.assertEqual(str(c.apply(x)), "1.2346E+5")
3888
3889 self.assertEqual(str(x.apply(d)), "1.235E+5")
3890 self.assertEqual(str(d.apply(x)), "1.235E+5")
3891
3892 self.assertRaises(TypeError, x.apply, "p")
3893 self.assertRaises(TypeError, x.apply, "p", "q")
3894 self.assertRaises(TypeError, c.apply, "p")
3895
3896 x = Decimal(1171**2221)
3897 self.assertEqual(str(x.apply()), "1.8402E+6815")
3898 self.assertEqual(str(c.apply(x)), "1.8402E+6815")
3899 self.assertEqual(str(d.apply(x)), "1.840E+6815")
3900 4003
3901 @requires_IEEE_754 4004 @requires_IEEE_754
3902 def test_c_float_operation(self): 4005 def test_c_float_operation(self):
3903 Decimal = C.Decimal 4006 Decimal = C.Decimal
3904 FloatOperation= C.FloatOperation 4007 FloatOperation= C.FloatOperation
3905 localcontext = C.localcontext 4008 localcontext = C.localcontext
3906 4009
3907 with localcontext() as c: 4010 with localcontext() as c:
3908 c.clear_flags() 4011 c.clear_flags()
3909 self.assertEqual(Decimal(7.5), 7.5) 4012 self.assertEqual(Decimal(7.5), 7.5)
(...skipping 104 matching lines...) Expand 10 before | Expand all | Expand 10 after
4014 test_containers(c, sig) 4117 test_containers(c, sig)
4015 4118
4016 c.traps[FloatOperation] = True 4119 c.traps[FloatOperation] = True
4017 doit(c, signal=FloatOperation) 4120 doit(c, signal=FloatOperation)
4018 test_containers(c, FloatOperation) 4121 test_containers(c, FloatOperation)
4019 4122
4020 def test_c_float_operation_default(self): 4123 def test_c_float_operation_default(self):
4021 Decimal = C.Decimal 4124 Decimal = C.Decimal
4022 Context = C.Context 4125 Context = C.Context
4023 Inexact = C.Inexact 4126 Inexact = C.Inexact
4024 DecInexact = C.DecInexact
4025 FloatOperation= C.FloatOperation 4127 FloatOperation= C.FloatOperation
4026 DecFloatOperation= C.DecFloatOperation
4027 4128
4028 context = Context() 4129 context = Context()
4029 self.assertFalse(context.flags[FloatOperation]) 4130 self.assertFalse(context.flags[FloatOperation])
4030 self.assertFalse(context.traps[FloatOperation]) 4131 self.assertFalse(context.traps[FloatOperation])
4031 self.assertFalse(context._flags&DecFloatOperation) 4132
4032 self.assertFalse(context._traps&DecFloatOperation) 4133 context.clear_traps()
4033 4134 context.traps[Inexact] = True
4034 context.settraps([Inexact, FloatOperation]) 4135 context.traps[FloatOperation] = True
4035 self.assertEqual(context._traps, DecInexact|DecFloatOperation)
4036 self.assertTrue(context.traps[FloatOperation]) 4136 self.assertTrue(context.traps[FloatOperation])
4037 self.assertTrue(context.traps[Inexact]) 4137 self.assertTrue(context.traps[Inexact])
4038 4138
4039 def test_c_powmod(self): 4139 @requires_extra_functionality
4040 Decimal = C.Decimal
4041 Context = C.Context
4042
4043 c = Context()
4044 d = c.powmod(Decimal(1), Decimal(4), Decimal(2))
4045 self.assertEqual(c.powmod(1, 4, 2), d)
4046 self.assertEqual(c.powmod(Decimal(1), 4, 2), d)
4047 self.assertEqual(c.powmod(1, Decimal(4), 2), d)
4048 self.assertEqual(c.powmod(1, 4, Decimal(2)), d)
4049 self.assertEqual(c.powmod(Decimal(1), Decimal(4), 2), d)
4050 self.assertRaises(TypeError, c.powmod, '1', 4, 2)
4051 self.assertRaises(TypeError, c.powmod, 1, '4', 2)
4052 self.assertRaises(TypeError, c.powmod, 1, 4, '2')
4053
4054 def test_c_context(self): 4140 def test_c_context(self):
4055 Context = C.Context 4141 Context = C.Context
4056 4142
4057 c = Context(flags=C.DecClamped, traps=C.DecRounded) 4143 c = Context(flags=C.DecClamped, traps=C.DecRounded)
4058 self.assertEqual(c._flags, C.DecClamped) 4144 self.assertEqual(c._flags, C.DecClamped)
4059 self.assertEqual(c._traps, C.DecRounded) 4145 self.assertEqual(c._traps, C.DecRounded)
4060 4146
4061 def test_sundry(self): 4147 @requires_extra_functionality
4062 Decimal = C.Decimal
4063
4064 # mpd_isinteger
4065 self.assertTrue(Decimal("1.234e5").is_integer())
4066 self.assertTrue(Decimal("snan").is_special())
4067
4068 # Extra functions
4069 self.assertEqual(Decimal(-1).abs(), 1)
4070 self.assertEqual(Decimal(1).minus(), -1)
4071 self.assertEqual(Decimal(1).plus(), 1)
4072 self.assertEqual(Decimal(1).add(1), 2)
4073 self.assertEqual(Decimal(12).div(2), 6)
4074 self.assertEqual(Decimal(10).divint(7), 1)
4075 self.assertEqual(Decimal(10).mul(12), 120)
4076 self.assertEqual(Decimal(10).rem(7), 3)
4077 self.assertEqual(Decimal(10).sub(7), 3)
4078 self.assertEqual(Decimal(10).divmod(7), (1, 3))
4079
4080 def test_constants(self): 4148 def test_constants(self):
4081 # Condition flags 4149 # Condition flags
4082 cond = ( 4150 cond = (
4083 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero, 4151 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero,
4084 C.DecDivisionImpossible, C.DecDivisionUndefined, 4152 C.DecDivisionImpossible, C.DecDivisionUndefined,
4085 C.DecFpuError, C.DecInexact, C.DecInvalidContext, 4153 C.DecFpuError, C.DecInexact, C.DecInvalidContext,
4086 C.DecInvalidOperation, C.DecMallocError, 4154 C.DecInvalidOperation, C.DecMallocError,
4087 C.DecFloatOperation, C.DecOverflow, C.DecRounded, 4155 C.DecFloatOperation, C.DecOverflow, C.DecRounded,
4088 C.DecSubnormal, C.DecUnderflow 4156 C.DecSubnormal, C.DecUnderflow
4089 ) 4157 )
4090 4158
4091 # Architecture dependent context limits 4159 # IEEEContext
4092 if C.MAX_EMAX > 425000000:
4093 self.assertEqual(C.MAX_PREC, 999999999999999999)
4094 self.assertEqual(C.MAX_EMAX, 999999999999999999)
4095 self.assertEqual(C.MIN_EMIN, -999999999999999999)
4096 self.assertEqual(C.MIN_ETINY, -1999999999999999997)
4097 else:
4098 self.assertEqual(C.MAX_PREC, 425000000)
4099 self.assertEqual(C.MAX_EMAX, 425000000)
4100 self.assertEqual(C.MIN_EMIN, -425000000)
4101 self.assertEqual(C.MIN_ETINY, -849999999)
4102
4103 » # IEEEContext
4104 self.assertEqual(C.DECIMAL32, 32) 4160 self.assertEqual(C.DECIMAL32, 32)
4105 self.assertEqual(C.DECIMAL64, 64) 4161 self.assertEqual(C.DECIMAL64, 64)
4106 self.assertEqual(C.DECIMAL128, 128) 4162 self.assertEqual(C.DECIMAL128, 128)
4107 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512) 4163 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512)
4108 4164
4109 # Rounding modes 4165 # Rounding modes
4110 for i, v in enumerate(RoundingModes[C]): 4166 for i, v in enumerate(RoundingModes[C]):
4111 self.assertEqual(v, i) 4167 self.assertEqual(v, i)
4112 self.assertEqual(C.ROUND_TRUNC, 8) 4168 self.assertEqual(C.ROUND_TRUNC, 8)
4113 4169
(...skipping 15 matching lines...) Expand all
4129 C.DecDivisionByZero) 4185 C.DecDivisionByZero)
4130 4186
4131 self.assertEqual(C.DecTraps, 4187 self.assertEqual(C.DecTraps,
4132 C.DecErrors|C.DecOverflow|C.DecUnderflow) 4188 C.DecErrors|C.DecOverflow|C.DecUnderflow)
4133 4189
4134 class CWhitebox(unittest.TestCase): 4190 class CWhitebox(unittest.TestCase):
4135 """Whitebox testing for _decimal""" 4191 """Whitebox testing for _decimal"""
4136 4192
4137 def test_bignum(self): 4193 def test_bignum(self):
4138 # Not exactly whitebox, but too slow with pydecimal. 4194 # Not exactly whitebox, but too slow with pydecimal.
4139 if hasattr(C, 'setfailpoint'):
4140 random.seed(randseed)
4141 4195
4142 Decimal = C.Decimal 4196 Decimal = C.Decimal
4143 localcontext = C.localcontext 4197 localcontext = C.localcontext
4144 4198
4145 b1 = 10**35 4199 b1 = 10**35
4146 b2 = 10**36 4200 b2 = 10**36
4147 with localcontext() as c: 4201 with localcontext() as c:
4148 c.prec = 1000000 4202 c.prec = 1000000
4149 r = 1 if hasattr(C, 'setfailpoint') else 5 4203 for i in range(5):
4150 for i in range(r):
4151 a = random.randrange(b1, b2) 4204 a = random.randrange(b1, b2)
4152 b = random.randrange(1000, 1200) 4205 b = random.randrange(1000, 1200)
4153 x = a ** b 4206 x = a ** b
4154 y = Decimal(a) ** Decimal(b) 4207 y = Decimal(a) ** Decimal(b)
4155 self.assertEqual(x, y) 4208 self.assertEqual(x, y)
4209
4210 def test_invalid_construction(self):
4211 self.assertRaises(TypeError, C.Decimal, 9, "xyz")
4156 4212
4157 def test_c_input_restriction(self): 4213 def test_c_input_restriction(self):
4158 # Too large for _decimal to be converted exactly 4214 # Too large for _decimal to be converted exactly
4159 Decimal = C.Decimal 4215 Decimal = C.Decimal
4160 InvalidOperation = C.InvalidOperation 4216 InvalidOperation = C.InvalidOperation
4161 Context = C.Context 4217 Context = C.Context
4162 localcontext = C.localcontext 4218 localcontext = C.localcontext
4163 4219
4164 with localcontext(Context()): 4220 with localcontext(Context()):
4165 self.assertRaises(InvalidOperation, Decimal, 4221 self.assertRaises(InvalidOperation, Decimal,
(...skipping 26 matching lines...) Expand all
4192 "flags=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \ 4248 "flags=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \
4193 "FloatOperation, Overflow, Rounded, Subnormal, Underflow], " \ 4249 "FloatOperation, Overflow, Rounded, Subnormal, Underflow], " \
4194 "traps=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \ 4250 "traps=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \
4195 "FloatOperation, Overflow, Rounded, Subnormal, Underflow])" 4251 "FloatOperation, Overflow, Rounded, Subnormal, Underflow])"
4196 self.assertEqual(s, t) 4252 self.assertEqual(s, t)
4197 4253
4198 def test_c_context_errors(self): 4254 def test_c_context_errors(self):
4199 Context = C.Context 4255 Context = C.Context
4200 InvalidOperation = C.InvalidOperation 4256 InvalidOperation = C.InvalidOperation
4201 Overflow = C.Overflow 4257 Overflow = C.Overflow
4258 localcontext = C.localcontext
4259 getcontext = C.getcontext
4260 setcontext = C.setcontext
4202 HAVE_CONFIG_64 = (C.MAX_PREC > 425000000) 4261 HAVE_CONFIG_64 = (C.MAX_PREC > 425000000)
4203 4262
4204 c = Context() 4263 c = Context()
4205 4264
4206 # SignalDict: input validation 4265 # SignalDict: input validation
4207 self.assertRaises(TypeError, c.flags.__setitem__, 801, 0) 4266 self.assertRaises(KeyError, c.flags.__setitem__, 801, 0)
4208 self.assertRaises(TypeError, c.traps.__setitem__, 801, 0) 4267 self.assertRaises(KeyError, c.traps.__setitem__, 801, 0)
4209 self.assertRaises(ValueError, c.flags.__delitem__, Overflow) 4268 self.assertRaises(ValueError, c.flags.__delitem__, Overflow)
4210 self.assertRaises(ValueError, c.traps.__delitem__, InvalidOperation) 4269 self.assertRaises(ValueError, c.traps.__delitem__, InvalidOperation)
4211 self.assertRaises(TypeError, setattr, c, 'flags', ['x']) 4270 self.assertRaises(TypeError, setattr, c, 'flags', ['x'])
4212 self.assertRaises(TypeError, setattr, c,'traps', ['y']) 4271 self.assertRaises(TypeError, setattr, c,'traps', ['y'])
4213 self.assertRaises(TypeError, setattr, c, 'flags', {0:1}) 4272 self.assertRaises(KeyError, setattr, c, 'flags', {0:1})
4214 self.assertRaises(TypeError, setattr, c, 'traps', {0:1}) 4273 self.assertRaises(KeyError, setattr, c, 'traps', {0:1})
4215
4216 self.assertRaises(TypeError, c.setflags, ['x'])
4217 self.assertRaises(TypeError, c.settraps, ['y'])
4218 self.assertRaises(TypeError, c.setflags, 'x')
4219 self.assertRaises(TypeError, c.settraps, 'y')
4220 4274
4221 # Input corner cases 4275 # Input corner cases
4222 int_max = 2**63-1 if HAVE_CONFIG_64 else 2**31-1 4276 int_max = 2**63-1 if HAVE_CONFIG_64 else 2**31-1
4223 gt_max_emax = 10**18 if HAVE_CONFIG_64 else 10**9 4277 gt_max_emax = 10**18 if HAVE_CONFIG_64 else 10**9
4224 4278
4225 # prec, Emax, Emin 4279 # prec, Emax, Emin
4226 for attr in ['prec', 'Emax']: 4280 for attr in ['prec', 'Emax']:
4227 self.assertRaises(ValueError, setattr, c, attr, gt_max_emax) 4281 self.assertRaises(ValueError, setattr, c, attr, gt_max_emax)
4228 self.assertRaises(ValueError, setattr, c, 'Emin', -gt_max_emax) 4282 self.assertRaises(ValueError, setattr, c, 'Emin', -gt_max_emax)
4229 4283
4230 # prec, Emax, Emin in context constructor 4284 # prec, Emax, Emin in context constructor
4231 self.assertRaises(ValueError, Context, prec=gt_max_emax) 4285 self.assertRaises(ValueError, Context, prec=gt_max_emax)
4232 self.assertRaises(ValueError, Context, Emax=gt_max_emax) 4286 self.assertRaises(ValueError, Context, Emax=gt_max_emax)
4233 self.assertRaises(ValueError, Context, Emin=-gt_max_emax) 4287 self.assertRaises(ValueError, Context, Emin=-gt_max_emax)
4234 4288
4235 # Overflow in conversion 4289 # Overflow in conversion
4236 self.assertRaises(OverflowError, Context, prec=int_max+1) 4290 self.assertRaises(OverflowError, Context, prec=int_max+1)
4237 self.assertRaises(OverflowError, Context, Emax=int_max+1) 4291 self.assertRaises(OverflowError, Context, Emax=int_max+1)
4238 self.assertRaises(OverflowError, Context, Emin=-int_max-2) 4292 self.assertRaises(OverflowError, Context, Emin=-int_max-2)
4239 self.assertRaises(OverflowError, Context, rounding=int_max+1) 4293 self.assertRaises(OverflowError, Context, rounding=int_max+1)
4240 self.assertRaises(OverflowError, Context, clamp=int_max+1) 4294 self.assertRaises(OverflowError, Context, clamp=int_max+1)
4241 self.assertRaises(OverflowError, Context, capitals=int_max+1) 4295 self.assertRaises(OverflowError, Context, capitals=int_max+1)
4242 self.assertRaises(OverflowError, Context, _allcr=int_max+1) 4296 self.assertRaises(OverflowError, Context, _allcr=int_max+1)
4243 4297
4244 # OverflowError, general ValueError 4298 # OverflowError, general ValueError
4245 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp', '_allcr'): 4299 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp'):
4246 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4300 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4247 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4301 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4248 if sys.platform != 'win32': 4302 if sys.platform != 'win32':
4249 self.assertRaises(ValueError, setattr, c, attr, int_max) 4303 self.assertRaises(ValueError, setattr, c, attr, int_max)
4250 self.assertRaises(ValueError, setattr, c, attr, -int_max-1) 4304 self.assertRaises(ValueError, setattr, c, attr, -int_max-1)
4251 4305
4252 # OverflowError, general TypeError 4306 # OverflowError, general TypeError
4253 for attr in ('rounding', '_flags', '_traps'): 4307 for attr in ('rounding',):
4254 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4308 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4255 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4309 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4256 if sys.platform != 'win32': 4310 if sys.platform != 'win32':
4257 self.assertRaises(TypeError, setattr, c, attr, int_max) 4311 self.assertRaises(TypeError, setattr, c, attr, int_max)
4258 self.assertRaises(TypeError, setattr, c, attr, -int_max-1) 4312 self.assertRaises(TypeError, setattr, c, attr, -int_max-1)
4259 4313
4260 # OverflowError: unsafe_prec, unsafe_emin, unsafe_emax 4314 # OverflowError: _unsafe_setprec, _unsafe_setemin, _unsafe_setemax
4261 self.assertRaises(OverflowError, getattr(c, 'unsafe_setprec'), int_max+1 ) 4315 if C.MAX_PREC == 425000000:
4262 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemax'), int_max+1 ) 4316 self.assertRaises(OverflowError, getattr(c, '_unsafe_setprec'),
4263 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemin'), -int_max- 2) 4317 int_max+1)
4264 4318 self.assertRaises(OverflowError, getattr(c, '_unsafe_setemax'),
4265 # capitals, clamp, _allcr 4319 int_max+1)
4266 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']:
4267 self.assertRaises(ValueError, setattr, c, attr, -1) 4337 self.assertRaises(ValueError, setattr, c, attr, -1)
4268 self.assertRaises(ValueError, setattr, c, attr, 2) 4338 self.assertRaises(ValueError, setattr, c, attr, 2)
4269 self.assertRaises(TypeError, setattr, c, attr, [1,2,3]) 4339 self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
4270 if HAVE_CONFIG_64: 4340 if HAVE_CONFIG_64:
4271 self.assertRaises(ValueError, setattr, c, attr, 2**32) 4341 self.assertRaises(ValueError, setattr, c, attr, 2**32)
4272 self.assertRaises(ValueError, setattr, c, attr, 2**32+1) 4342 self.assertRaises(ValueError, setattr, c, attr, 2**32+1)
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)
4273 4390
4274 self.assertRaises(ValueError, Context, _allcr=2) 4391 self.assertRaises(ValueError, Context, _allcr=2)
4275 4392
4276 # _flags, _traps 4393 # _flags, _traps
4277 for attr in ['_flags', '_traps']: 4394 for attr in ['_flags', '_traps']:
4278 self.assertRaises(TypeError, setattr, c, attr, 999999) 4395 self.assertRaises(TypeError, setattr, c, attr, 999999)
4279 self.assertRaises(TypeError, setattr, c, attr, 'x') 4396 self.assertRaises(TypeError, setattr, c, attr, 'x')
4280 4397
4281 def test_c_valid_context(self): 4398 def test_c_valid_context(self):
4282 # These tests are for code coverage in _decimal. 4399 # These tests are for code coverage in _decimal.
4283 DefaultContext = C.DefaultContext 4400 DefaultContext = C.DefaultContext
4284 ROUND_HALF_UP = C.ROUND_HALF_UP 4401 ROUND_HALF_UP = C.ROUND_HALF_UP
4285 Clamped = C.Clamped 4402 Clamped = C.Clamped
4286 Underflow = C.Underflow 4403 Underflow = C.Underflow
4287 Inexact = C.Inexact 4404 Inexact = C.Inexact
4288 Rounded = C.Rounded 4405 Rounded = C.Rounded
4289 Subnormal = C.Subnormal 4406 Subnormal = C.Subnormal
4290 DecClamped = C.DecClamped
4291 DecUnderflow = C.DecUnderflow
4292 DecInexact = C.DecInexact
4293 DecRounded = C.DecRounded
4294 DecSubnormal = C.DecSubnormal
4295 4407
4296 c = DefaultContext.copy() 4408 c = DefaultContext.copy()
4297 4409
4298 # Exercise all getters and setters 4410 # Exercise all getters and setters
4299 c.prec = 34 4411 c.prec = 34
4300 c.rounding = ROUND_HALF_UP 4412 c.rounding = ROUND_HALF_UP
4301 c.Emax = 3000 4413 c.Emax = 3000
4302 c.Emin = -3000 4414 c.Emin = -3000
4303 c.capitals = 1 4415 c.capitals = 1
4304 c.clamp = 0 4416 c.clamp = 0
4305 c._flags = DecUnderflow
4306 c._traps = DecClamped
4307 c._allcr = 0
4308 4417
4309 self.assertEqual(c.prec, 34) 4418 self.assertEqual(c.prec, 34)
4310 self.assertEqual(c.rounding, ROUND_HALF_UP) 4419 self.assertEqual(c.rounding, ROUND_HALF_UP)
4311 self.assertEqual(c.Emin, -3000) 4420 self.assertEqual(c.Emin, -3000)
4312 self.assertEqual(c.Emax, 3000) 4421 self.assertEqual(c.Emax, 3000)
4313 self.assertEqual(c.capitals, 1) 4422 self.assertEqual(c.capitals, 1)
4314 self.assertEqual(c.clamp, 0) 4423 self.assertEqual(c.clamp, 0)
4315 self.assertEqual(c._flags, DecUnderflow)
4316 self.assertEqual(c._traps, DecClamped)
4317 self.assertEqual(c._allcr, 0)
4318 4424
4319 self.assertEqual(c.Etiny(), -3033) 4425 self.assertEqual(c.Etiny(), -3033)
4320 self.assertEqual(c.Etop(), 2967) 4426 self.assertEqual(c.Etop(), 2967)
4321 4427
4322 # Set traps/flags from list
4323 c.settraps([Clamped, Underflow])
4324 self.assertEqual(c._traps, DecClamped|DecUnderflow)
4325
4326 c.setflags([Inexact, Rounded, Subnormal])
4327 self.assertEqual(c._flags, DecInexact|DecRounded|DecSubnormal)
4328
4329 # Exercise all unsafe setters 4428 # Exercise all unsafe setters
4330 c.unsafe_setprec(999999999) 4429 if C.MAX_PREC == 425000000:
4331 c.unsafe_setemax(999999999) 4430 c._unsafe_setprec(999999999)
4332 c.unsafe_setemin(-999999999) 4431 c._unsafe_setemax(999999999)
4333 4432 c._unsafe_setemin(-999999999)
4334 self.assertEqual(c.prec, 999999999) 4433 self.assertEqual(c.prec, 999999999)
4335 self.assertEqual(c.Emax, 999999999) 4434 self.assertEqual(c.Emax, 999999999)
4336 self.assertEqual(c.Emin, -999999999) 4435 self.assertEqual(c.Emin, -999999999)
4337 4436
4338 def test_c_round(self): 4437 def test_c_round(self):
4339 # Restricted input. 4438 # Restricted input.
4340 Decimal = C.Decimal 4439 Decimal = C.Decimal
4341 InvalidOperation = C.InvalidOperation 4440 InvalidOperation = C.InvalidOperation
4342 localcontext = C.localcontext 4441 localcontext = C.localcontext
4343 MAX_EMAX = C.MAX_EMAX 4442 MAX_EMAX = C.MAX_EMAX
4344 MIN_ETINY = C.MIN_ETINY 4443 MIN_ETINY = C.MIN_ETINY
4345 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
4346 4445
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
4413 4512
4414 def test_c_funcs(self): 4513 def test_c_funcs(self):
4415 # Invalid arguments 4514 # Invalid arguments
4416 Decimal = C.Decimal 4515 Decimal = C.Decimal
4417 InvalidOperation = C.InvalidOperation 4516 InvalidOperation = C.InvalidOperation
4418 DivisionByZero = C.DivisionByZero 4517 DivisionByZero = C.DivisionByZero
4419 ROUND_UP = C.ROUND_UP 4518 ROUND_UP = C.ROUND_UP
4420 getcontext = C.getcontext 4519 getcontext = C.getcontext
4421 localcontext = C.localcontext 4520 localcontext = C.localcontext
4422 4521
4423 self.assertEqual(Decimal('9.99e10').to_sci_string(), '9.99E+10')
4424 self.assertEqual(Decimal('9.99e10').to_eng_string(), '99.9E+9') 4522 self.assertEqual(Decimal('9.99e10').to_eng_string(), '99.9E+9')
4425 4523
4426 self.assertRaises(TypeError, pow, Decimal(1), 2, "3") 4524 self.assertRaises(TypeError, pow, Decimal(1), 2, "3")
4427 self.assertRaises(TypeError, Decimal(9).number_class, "x", "y") 4525 self.assertRaises(TypeError, Decimal(9).number_class, "x", "y")
4428 self.assertRaises(TypeError, Decimal(9).divmod, 8, "x", "y")
4429 self.assertRaises(TypeError, Decimal(9).same_quantum, 3, "x", "y") 4526 self.assertRaises(TypeError, Decimal(9).same_quantum, 3, "x", "y")
4430 self.assertRaises(TypeError, Decimal(9).to_sci, 3, "x", "y")
4431 self.assertRaises(TypeError, Decimal(9).to_eng, 3, "x", "y")
4432
4433 self.assertEqual(Decimal("1.234e2007").sign(), 1)
4434 self.assertEqual(Decimal("-1.234e2007").sign(), -1)
4435 4527
4436 self.assertRaises( 4528 self.assertRaises(
4437 TypeError, 4529 TypeError,
4438 Decimal("1.23456789").quantize, Decimal('1e-100000'), [] 4530 Decimal("1.23456789").quantize, Decimal('1e-100000'), []
4439 ) 4531 )
4440 self.assertRaises( 4532 self.assertRaises(
4441 TypeError, 4533 TypeError,
4442 Decimal("1.23456789").quantize, Decimal('1e-100000'), getcontext() 4534 Decimal("1.23456789").quantize, Decimal('1e-100000'), getcontext()
4443 ) 4535 )
4444 self.assertRaises( 4536 self.assertRaises(
(...skipping 13 matching lines...) Expand all
4458 self.assertRaises(TypeError, c.canonical, 200) 4550 self.assertRaises(TypeError, c.canonical, 200)
4459 self.assertRaises(TypeError, c.is_canonical, 200) 4551 self.assertRaises(TypeError, c.is_canonical, 200)
4460 self.assertRaises(TypeError, c.divmod, 9, 8, "x", "y") 4552 self.assertRaises(TypeError, c.divmod, 9, 8, "x", "y")
4461 self.assertRaises(TypeError, c.same_quantum, 9, 3, "x", "y") 4553 self.assertRaises(TypeError, c.same_quantum, 9, 3, "x", "y")
4462 4554
4463 self.assertEqual(str(c.canonical(Decimal(200))), '200') 4555 self.assertEqual(str(c.canonical(Decimal(200))), '200')
4464 self.assertEqual(c.radix(), 10) 4556 self.assertEqual(c.radix(), 10)
4465 4557
4466 c.traps[DivisionByZero] = True 4558 c.traps[DivisionByZero] = True
4467 self.assertRaises(DivisionByZero, Decimal(9).__divmod__, 0) 4559 self.assertRaises(DivisionByZero, Decimal(9).__divmod__, 0)
4468 self.assertRaises(DivisionByZero, Decimal(9).divmod, 0)
4469 self.assertRaises(DivisionByZero, c.divmod, 9, 0) 4560 self.assertRaises(DivisionByZero, c.divmod, 9, 0)
4470 self.assertTrue(c.flags[InvalidOperation]) 4561 self.assertTrue(c.flags[InvalidOperation])
4471 4562
4472 c.clear_flags() 4563 c.clear_flags()
4473 c.traps[InvalidOperation] = True 4564 c.traps[InvalidOperation] = True
4474 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0) 4565 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0)
4475 self.assertRaises(InvalidOperation, Decimal(9).divmod, 0)
4476 self.assertRaises(InvalidOperation, c.divmod, 9, 0) 4566 self.assertRaises(InvalidOperation, c.divmod, 9, 0)
4477 self.assertTrue(c.flags[DivisionByZero]) 4567 self.assertTrue(c.flags[DivisionByZero])
4478 4568
4479 c.traps[InvalidOperation] = True 4569 c.traps[InvalidOperation] = True
4480 c.prec = 2 4570 c.prec = 2
4481 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501) 4571 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501)
4482 4572
4483 c.prec = 10 4573 @requires_extra_functionality
4484 x = Decimal(2).invroot()
4485 self.assertEqual(str(x), '0.7071067812')
4486
4487 x = c.invroot(3)
4488 self.assertEqual(str(x), '0.5773502692')
4489
4490 c.prec = 28
4491 x = Decimal(2).power(8)
4492 self.assertEqual(str(x), '256')
4493
4494 x = Decimal(2).powmod(8, 31)
4495 self.assertEqual(str(x), '8')
4496
4497 def test_c_context_templates(self): 4574 def test_c_context_templates(self):
4498 self.assertEqual( 4575 self.assertEqual(
4499 C.BasicContext._traps, 4576 C.BasicContext._traps,
4500 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow| 4577 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow|
4501 C.DecUnderflow|C.DecClamped 4578 C.DecUnderflow|C.DecClamped
4502 ) 4579 )
4503 self.assertEqual( 4580 self.assertEqual(
4504 C.DefaultContext._traps, 4581 C.DefaultContext._traps,
4505 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow 4582 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow
4506 ) 4583 )
4507 4584
4585 @requires_extra_functionality
4508 def test_c_signal_dict(self): 4586 def test_c_signal_dict(self):
4509 if hasattr(C, 'setfailpoint'):
4510 random.seed(randseed)
4511 4587
4512 # SignalDict coverage 4588 # SignalDict coverage
4513 Context = C.Context 4589 Context = C.Context
4514 DefaultContext = C.DefaultContext 4590 DefaultContext = C.DefaultContext
4515 4591
4516 InvalidOperation = C.InvalidOperation 4592 InvalidOperation = C.InvalidOperation
4517 DivisionByZero = C.DivisionByZero 4593 DivisionByZero = C.DivisionByZero
4518 Overflow = C.Overflow 4594 Overflow = C.Overflow
4519 Subnormal = C.Subnormal 4595 Subnormal = C.Subnormal
4520 Underflow = C.Underflow 4596 Underflow = C.Underflow
4521 Rounded = C.Rounded 4597 Rounded = C.Rounded
4522 Inexact = C.Inexact 4598 Inexact = C.Inexact
4523 Clamped = C.Clamped 4599 Clamped = C.Clamped
4524 4600
4525 DecClamped = C.DecClamped 4601 DecClamped = C.DecClamped
4526 DecInvalidOperation = C.DecInvalidOperation 4602 DecInvalidOperation = C.DecInvalidOperation
4527 DecIEEEInvalidOperation = C.DecIEEEInvalidOperation 4603 DecIEEEInvalidOperation = C.DecIEEEInvalidOperation
4528 4604
4529 def assertIsExclusivelySet(signal, signal_dict): 4605 def assertIsExclusivelySet(signal, signal_dict):
4530 for sig in signal_dict: 4606 for sig in signal_dict:
4531 if sig == signal: 4607 if sig == signal:
4532 self.assertTrue(signal_dict[sig]) 4608 self.assertTrue(signal_dict[sig])
4533 else: 4609 else:
4534 self.assertFalse(signal_dict[sig]) 4610 self.assertFalse(signal_dict[sig])
4535 4611
4536 c = DefaultContext.copy() 4612 c = DefaultContext.copy()
4537 4613
4538 # Signal dict methods 4614 # Signal dict methods
4539 self.assertTrue(Overflow in c.traps) 4615 self.assertTrue(Overflow in c.traps)
4540 self.assertTrue(c.traps.has_key(Overflow))
4541 c.clear_traps() 4616 c.clear_traps()
4542 for k in c.traps.keys(): 4617 for k in c.traps.keys():
4543 c.traps[k] = True 4618 c.traps[k] = True
4544 for v in c.traps.values(): 4619 for v in c.traps.values():
4545 self.assertTrue(v) 4620 self.assertTrue(v)
4546 c.clear_traps() 4621 c.clear_traps()
4547 for k, v in c.traps.items(): 4622 for k, v in c.traps.items():
4548 self.assertFalse(v) 4623 self.assertFalse(v)
4549 4624
4550 self.assertFalse(c.flags.get(Overflow)) 4625 self.assertFalse(c.flags.get(Overflow))
(...skipping 38 matching lines...) Expand 10 before | Expand all | Expand 10 after
4589 Overflow: C.DecOverflow, 4664 Overflow: C.DecOverflow,
4590 DivisionByZero: C.DecDivisionByZero, 4665 DivisionByZero: C.DecDivisionByZero,
4591 InvalidOperation: C.DecIEEEInvalidOperation 4666 InvalidOperation: C.DecIEEEInvalidOperation
4592 } 4667 }
4593 IntCond = [ 4668 IntCond = [
4594 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError, 4669 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError,
4595 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError, 4670 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError,
4596 C.DecConversionSyntax, 4671 C.DecConversionSyntax,
4597 ] 4672 ]
4598 4673
4599 lim = 1 if hasattr(C, 'setfailpoint') else len(OrderedSignals[C]) 4674 lim = len(OrderedSignals[C])
4600 for r in range(lim): 4675 for r in range(lim):
4601 for t in range(lim): 4676 for t in range(lim):
4602 for round in RoundingModes[C]: 4677 for round in RoundingModes[C]:
4603 flags = random.sample(OrderedSignals[C], r) 4678 flags = random.sample(OrderedSignals[C], r)
4604 traps = random.sample(OrderedSignals[C], t) 4679 traps = random.sample(OrderedSignals[C], t)
4605 prec = random.randrange(1, 10000) 4680 prec = random.randrange(1, 10000)
4606 emin = random.randrange(-10000, 0) 4681 emin = random.randrange(-10000, 0)
4607 emax = random.randrange(0, 10000) 4682 emax = random.randrange(0, 10000)
4608 clamp = random.randrange(0, 2) 4683 clamp = random.randrange(0, 2)
4609 caps = random.randrange(0, 2) 4684 caps = random.randrange(0, 2)
(...skipping 22 matching lines...) Expand all
4632 4707
4633 for cond in IntCond: 4708 for cond in IntCond:
4634 c._flags = cond 4709 c._flags = cond
4635 self.assertTrue(c._flags&DecIEEEInvalidOperation) 4710 self.assertTrue(c._flags&DecIEEEInvalidOperation)
4636 assertIsExclusivelySet(InvalidOperation, c.flags) 4711 assertIsExclusivelySet(InvalidOperation, c.flags)
4637 4712
4638 for cond in IntCond: 4713 for cond in IntCond:
4639 c._traps = cond 4714 c._traps = cond
4640 self.assertTrue(c._traps&DecIEEEInvalidOperation) 4715 self.assertTrue(c._traps&DecIEEEInvalidOperation)
4641 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')
4642 4754
4643 4755
4644 all_tests = [ 4756 all_tests = [
4645 CExplicitConstructionTest, PyExplicitConstructionTest, 4757 CExplicitConstructionTest, PyExplicitConstructionTest,
4646 CImplicitConstructionTest, PyImplicitConstructionTest, 4758 CImplicitConstructionTest, PyImplicitConstructionTest,
4647 CFormatTest, PyFormatTest, 4759 CFormatTest, PyFormatTest,
4648 CArithmeticOperatorsTest, PyArithmeticOperatorsTest, 4760 CArithmeticOperatorsTest, PyArithmeticOperatorsTest,
4649 CThreadingTest, PyThreadingTest, 4761 CThreadingTest, PyThreadingTest,
4650 CUsabilityTest, PyUsabilityTest, 4762 CUsabilityTest, PyUsabilityTest,
4651 CPythonAPItests, PyPythonAPItests, 4763 CPythonAPItests, PyPythonAPItests,
4652 CContextAPItests, PyContextAPItests, 4764 CContextAPItests, PyContextAPItests,
4653 CContextWithStatement, PyContextWithStatement, 4765 CContextWithStatement, PyContextWithStatement,
4654 CContextFlags, PyContextFlags, 4766 CContextFlags, PyContextFlags,
4655 CSpecialContexts, PySpecialContexts, 4767 CSpecialContexts, PySpecialContexts,
4656 CContextInputValidation, PyContextInputValidation, 4768 CContextInputValidation, PyContextInputValidation,
4657 CCoverage, PyCoverage, 4769 CCoverage, PyCoverage,
4658 CFunctionality, PyFunctionality, 4770 CFunctionality, PyFunctionality,
4659 CWhitebox, PyWhitebox, 4771 CWhitebox, PyWhitebox,
4660 CIBMTestCases, PyIBMTestCases, 4772 CIBMTestCases, PyIBMTestCases,
4661 ] 4773 ]
4662 4774
4663 # Delete C tests if _decimal.so is not present. 4775 # Delete C tests if _decimal.so is not present.
4664 if not C: 4776 if not C:
4665 all_tests = all_tests[1::2] 4777 all_tests = all_tests[1::2]
4666 4778 else:
4667 # Wrap test functions for testing api failures. Doing this in 4779 all_tests.insert(0, CheckAttributes)
4668 # test_main() causes spurious refleaks, so it is done here. 4780
4669 if hasattr(C, 'setapicalls'):
4670 for cls in all_tests:
4671 if cls == CIBMTestCases or cls == PyIBMTestCases:
4672 newfunc = withFailpoint(getattr(cls, 'eval_equation'))
4673 setattr(cls, 'eval_equation', newfunc)
4674 else:
4675 for attr in dir(cls):
4676 if attr.startswith('test_'):
4677 if attr == 'test_threading':
4678 continue
4679 newfunc = withFailpoint(getattr(cls, attr))
4680 setattr(cls, attr, newfunc)
4681 4781
4682 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):
4683 """ Execute the tests. 4783 """ Execute the tests.
4684 4784
4685 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
4686 is enabled in regrtest.py 4786 is enabled in regrtest.py
4687 """ 4787 """
4688 4788
4689 init(C) 4789 init(C)
4690 init(P) 4790 init(P)
(...skipping 49 matching lines...) Expand 10 before | Expand all | Expand 10 after
4740 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')
4741 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')
4742 (opt, args) = p.parse_args() 4842 (opt, args) = p.parse_args()
4743 4843
4744 if opt.skip: 4844 if opt.skip:
4745 test_main(arith=False, verbose=True) 4845 test_main(arith=False, verbose=True)
4746 elif args: 4846 elif args:
4747 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)
4748 else: 4848 else:
4749 test_main(arith=True, verbose=True) 4849 test_main(arith=True, verbose=True)
LEFTRIGHT

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