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

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, 2 months ago
Right Patch Set: Created 7 years, 5 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 28 matching lines...) Expand all
39 import time 39 import time
40 import warnings 40 import warnings
41 try: 41 try:
42 import threading 42 import threading
43 except ImportError: 43 except ImportError:
44 threading = None 44 threading = None
45 45
46 46
47 C = import_fresh_module('decimal', fresh=['_decimal']) 47 C = import_fresh_module('decimal', fresh=['_decimal'])
48 P = import_fresh_module('decimal', blocked=['_decimal']) 48 P = import_fresh_module('decimal', blocked=['_decimal'])
49 orig_sys_modules = sys.modules['decimal'] 49 orig_sys_decimal = sys.modules['decimal']
50 50
51 # Testing all failures of API functions for _decimal. First, 51 # fractions module must import the correct decimal module.
52 # the number of API calls in a test case is determined. Then, 52 cfractions = import_fresh_module('fractions', fresh=['fractions'])
53 # the testcase is run with all possible API failures, checking 53 sys.modules['decimal'] = P
54 # that FailAPIException is properly raised. 54 pfractions = import_fresh_module('fractions', fresh=['fractions'])
55 def assertRaises(expEx, func, *args, **kwargs): 55 sys.modules['decimal'] = C
56 """assertRaises has to reraise FailAPIException.""" 56 fractions = {C:cfractions, P:pfractions}
57 try: 57 sys.modules['decimal'] = orig_sys_decimal
58 func(*args, **kwargs) 58
59 except Exception as e:
60 if e.__class__ is C.FailAPIException:
61 raise C.FailAPIException
62 if not e.__class__ is expEx:
63 raise e
64
65 def withFailpoint(func):
66 """Wrap a function for testing all possible API failures."""
67 def iter_failpoint(testcase, *args):
68 # These tests will not work.
69 setattr(testcase, 'assertRaises', assertRaises)
70 # Determine number of API calls.
71 C.setapicalls(0)
72 C.setfailpoint(0)
73 func(testcase, *args)
74 n = C.getapicalls()
75 # Fail at each possible API call.
76 for i in range(1, n+1):
77 C.setapicalls(0)
78 C.setfailpoint(i)
79 try:
80 func(testcase, *args)
81 except C.FailAPIException:
82 continue
83 # Error: FailAPIException was not raised
84 raise TestFailed("FailAPIException not raised in: %s" % func)
85 C.setapicalls(0)
86 C.setfailpoint(0)
87 return iter_failpoint
88
89 class ProtectFail(object):
90 """Protect code regions that modify global state (e.g. lines
91 that set or restore global context values). Otherwise it
92 would not be possible to rerun a test case several times."""
93 def __enter__(self):
94 if hasattr(C, 'setfailpoint'):
95 self.fp = C.getfailpoint()
96 C.setfailpoint(0)
97 def __exit__(self, *_):
98 if hasattr(C, 'setfailpoint'):
99 C.setfailpoint(self.fp)
100 if self.fp and C.getapicalls() >= self.fp:
101 # Pretend that API calls in the protected block failed.
102 raise C.FailAPIException
103
104 def protectfail():
105 return ProtectFail()
106
107 if hasattr(C, 'setfailpoint'):
108 # Functions that are iterated several times must use
109 # the same random sequence each time.
110 randseed = int(time.time())
111 # Implicit initialization of the module context must
112 # be tested first.
113 for i in range(1, 100):
114 C.setapicalls(0)
115 C.setfailpoint(i)
116 try:
117 C.getcontext()
118 except C.FailAPIException as e:
119 continue
120 C.setapicalls(0)
121 C.setfailpoint(0)
122 59
123 # Useful Test Constant 60 # Useful Test Constant
124 Signals = { 61 Signals = {
125 C: tuple(C.getcontext().flags.keys()) if C else None, 62 C: tuple(C.getcontext().flags.keys()) if C else None,
126 P: tuple(P.getcontext().flags.keys()) 63 P: tuple(P.getcontext().flags.keys())
127 } 64 }
128 # Signals ordered with respect to precedence: when an operation 65 # Signals ordered with respect to precedence: when an operation
129 # produces multiple signals, signals occurring later in the list 66 # produces multiple signals, signals occurring later in the list
130 # should be handled before those occurring earlier in the list. 67 # should be handled before those occurring earlier in the list.
131 OrderedSignals = { 68 OrderedSignals = {
132 C: [C.Clamped, C.Rounded, C.Inexact, C.Subnormal, C.Underflow, 69 C: [C.Clamped, C.Rounded, C.Inexact, C.Subnormal, C.Underflow,
133 C.Overflow, C.DivisionByZero, C.InvalidOperation] if C else None, 70 C.Overflow, C.DivisionByZero, C.InvalidOperation] if C else None,
134 P: [P.Clamped, P.Rounded, P.Inexact, P.Subnormal, P.Underflow, 71 P: [P.Clamped, P.Rounded, P.Inexact, P.Subnormal, P.Underflow,
135 P.Overflow, P.DivisionByZero, P.InvalidOperation] 72 P.Overflow, P.DivisionByZero, P.InvalidOperation]
136 } 73 }
137 def assert_signals(cls, context, attr, expected): 74 def assert_signals(cls, context, attr, expected):
138 d = getattr(context, attr) 75 d = getattr(context, attr)
139 cls.assertTrue(all(d[s] if s in expected else not d[s] for s in d)) 76 cls.assertTrue(all(d[s] if s in expected else not d[s] for s in d))
140 77
141 RoundingModes = { 78 RoundingModes = {
142 C: (C.ROUND_UP, C.ROUND_DOWN, C.ROUND_CEILING, C.ROUND_FLOOR, 79 C: (C.ROUND_UP, C.ROUND_DOWN, C.ROUND_CEILING, C.ROUND_FLOOR,
143 C.ROUND_HALF_UP, C.ROUND_HALF_DOWN, C.ROUND_HALF_EVEN, 80 C.ROUND_HALF_UP, C.ROUND_HALF_DOWN, C.ROUND_HALF_EVEN,
144 C.ROUND_05UP) if C else None, 81 C.ROUND_05UP) if C else None,
145 P: (P.ROUND_UP, P.ROUND_DOWN, P.ROUND_CEILING, P.ROUND_FLOOR, 82 P: (P.ROUND_UP, P.ROUND_DOWN, P.ROUND_CEILING, P.ROUND_FLOOR,
146 P.ROUND_HALF_UP, P.ROUND_HALF_DOWN, P.ROUND_HALF_EVEN, P.ROUND_05UP) 83 P.ROUND_HALF_UP, P.ROUND_HALF_DOWN, P.ROUND_HALF_EVEN,
84 P.ROUND_05UP)
147 } 85 }
148 86
149 # Tests are built around these assumed context defaults. 87 # Tests are built around these assumed context defaults.
150 # test_main() restores the original context. 88 # test_main() restores the original context.
151 ORIGINAL_CONTEXT = { 89 ORIGINAL_CONTEXT = {
152 C: C.getcontext().copy() if C else None, 90 C: C.getcontext().copy() if C else None,
153 P: P.getcontext().copy() 91 P: P.getcontext().copy()
154 } 92 }
155 def init(m): 93 def init(m):
156 if not m: return 94 if not m: return
157 DefaultTestContext = m.Context( 95 DefaultTestContext = m.Context(
158 prec=9, rounding=m.ROUND_HALF_EVEN, traps=dict.fromkeys(Signals[m], 0) 96 prec=9, rounding=m.ROUND_HALF_EVEN, traps=dict.fromkeys(Signals[m], 0)
159 ) 97 )
160 m.setcontext(DefaultTestContext) 98 m.setcontext(DefaultTestContext)
161 99
162 TESTDATADIR = 'decimaltestdata' 100 TESTDATADIR = 'decimaltestdata'
163 if __name__ == '__main__': 101 if __name__ == '__main__':
164 file = sys.argv[0] 102 file = sys.argv[0]
165 else: 103 else:
166 file = __file__ 104 file = __file__
167 testdir = os.path.dirname(file) or os.curdir 105 testdir = os.path.dirname(file) or os.curdir
168 directory = testdir + os.sep + TESTDATADIR + os.sep 106 directory = testdir + os.sep + TESTDATADIR + os.sep
169 107
170 skip_expected = not os.path.isdir(directory) 108 skip_expected = not os.path.isdir(directory)
171 109
172 # 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
173 # Slower, since it runs some things several times. 111 # Slower, since it runs some things several times.
174 EXTENDEDERRORTEST = False 112 EXTENDEDERRORTEST = False
175 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
176 119
177 class IBMTestCases(unittest.TestCase): 120 class IBMTestCases(unittest.TestCase):
178 """Class which tests the Decimal class against the IBM test cases.""" 121 """Class which tests the Decimal class against the IBM test cases."""
179 122
180 def setUp(self): 123 def setUp(self):
181 self.context = self.decimal.Context() 124 self.context = self.decimal.Context()
182 self.readcontext = self.decimal.Context() 125 self.readcontext = self.decimal.Context()
183 self.ignore_list = ['#'] 126 self.ignore_list = ['#']
184 127
185 # List of individual .decTest test ids that correspond to tests that 128 # List of individual .decTest test ids that correspond to tests that
186 # we're skipping for one reason or another. 129 # we're skipping for one reason or another.
187 self.skipped_test_ids = set([ 130 self.skipped_test_ids = set([
188 # Skip implementation-specific scaleb tests. 131 # Skip implementation-specific scaleb tests.
189 'scbx164', 132 'scbx164',
190 'scbx165', 133 'scbx165',
191 134
192 # For some operations (currently exp, ln, log10, power), the decNumb er 135 # For some operations (currently exp, ln, log10, power), the decNumb er
193 # reference implementation imposes additional restrictions on the co ntext 136 # reference implementation imposes additional restrictions on the co ntext
194 # and operands. These restrictions are not part of the specificatio n; 137 # and operands. These restrictions are not part of the specificatio n;
195 # 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
196 # testcases. We skip testcases that violate these restrictions, sin ce 139 # testcases. We skip testcases that violate these restrictions, sin ce
197 # Decimal behaves differently from decNumber for these testcases so these 140 # Decimal behaves differently from decNumber for these testcases so these
198 # testcases would otherwise fail. 141 # testcases would otherwise fail.
199 'expx901', 142 'expx901',
200 'expx902', 143 'expx902',
201 'expx903', 144 'expx903',
(...skipping 116 matching lines...) Expand 10 before | Expand all | Expand 10 after
318 'is_zero', 261 'is_zero',
319 'same_quantum') 262 'same_quantum')
320 263
321 def read_unlimited(self, v, context): 264 def read_unlimited(self, v, context):
322 """Work around the limitations of the 32-bit _decimal version. The 265 """Work around the limitations of the 32-bit _decimal version. The
323 guaranteed maximum values for prec, Emax etc. are 425000000, 266 guaranteed maximum values for prec, Emax etc. are 425000000,
324 but higher values usually work, except for rare corner cases. 267 but higher values usually work, except for rare corner cases.
325 In particular, all of the IBM tests pass with maximum values 268 In particular, all of the IBM tests pass with maximum values
326 of 1070000000.""" 269 of 1070000000."""
327 if self.decimal == C and self.decimal.MAX_EMAX == 425000000: 270 if self.decimal == C and self.decimal.MAX_EMAX == 425000000:
328 self.readcontext.unsafe_setprec(1070000000) 271 self.readcontext._unsafe_setprec(1070000000)
329 self.readcontext.unsafe_setemax(1070000000) 272 self.readcontext._unsafe_setemax(1070000000)
330 self.readcontext.unsafe_setemin(-1070000000) 273 self.readcontext._unsafe_setemin(-1070000000)
331 return self.readcontext.create_decimal(v) 274 return self.readcontext.create_decimal(v)
332 else: 275 else:
333 return self.decimal.Decimal(v, context) 276 return self.decimal.Decimal(v, context)
334 277
335 def eval_file(self, file): 278 def eval_file(self, file):
336 global skip_expected 279 global skip_expected
337 if skip_expected: 280 if skip_expected:
338 raise unittest.SkipTest 281 raise unittest.SkipTest
339 return 282 return
340 with open(file) as f: 283 with open(file) as f:
(...skipping 34 matching lines...) Expand 10 before | Expand all | Expand 10 after
375 try: 318 try:
376 value = int(value) 319 value = int(value)
377 except ValueError: 320 except ValueError:
378 pass 321 pass
379 322
380 funct = self.ChangeDict.get(funct, (lambda *args: None)) 323 funct = self.ChangeDict.get(funct, (lambda *args: None))
381 funct(value) 324 funct(value)
382 325
383 def eval_equation(self, s): 326 def eval_equation(self, s):
384 327
385 if not TEST_ALL and not hasattr(C, 'setfailpoint') and \ 328 if not TEST_ALL and random.random() < 0.90:
386 random.random() < 0.90:
387 return 329 return
388 330
389 with protectfail(): 331 self.context.clear_flags()
390 self.context.clear_flags()
391 332
392 try: 333 try:
393 Sides = s.split('->') 334 Sides = s.split('->')
394 L = Sides[0].strip().split() 335 L = Sides[0].strip().split()
395 id = L[0] 336 id = L[0]
396 if DEBUG: 337 if DEBUG:
397 print("Test ", id, end=" ") 338 print("Test ", id, end=" ")
398 funct = L[1].lower() 339 funct = L[1].lower()
399 valstemp = L[2:] 340 valstemp = L[2:]
400 L = Sides[1].strip().split() 341 L = Sides[1].strip().split()
(...skipping 47 matching lines...) Expand 10 before | Expand all | Expand 10 after
448 else: 389 else:
449 self.fail("Did not raise %s in %s" % (error, s)) 390 self.fail("Did not raise %s in %s" % (error, s))
450 self.context.traps[error] = 0 391 self.context.traps[error] = 0
451 v = self.context.create_decimal(v) 392 v = self.context.create_decimal(v)
452 else: 393 else:
453 v = self.read_unlimited(v, self.context) 394 v = self.read_unlimited(v, self.context)
454 vals.append(v) 395 vals.append(v)
455 396
456 ans = FixQuotes(ans) 397 ans = FixQuotes(ans)
457 398
458 # three argument power/powmod (deprecated)
459 if self.decimal == C:
460 if fname == 'power' and len(vals) == 3:
461 # name is different
462 fname = 'powmod'
463 funct = getattr(self.context, fname)
464
465 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') :
466 for error in theirexceptions: 400 for error in theirexceptions:
467 self.context.traps[error] = 1 401 self.context.traps[error] = 1
468 try: 402 try:
469 funct(*vals) 403 funct(*vals)
470 except error: 404 except error:
471 pass 405 pass
472 except Signals[self.decimal] as e: 406 except Signals[self.decimal] as e:
473 self.fail("Raised %s in %s when %s disabled" % \ 407 self.fail("Raised %s in %s when %s disabled" % \
474 (e, s, error)) 408 (e, s, error))
(...skipping 20 matching lines...) Expand all
495 429
496 430
497 if DEBUG: 431 if DEBUG:
498 print("--", self.context) 432 print("--", self.context)
499 try: 433 try:
500 result = str(funct(*vals)) 434 result = str(funct(*vals))
501 if fname in self.LogicalFunctions: 435 if fname in self.LogicalFunctions:
502 result = str(int(eval(result))) # 'True', 'False' -> '1', '0' 436 result = str(int(eval(result))) # 'True', 'False' -> '1', '0'
503 except Signals[self.decimal] as error: 437 except Signals[self.decimal] as error:
504 self.fail("Raised %s in %s" % (error, s)) 438 self.fail("Raised %s in %s" % (error, s))
505 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.
506 # Errors are expected with failpoints. 440 print("ERROR:", s)
507 if not hasattr(C, 'setfailpoint'): 441 raise
508 print("ERROR:", s)
509 raise e.__class__
510 442
511 myexceptions = self.getexceptions() 443 myexceptions = self.getexceptions()
512 444
513 myexceptions.sort(key=repr) 445 myexceptions.sort(key=repr)
514 theirexceptions.sort(key=repr) 446 theirexceptions.sort(key=repr)
515 447
516 self.assertEqual(result, ans, 448 self.assertEqual(result, ans,
517 'Incorrect answer for ' + s + ' -- got ' + result) 449 'Incorrect answer for ' + s + ' -- got ' + result)
518 450
519 self.assertEqual(myexceptions, theirexceptions, 451 self.assertEqual(myexceptions, theirexceptions,
520 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) 452 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions))
521 return 453 return
522 454
523 def getexceptions(self): 455 def getexceptions(self):
524 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]]
525 457
526 def change_precision(self, prec): 458 def change_precision(self, prec):
527 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 459 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
528 self.context.unsafe_setprec(prec) 460 self.context._unsafe_setprec(prec)
529 else: 461 else:
530 self.context.prec = prec 462 self.context.prec = prec
531 def change_rounding_method(self, rounding): 463 def change_rounding_method(self, rounding):
532 self.context.rounding = rounding 464 self.context.rounding = rounding
533 def change_min_exponent(self, exp): 465 def change_min_exponent(self, exp):
534 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 466 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
535 self.context.unsafe_setemin(exp) 467 self.context._unsafe_setemin(exp)
536 else: 468 else:
537 self.context.Emin = exp 469 self.context.Emin = exp
538 def change_max_exponent(self, exp): 470 def change_max_exponent(self, exp):
539 if self.decimal == C and self.decimal.MAX_PREC == 425000000: 471 if self.decimal == C and self.decimal.MAX_PREC == 425000000:
540 self.context.unsafe_setemax(exp) 472 self.context._unsafe_setemax(exp)
541 else: 473 else:
542 self.context.Emax = exp 474 self.context.Emax = exp
543 def change_clamp(self, clamp): 475 def change_clamp(self, clamp):
544 self.context.clamp = clamp 476 self.context.clamp = clamp
545 477
546 class CIBMTestCases(IBMTestCases): 478 class CIBMTestCases(IBMTestCases):
547 decimal = C 479 decimal = C
548 class PyIBMTestCases(IBMTestCases): 480 class PyIBMTestCases(IBMTestCases):
549 decimal = P 481 decimal = P
550 482
(...skipping 55 matching lines...) Expand 10 before | Expand all | Expand 10 after
606 self.assertEqual(str(Decimal('45e2')), '4.5E+3') 538 self.assertEqual(str(Decimal('45e2')), '4.5E+3')
607 539
608 #just not a number 540 #just not a number
609 self.assertEqual(str(Decimal('ugly')), 'NaN') 541 self.assertEqual(str(Decimal('ugly')), 'NaN')
610 542
611 #leading and trailing whitespace permitted 543 #leading and trailing whitespace permitted
612 self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4') 544 self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4')
613 self.assertEqual(str(Decimal(' -7.89')), '-7.89') 545 self.assertEqual(str(Decimal(' -7.89')), '-7.89')
614 self.assertEqual(str(Decimal(" 3.45679 ")), '3.45679') 546 self.assertEqual(str(Decimal(" 3.45679 ")), '3.45679')
615 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
616 with localcontext() as c: 554 with localcontext() as c:
617 c.traps[InvalidOperation] = True 555 c.traps[InvalidOperation] = True
618 # Invalid string 556 # Invalid string
619 self.assertRaises(InvalidOperation, Decimal, "xyz") 557 self.assertRaises(InvalidOperation, Decimal, "xyz")
620 # Two arguments max 558 # Two arguments max
621 self.assertRaises(TypeError, Decimal, "1234", "x", "y") 559 self.assertRaises(TypeError, Decimal, "1234", "x", "y")
622 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
623 def test_explicit_from_tuples(self): 573 def test_explicit_from_tuples(self):
624 Decimal = self.decimal.Decimal 574 Decimal = self.decimal.Decimal
625 575
626 #zero 576 #zero
627 d = Decimal( (0, (0,), 0) ) 577 d = Decimal( (0, (0,), 0) )
628 self.assertEqual(str(d), '0') 578 self.assertEqual(str(d), '0')
629 579
630 #int 580 #int
631 d = Decimal( (1, (4, 5), 0) ) 581 d = Decimal( (1, (4, 5), 0) )
632 self.assertEqual(str(d), '-45') 582 self.assertEqual(str(d), '-45')
(...skipping 23 matching lines...) Expand all
656 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) ) 606 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) )
657 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') ) 607 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') )
658 608
659 #bad coefficients 609 #bad coefficients
660 self.assertRaises(ValueError, Decimal, (1, "xyz", 2) ) 610 self.assertRaises(ValueError, Decimal, (1, "xyz", 2) )
661 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) ) 611 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) )
662 self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) ) 612 self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) )
663 self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) ) 613 self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) )
664 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) ) 614 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) )
665 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
666 def test_explicit_from_bool(self): 631 def test_explicit_from_bool(self):
667 Decimal = self.decimal.Decimal 632 Decimal = self.decimal.Decimal
668 633
669 self.assertIs(bool(Decimal(0)), False) 634 self.assertIs(bool(Decimal(0)), False)
670 self.assertIs(bool(Decimal(1)), True) 635 self.assertIs(bool(Decimal(1)), True)
671 self.assertEqual(Decimal(False), Decimal(0)) 636 self.assertEqual(Decimal(False), Decimal(0))
672 self.assertEqual(Decimal(True), Decimal(1)) 637 self.assertEqual(Decimal(True), Decimal(1))
673 638
674 def test_explicit_from_Decimal(self): 639 def test_explicit_from_Decimal(self):
675 Decimal = self.decimal.Decimal 640 Decimal = self.decimal.Decimal
(...skipping 13 matching lines...) Expand all
689 e = Decimal(d) 654 e = Decimal(d)
690 self.assertEqual(str(e), '-45') 655 self.assertEqual(str(e), '-45')
691 656
692 #zero 657 #zero
693 d = Decimal(0) 658 d = Decimal(0)
694 e = Decimal(d) 659 e = Decimal(d)
695 self.assertEqual(str(e), '0') 660 self.assertEqual(str(e), '0')
696 661
697 @requires_IEEE_754 662 @requires_IEEE_754
698 def test_explicit_from_float(self): 663 def test_explicit_from_float(self):
699 if hasattr(C, 'setfailpoint'):
700 random.seed(randseed)
701 664
702 Decimal = self.decimal.Decimal 665 Decimal = self.decimal.Decimal
703 666
704 r = Decimal(0.1) 667 r = Decimal(0.1)
705 self.assertEqual(type(r), Decimal) 668 self.assertEqual(type(r), Decimal)
706 self.assertEqual(str(r), 669 self.assertEqual(str(r),
707 '0.1000000000000000055511151231257827021181583404541015625') 670 '0.1000000000000000055511151231257827021181583404541015625')
708 self.assertTrue(Decimal(float('nan')).is_qnan()) 671 self.assertTrue(Decimal(float('nan')).is_qnan())
709 self.assertTrue(Decimal(float('inf')).is_infinite()) 672 self.assertTrue(Decimal(float('inf')).is_infinite())
710 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
800 763
801 nc.traps[InvalidOperation] = False 764 nc.traps[InvalidOperation] = False
802 self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN') 765 self.assertEqual(str(nc.create_decimal('NaN12345')), 'NaN')
803 self.assertTrue(nc.flags[InvalidOperation]) 766 self.assertTrue(nc.flags[InvalidOperation])
804 767
805 nc.flags[InvalidOperation] = False 768 nc.flags[InvalidOperation] = False
806 self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN') 769 self.assertEqual(str(nc.create_decimal(Decimal('NaN12345'))), 'NaN')
807 self.assertTrue(nc.flags[InvalidOperation]) 770 self.assertTrue(nc.flags[InvalidOperation])
808 771
809 def test_explicit_context_create_from_float(self): 772 def test_explicit_context_create_from_float(self):
810 if hasattr(C, 'setfailpoint'):
811 random.seed(randseed)
812 773
813 Decimal = self.decimal.Decimal 774 Decimal = self.decimal.Decimal
814 775
815 nc = self.decimal.Context() 776 nc = self.decimal.Context()
816 r = nc.create_decimal(0.1) 777 r = nc.create_decimal(0.1)
817 self.assertEqual(type(r), Decimal) 778 self.assertEqual(type(r), Decimal)
818 self.assertEqual(str(r), '0.1000000000000000055511151231') 779 self.assertEqual(str(r), '0.1000000000000000055511151231')
819 self.assertTrue(nc.create_decimal(float('nan')).is_qnan()) 780 self.assertTrue(nc.create_decimal(float('nan')).is_qnan())
820 self.assertTrue(nc.create_decimal(float('inf')).is_infinite()) 781 self.assertTrue(nc.create_decimal(float('inf')).is_infinite())
821 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
983 944
984 ('g', '0', '0'), 945 ('g', '0', '0'),
985 ('g', '0.0', '0.0'), 946 ('g', '0.0', '0.0'),
986 ('g', '0E1', '0e+1'), 947 ('g', '0E1', '0e+1'),
987 ('G', '0E1', '0E+1'), 948 ('G', '0E1', '0E+1'),
988 ('g', '0E-5', '0.00000'), 949 ('g', '0E-5', '0.00000'),
989 ('g', '0E-6', '0.000000'), 950 ('g', '0E-6', '0.000000'),
990 ('g', '0E-7', '0e-7'), 951 ('g', '0E-7', '0e-7'),
991 ('g', '-0E2', '-0e+2'), 952 ('g', '-0E2', '-0e+2'),
992 ('.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'
993 ('.1g', '3.14159265', '3'), 955 ('.1g', '3.14159265', '3'),
994 ('.2g', '3.14159265', '3.1'), 956 ('.2g', '3.14159265', '3.1'),
995 ('.5g', '3.14159265', '3.1416'), 957 ('.5g', '3.14159265', '3.1416'),
996 ('.7g', '3.14159265', '3.141593'), 958 ('.7g', '3.14159265', '3.141593'),
997 ('.8g', '3.14159265', '3.1415926'), # round-half-even! 959 ('.8g', '3.14159265', '3.1415926'), # round-half-even!
998 ('.9g', '3.14159265', '3.14159265'), 960 ('.9g', '3.14159265', '3.14159265'),
999 ('.10g', '3.14159265', '3.14159265'), # don't pad 961 ('.10g', '3.14159265', '3.14159265'), # don't pad
1000 962
1001 ('%', '0E1', '0%'), 963 ('%', '0E1', '0%'),
1002 ('%', '0E0', '0%'), 964 ('%', '0E0', '0%'),
(...skipping 158 matching lines...) Expand 10 before | Expand all | Expand 10 after
1161 self.assertEqual(get_fmt(123456, crazy, '07n'), '1-2345-6') 1123 self.assertEqual(get_fmt(123456, crazy, '07n'), '1-2345-6')
1162 self.assertEqual(get_fmt(123456, crazy, '08n'), '1-2345-6') 1124 self.assertEqual(get_fmt(123456, crazy, '08n'), '1-2345-6')
1163 self.assertEqual(get_fmt(123456, crazy, '09n'), '01-2345-6') 1125 self.assertEqual(get_fmt(123456, crazy, '09n'), '01-2345-6')
1164 self.assertEqual(get_fmt(123456, crazy, '010n'), '0-01-2345-6') 1126 self.assertEqual(get_fmt(123456, crazy, '010n'), '0-01-2345-6')
1165 self.assertEqual(get_fmt(123456, crazy, '011n'), '0-01-2345-6') 1127 self.assertEqual(get_fmt(123456, crazy, '011n'), '0-01-2345-6')
1166 self.assertEqual(get_fmt(123456, crazy, '012n'), '00-01-2345-6') 1128 self.assertEqual(get_fmt(123456, crazy, '012n'), '00-01-2345-6')
1167 self.assertEqual(get_fmt(123456, crazy, '013n'), '000-01-2345-6') 1129 self.assertEqual(get_fmt(123456, crazy, '013n'), '000-01-2345-6')
1168 1130
1169 # wide char separator and decimal point 1131 # wide char separator and decimal point
1170 self.assertEqual(get_fmt(Decimal('-1.5'), dotsep_wide, '020n'), 1132 self.assertEqual(get_fmt(Decimal('-1.5'), dotsep_wide, '020n'),
1171 '-0´000´000´000´001¿5') 1133 '-0\u00b4000\u00b4000\u00b4000\u00b4001\u00bf5')
1172 1134
1173 def test_wide_char_separator_decimal_point(self): 1135 def test_wide_char_separator_decimal_point(self):
1174 # locale with wide char separator and decimal point 1136 # locale with wide char separator and decimal point
1175 Decimal = self.decimal.Decimal 1137 Decimal = self.decimal.Decimal
1176 1138
1177 try: 1139 try:
1178 locale.setlocale(locale.LC_ALL, 'ps_AF') 1140 locale.setlocale(locale.LC_ALL, 'ps_AF')
1179 except locale.Error: 1141 except locale.Error:
1180 return 1142 return
1181 1143
1182 self.assertEqual(format(Decimal('100000000.123'), 'n'), 1144 self.assertEqual(format(Decimal('100000000.123'), 'n'),
1183 '100٬000٬000٫123') 1145 '100\u066c000\u066c000\u066b123')
1184 locale.resetlocale() 1146 locale.resetlocale()
1185 1147
1186 class CFormatTest(FormatTest): 1148 class CFormatTest(FormatTest):
1187 decimal = C 1149 decimal = C
1188 class PyFormatTest(FormatTest): 1150 class PyFormatTest(FormatTest):
1189 decimal = P 1151 decimal = P
1190 1152
1191 class ArithmeticOperatorsTest(unittest.TestCase): 1153 class ArithmeticOperatorsTest(unittest.TestCase):
1192 '''Unit tests for all arithmetic operators, binary and unary.''' 1154 '''Unit tests for all arithmetic operators, binary and unary.'''
1193 1155
(...skipping 395 matching lines...) Expand 10 before | Expand all | Expand 10 after
1589 # Test the "threading isolation" of a Context. Also test changing 1551 # Test the "threading isolation" of a Context. Also test changing
1590 # the DefaultContext, which acts as a template for the thread-local 1552 # the DefaultContext, which acts as a template for the thread-local
1591 # contexts. 1553 # contexts.
1592 save_prec = DefaultContext.prec 1554 save_prec = DefaultContext.prec
1593 save_emax = DefaultContext.Emax 1555 save_emax = DefaultContext.Emax
1594 save_emin = DefaultContext.Emin 1556 save_emin = DefaultContext.Emin
1595 DefaultContext.prec = 24 1557 DefaultContext.prec = 24
1596 DefaultContext.Emax = 425000000 1558 DefaultContext.Emax = 425000000
1597 DefaultContext.Emin = -425000000 1559 DefaultContext.Emin = -425000000
1598 1560
1599 with protectfail(): 1561 self.synchro = threading.Event()
1600 self.synchro = threading.Event() 1562 self.finish1 = threading.Event()
1601 self.finish1 = threading.Event() 1563 self.finish2 = threading.Event()
1602 self.finish2 = threading.Event() 1564
1603 1565 th1 = threading.Thread(target=thfunc1, args=(self,))
1604 th1 = threading.Thread(target=thfunc1, args=(self,)) 1566 th2 = threading.Thread(target=thfunc2, args=(self,))
1605 th2 = threading.Thread(target=thfunc2, args=(self,)) 1567
1606 1568 th1.start()
1607 th1.start() 1569 th2.start()
1608 th2.start() 1570
1609 1571 self.finish1.wait()
1610 self.finish1.wait() 1572 self.finish2.wait()
1611 self.finish2.wait()
1612 1573
1613 for sig in Signals[self.decimal]: 1574 for sig in Signals[self.decimal]:
1614 self.assertFalse(DefaultContext.flags[sig]) 1575 self.assertFalse(DefaultContext.flags[sig])
1615 1576
1616 DefaultContext.prec = save_prec 1577 DefaultContext.prec = save_prec
1617 DefaultContext.Emax = save_emax 1578 DefaultContext.Emax = save_emax
1618 DefaultContext.Emin = save_emin 1579 DefaultContext.Emin = save_emin
1619 return 1580 return
1620 1581
1621 @unittest.skipUnless(threading, 'threading required') 1582 @unittest.skipUnless(threading, 'threading required')
1622 class CThreadingTest(ThreadingTest): 1583 class CThreadingTest(ThreadingTest):
1623 decimal = C 1584 decimal = C
1624 @unittest.skipUnless(threading, 'threading required') 1585 @unittest.skipUnless(threading, 'threading required')
1625 class PyThreadingTest(ThreadingTest): 1586 class PyThreadingTest(ThreadingTest):
1626 decimal = P 1587 decimal = P
1627 1588
1628 class UsabilityTest(unittest.TestCase): 1589 class UsabilityTest(unittest.TestCase):
1629 '''Unit tests for Usability cases of Decimal.''' 1590 '''Unit tests for Usability cases of Decimal.'''
1630 1591
1631 def test_comparison_operators(self): 1592 def test_comparison_operators(self):
1632 if hasattr(C, 'setfailpoint'):
1633 random.seed(randseed)
1634 1593
1635 Decimal = self.decimal.Decimal 1594 Decimal = self.decimal.Decimal
1636 1595
1637 da = Decimal('23.42') 1596 da = Decimal('23.42')
1638 db = Decimal('23.42') 1597 db = Decimal('23.42')
1639 dc = Decimal('45') 1598 dc = Decimal('45')
1640 1599
1641 #two Decimals 1600 #two Decimals
1642 self.assertGreater(dc, da) 1601 self.assertGreater(dc, da)
1643 self.assertGreaterEqual(dc, da) 1602 self.assertGreaterEqual(dc, da)
(...skipping 56 matching lines...) Expand 10 before | Expand all | Expand 10 after
1700 self.assertNotEqual(db, (3.0+1j)) 1659 self.assertNotEqual(db, (3.0+1j))
1701 self.assertNotEqual((3.0+1j), db) 1660 self.assertNotEqual((3.0+1j), db)
1702 1661
1703 self.assertIs(db.__lt__(3.0+0j), NotImplemented) 1662 self.assertIs(db.__lt__(3.0+0j), NotImplemented)
1704 self.assertIs(db.__le__(3.0+0j), NotImplemented) 1663 self.assertIs(db.__le__(3.0+0j), NotImplemented)
1705 self.assertIs(db.__gt__(3.0+0j), NotImplemented) 1664 self.assertIs(db.__gt__(3.0+0j), NotImplemented)
1706 self.assertIs(db.__le__(3.0+0j), NotImplemented) 1665 self.assertIs(db.__le__(3.0+0j), NotImplemented)
1707 1666
1708 def test_decimal_fraction_comparison(self): 1667 def test_decimal_fraction_comparison(self):
1709 D = self.decimal.Decimal 1668 D = self.decimal.Decimal
1669 F = fractions[self.decimal].Fraction
1710 Context = self.decimal.Context 1670 Context = self.decimal.Context
1711 localcontext = self.decimal.localcontext 1671 localcontext = self.decimal.localcontext
1712 InvalidOperation = self.decimal.InvalidOperation 1672 InvalidOperation = self.decimal.InvalidOperation
1713 1673
1714 savedecimal = sys.modules['decimal']
1715 sys.modules['decimal'] = self.decimal
1716 fractions = import_fresh_module('fractions', fresh=['fractions'])
1717 F = fractions.Fraction
1718 1674
1719 emax = C.MAX_EMAX if C else 999999999 1675 emax = C.MAX_EMAX if C else 999999999
1720 emin = C.MIN_EMIN if C else -999999999 1676 emin = C.MIN_EMIN if C else -999999999
1721 etiny = C.MIN_ETINY if C else -1999999997 1677 etiny = C.MIN_ETINY if C else -1999999997
1722 c = Context(Emax=emax, Emin=emin) 1678 c = Context(Emax=emax, Emin=emin)
1723 1679
1724 with localcontext(c): 1680 with localcontext(c):
1725 c.prec = emax 1681 c.prec = emax
1726 self.assertLess(D(0), F(1,9999999999999999999999999999999999999)) 1682 self.assertLess(D(0), F(1,9999999999999999999999999999999999999))
1727 self.assertLess(F(-1,9999999999999999999999999999999999999), D(0)) 1683 self.assertLess(F(-1,9999999999999999999999999999999999999), D(0))
(...skipping 15 matching lines...) Expand all
1743 self.assertGreater(D('inf'), F(99999999999,123)) 1699 self.assertGreater(D('inf'), F(99999999999,123))
1744 self.assertGreater(D('inf'), F(-99999999999,123)) 1700 self.assertGreater(D('inf'), F(-99999999999,123))
1745 self.assertLess(D('-inf'), F(99999999999,123)) 1701 self.assertLess(D('-inf'), F(99999999999,123))
1746 self.assertLess(D('-inf'), F(-99999999999,123)) 1702 self.assertLess(D('-inf'), F(-99999999999,123))
1747 1703
1748 self.assertRaises(InvalidOperation, D('nan').__gt__, F(-9,123)) 1704 self.assertRaises(InvalidOperation, D('nan').__gt__, F(-9,123))
1749 self.assertIs(NotImplemented, F(-9,123).__lt__(D('nan'))) 1705 self.assertIs(NotImplemented, F(-9,123).__lt__(D('nan')))
1750 self.assertNotEqual(D('nan'), F(-9,123)) 1706 self.assertNotEqual(D('nan'), F(-9,123))
1751 self.assertNotEqual(F(-9,123), D('nan')) 1707 self.assertNotEqual(F(-9,123), D('nan'))
1752 1708
1753 sys.modules['decimal'] = savedecimal
1754 del sys.modules['fractions']
1755
1756 def test_copy_and_deepcopy_methods(self): 1709 def test_copy_and_deepcopy_methods(self):
1757 Decimal = self.decimal.Decimal 1710 Decimal = self.decimal.Decimal
1758 1711
1759 d = Decimal('43.24') 1712 d = Decimal('43.24')
1760 c = copy.copy(d) 1713 c = copy.copy(d)
1761 self.assertEqual(id(c), id(d)) 1714 self.assertEqual(id(c), id(d))
1762 dc = copy.deepcopy(d) 1715 dc = copy.deepcopy(d)
1763 self.assertEqual(id(dc), id(d)) 1716 self.assertEqual(id(dc), id(d))
1764 1717
1765 def test_hash_method(self): 1718 def test_hash_method(self):
1766 if hasattr(C, 'setfailpoint'):
1767 random.seed(randseed)
1768 1719
1769 Decimal = self.decimal.Decimal 1720 Decimal = self.decimal.Decimal
1770 localcontext = self.decimal.localcontext 1721 localcontext = self.decimal.localcontext
1771 1722
1772 def hashit(d): 1723 def hashit(d):
1773 a = hash(d) 1724 a = hash(d)
1774 b = d.__hash__() 1725 b = d.__hash__()
1775 self.assertEqual(a, b) 1726 self.assertEqual(a, b)
1776 return a 1727 return a
1777 1728
1778 #just that it's hashable 1729 #just that it's hashable
1779 hashit(Decimal(23)) 1730 hashit(Decimal(23))
1780 hashit(Decimal('Infinity')) 1731 hashit(Decimal('Infinity'))
1781 hashit(Decimal('-Infinity')) 1732 hashit(Decimal('-Infinity'))
1782 hashit(Decimal('nan123')) 1733 hashit(Decimal('nan123'))
1783 hashit(Decimal('-NaN')) 1734 hashit(Decimal('-NaN'))
1784 1735
1785 test_values = [Decimal(sign*(2**m + n)) 1736 test_values = [Decimal(sign*(2**m + n))
1786 for m in [0, 14, 15, 16, 17, 30, 31, 1737 for m in [0, 14, 15, 16, 17, 30, 31,
1787 32, 33, 61, 62, 63, 64, 65, 66] 1738 32, 33, 61, 62, 63, 64, 65, 66]
1788 for n in range(-10, 10) 1739 for n in range(-10, 10)
1789 for sign in [-1, 1]] 1740 for sign in [-1, 1]]
1790 if hasattr(C, 'setfailpoint'):
1791 test_values = random.sample(test_values, 10)
1792 test_values.extend([ 1741 test_values.extend([
1793 Decimal("-1"), # ==> -2 1742 Decimal("-1"), # ==> -2
1794 Decimal("-0"), # zeros 1743 Decimal("-0"), # zeros
1795 Decimal("0.00"), 1744 Decimal("0.00"),
1796 Decimal("-0.000"), 1745 Decimal("-0.000"),
1797 Decimal("0E10"), 1746 Decimal("0E10"),
1798 Decimal("-0E12"), 1747 Decimal("-0E12"),
1799 Decimal("10.0"), # negative exponent 1748 Decimal("10.0"), # negative exponent
1800 Decimal("-23.00000"), 1749 Decimal("-23.00000"),
1801 Decimal("1230E100"), # positive exponent 1750 Decimal("1230E100"), # positive exponent
(...skipping 102 matching lines...) Expand 10 before | Expand all | Expand 10 after
1904 #floor 1853 #floor
1905 test_pairs = [ 1854 test_pairs = [
1906 ('123.00', 123), 1855 ('123.00', 123),
1907 ('3.2', 3), 1856 ('3.2', 3),
1908 ('3.54', 3), 1857 ('3.54', 3),
1909 ('3.899', 3), 1858 ('3.899', 3),
1910 ('-2.3', -3), 1859 ('-2.3', -3),
1911 ('-11.0', -11), 1860 ('-11.0', -11),
1912 ('0.0', 0), 1861 ('0.0', 0),
1913 ('-0E3', 0), 1862 ('-0E3', 0),
1863 ('89891211712379812736.1', 89891211712379812736),
1914 ] 1864 ]
1915 for d, i in test_pairs: 1865 for d, i in test_pairs:
1916 self.assertEqual(math.floor(Decimal(d)), i) 1866 self.assertEqual(math.floor(Decimal(d)), i)
1917 self.assertRaises(ValueError, math.floor, Decimal('-NaN')) 1867 self.assertRaises(ValueError, math.floor, Decimal('-NaN'))
1918 self.assertRaises(ValueError, math.floor, Decimal('sNaN')) 1868 self.assertRaises(ValueError, math.floor, Decimal('sNaN'))
1919 self.assertRaises(ValueError, math.floor, Decimal('NaN123')) 1869 self.assertRaises(ValueError, math.floor, Decimal('NaN123'))
1920 self.assertRaises(OverflowError, math.floor, Decimal('Inf')) 1870 self.assertRaises(OverflowError, math.floor, Decimal('Inf'))
1921 self.assertRaises(OverflowError, math.floor, Decimal('-Inf')) 1871 self.assertRaises(OverflowError, math.floor, Decimal('-Inf'))
1922 1872
1923 #ceiling 1873 #ceiling
1924 test_pairs = [ 1874 test_pairs = [
1925 ('123.00', 123), 1875 ('123.00', 123),
1926 ('3.2', 4), 1876 ('3.2', 4),
1927 ('3.54', 4), 1877 ('3.54', 4),
1928 ('3.899', 4), 1878 ('3.899', 4),
1929 ('-2.3', -2), 1879 ('-2.3', -2),
1930 ('-11.0', -11), 1880 ('-11.0', -11),
1931 ('0.0', 0), 1881 ('0.0', 0),
1932 ('-0E3', 0), 1882 ('-0E3', 0),
1883 ('89891211712379812736.1', 89891211712379812737),
1933 ] 1884 ]
1934 for d, i in test_pairs: 1885 for d, i in test_pairs:
1935 self.assertEqual(math.ceil(Decimal(d)), i) 1886 self.assertEqual(math.ceil(Decimal(d)), i)
1936 self.assertRaises(ValueError, math.ceil, Decimal('-NaN')) 1887 self.assertRaises(ValueError, math.ceil, Decimal('-NaN'))
1937 self.assertRaises(ValueError, math.ceil, Decimal('sNaN')) 1888 self.assertRaises(ValueError, math.ceil, Decimal('sNaN'))
1938 self.assertRaises(ValueError, math.ceil, Decimal('NaN123')) 1889 self.assertRaises(ValueError, math.ceil, Decimal('NaN123'))
1939 self.assertRaises(OverflowError, math.ceil, Decimal('Inf')) 1890 self.assertRaises(OverflowError, math.ceil, Decimal('Inf'))
1940 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf')) 1891 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf'))
1941 1892
1942 #round, single argument 1893 #round, single argument
(...skipping 231 matching lines...) Expand 10 before | Expand all | Expand 10 after
2174 r = pickle.loads(sy) 2125 r = pickle.loads(sy)
2175 self.assertIsInstance(r, C.Decimal) 2126 self.assertIsInstance(r, C.Decimal)
2176 self.assertEqual(r, x) 2127 self.assertEqual(r, x)
2177 2128
2178 sys.modules['decimal'] = savedecimal 2129 sys.modules['decimal'] = savedecimal
2179 2130
2180 def test_int(self): 2131 def test_int(self):
2181 Decimal = self.decimal.Decimal 2132 Decimal = self.decimal.Decimal
2182 ROUND_DOWN = self.decimal.ROUND_DOWN 2133 ROUND_DOWN = self.decimal.ROUND_DOWN
2183 2134
2184 lim = 10 if hasattr(C, 'setfailpoint') else 250 2135 for x in range(-250, 250):
2185 for x in range(-lim, lim):
2186 s = '%0.2f' % (x / 100.0) 2136 s = '%0.2f' % (x / 100.0)
2187 # should work the same as for floats 2137 # should work the same as for floats
2188 self.assertEqual(int(Decimal(s)), int(float(s))) 2138 self.assertEqual(int(Decimal(s)), int(float(s)))
2189 # 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
2190 d = Decimal(s) 2140 d = Decimal(s)
2191 r = d.to_integral(ROUND_DOWN) 2141 r = d.to_integral(ROUND_DOWN)
2192 self.assertEqual(Decimal(int(d)), r) 2142 self.assertEqual(Decimal(int(d)), r)
2193 2143
2194 self.assertRaises(ValueError, int, Decimal('-nan')) 2144 self.assertRaises(ValueError, int, Decimal('-nan'))
2195 self.assertRaises(ValueError, int, Decimal('snan')) 2145 self.assertRaises(ValueError, int, Decimal('snan'))
2196 self.assertRaises(OverflowError, int, Decimal('inf')) 2146 self.assertRaises(OverflowError, int, Decimal('inf'))
2197 self.assertRaises(OverflowError, int, Decimal('-inf')) 2147 self.assertRaises(OverflowError, int, Decimal('-inf'))
2198 2148
2199 def test_trunc(self): 2149 def test_trunc(self):
2200 Decimal = self.decimal.Decimal 2150 Decimal = self.decimal.Decimal
2201 ROUND_DOWN = self.decimal.ROUND_DOWN 2151 ROUND_DOWN = self.decimal.ROUND_DOWN
2202 2152
2203 lim = 10 if hasattr(C, 'setfailpoint') else 250 2153 for x in range(-250, 250):
2204 for x in range(-lim, lim):
2205 s = '%0.2f' % (x / 100.0) 2154 s = '%0.2f' % (x / 100.0)
2206 # should work the same as for floats 2155 # should work the same as for floats
2207 self.assertEqual(int(Decimal(s)), int(float(s))) 2156 self.assertEqual(int(Decimal(s)), int(float(s)))
2208 # 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
2209 d = Decimal(s) 2158 d = Decimal(s)
2210 r = d.to_integral(ROUND_DOWN) 2159 r = d.to_integral(ROUND_DOWN)
2211 self.assertEqual(Decimal(math.trunc(d)), r) 2160 self.assertEqual(Decimal(math.trunc(d)), r)
2212 2161
2213 def test_from_float(self): 2162 def test_from_float(self):
2214 if hasattr(C, 'setfailpoint'):
2215 random.seed(randseed)
2216 2163
2217 Decimal = self.decimal.Decimal 2164 Decimal = self.decimal.Decimal
2218 2165
2219 class MyDecimal(Decimal): 2166 class MyDecimal(Decimal):
2220 pass 2167 pass
2221 2168
2222 self.assertTrue(issubclass(MyDecimal, Decimal)) 2169 self.assertTrue(issubclass(MyDecimal, Decimal))
2223 2170
2224 r = MyDecimal.from_float(0.1) 2171 r = MyDecimal.from_float(0.1)
2225 self.assertEqual(type(r), MyDecimal) 2172 self.assertEqual(type(r), MyDecimal)
2226 self.assertEqual(str(r), 2173 self.assertEqual(str(r),
2227 '0.1000000000000000055511151231257827021181583404541015625') 2174 '0.1000000000000000055511151231257827021181583404541015625')
2228 bigint = 12345678901234567890123456789 2175 bigint = 12345678901234567890123456789
2229 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint)) 2176 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
2230 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan()) 2177 self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
2231 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite()) 2178 self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
2232 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite()) 2179 self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
2233 self.assertEqual(str(MyDecimal.from_float(float('nan'))), 2180 self.assertEqual(str(MyDecimal.from_float(float('nan'))),
2234 str(Decimal('NaN'))) 2181 str(Decimal('NaN')))
2235 self.assertEqual(str(MyDecimal.from_float(float('inf'))), 2182 self.assertEqual(str(MyDecimal.from_float(float('inf'))),
2236 str(Decimal('Infinity'))) 2183 str(Decimal('Infinity')))
2237 self.assertEqual(str(MyDecimal.from_float(float('-inf'))), 2184 self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
2238 str(Decimal('-Infinity'))) 2185 str(Decimal('-Infinity')))
2239 self.assertRaises(TypeError, MyDecimal.from_float, 'abc') 2186 self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
2240 lim = 10 if hasattr(C, 'setfailpoint') else 200 2187 for i in range(200):
2241 for i in range(lim):
2242 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0) 2188 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
2243 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip 2189 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip
2244 2190
2245 def test_create_decimal_from_float(self): 2191 def test_create_decimal_from_float(self):
2246 Decimal = self.decimal.Decimal 2192 Decimal = self.decimal.Decimal
2247 Context = self.decimal.Context 2193 Context = self.decimal.Context
2248 ROUND_DOWN = self.decimal.ROUND_DOWN 2194 ROUND_DOWN = self.decimal.ROUND_DOWN
2249 ROUND_UP = self.decimal.ROUND_UP 2195 ROUND_UP = self.decimal.ROUND_UP
2250 Inexact = self.decimal.Inexact 2196 Inexact = self.decimal.Inexact
2251 2197
(...skipping 54 matching lines...) Expand 10 before | Expand all | Expand 10 after
2306 self.assertEqual(x.conjugate(), x) 2252 self.assertEqual(x.conjugate(), x)
2307 2253
2308 x = Decimal("1") 2254 x = Decimal("1")
2309 self.assertEqual(complex(x), complex(float(1))) 2255 self.assertEqual(complex(x), complex(float(1)))
2310 2256
2311 self.assertRaises(AttributeError, setattr, x, 'real', 100) 2257 self.assertRaises(AttributeError, setattr, x, 'real', 100)
2312 self.assertRaises(AttributeError, setattr, x, 'imag', 100) 2258 self.assertRaises(AttributeError, setattr, x, 'imag', 100)
2313 self.assertRaises(AttributeError, setattr, x, 'conjugate', 100) 2259 self.assertRaises(AttributeError, setattr, x, 'conjugate', 100)
2314 self.assertRaises(AttributeError, setattr, x, '__complex__', 100) 2260 self.assertRaises(AttributeError, setattr, x, '__complex__', 100)
2315 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
2316 class CPythonAPItests(PythonAPItests): 2377 class CPythonAPItests(PythonAPItests):
2317 decimal = C 2378 decimal = C
2318 class PyPythonAPItests(PythonAPItests): 2379 class PyPythonAPItests(PythonAPItests):
2319 decimal = P 2380 decimal = P
2320 2381
2321 class ContextAPItests(unittest.TestCase): 2382 class ContextAPItests(unittest.TestCase):
2322 2383
2323 def test_pickle(self): 2384 def test_pickle(self):
2324 if hasattr(C, 'setfailpoint'):
2325 random.seed(randseed)
2326 2385
2327 Context = self.decimal.Context 2386 Context = self.decimal.Context
2328 2387
2329 savedecimal = sys.modules['decimal'] 2388 savedecimal = sys.modules['decimal']
2330 2389
2331 # Round trip 2390 # Round trip
2332 sys.modules['decimal'] = self.decimal 2391 sys.modules['decimal'] = self.decimal
2333 c = Context() 2392 c = Context()
2334 e = pickle.loads(pickle.dumps(c)) 2393 e = pickle.loads(pickle.dumps(c))
2335 2394
2336 self.assertEqual(c.prec, e.prec) 2395 self.assertEqual(c.prec, e.prec)
2337 self.assertEqual(c.Emin, e.Emin) 2396 self.assertEqual(c.Emin, e.Emin)
2338 self.assertEqual(c.Emax, e.Emax) 2397 self.assertEqual(c.Emax, e.Emax)
2339 self.assertEqual(c.rounding, e.rounding) 2398 self.assertEqual(c.rounding, e.rounding)
2340 self.assertEqual(c.capitals, e.capitals) 2399 self.assertEqual(c.capitals, e.capitals)
2341 self.assertEqual(c.clamp, e.clamp) 2400 self.assertEqual(c.clamp, e.clamp)
2342 self.assertEqual(c.flags, e.flags) 2401 self.assertEqual(c.flags, e.flags)
2343 self.assertEqual(c.traps, e.traps) 2402 self.assertEqual(c.traps, e.traps)
2344 2403
2345 # Test interchangeability 2404 # Test interchangeability
2346 combinations = [(C, P), (P, C)] if C else [(P, P)] 2405 combinations = [(C, P), (P, C)] if C else [(P, P)]
2347 for dumper, loader in combinations: 2406 for dumper, loader in combinations:
2348 for ri, _ in enumerate(RoundingModes[dumper]): 2407 for ri, _ in enumerate(RoundingModes[dumper]):
2349 if hasattr(C, 'setfailpoint') and ri > 0: continue
2350 for fi, _ in enumerate(OrderedSignals[dumper]): 2408 for fi, _ in enumerate(OrderedSignals[dumper]):
2351 if hasattr(C, 'setfailpoint') and fi > 0: continue
2352 for ti, _ in enumerate(OrderedSignals[dumper]): 2409 for ti, _ in enumerate(OrderedSignals[dumper]):
2353 if hasattr(C, 'setfailpoint') and ti > 0: continue
2354 2410
2355 prec = random.randrange(1, 100) 2411 prec = random.randrange(1, 100)
2356 emin = random.randrange(-100, 0) 2412 emin = random.randrange(-100, 0)
2357 emax = random.randrange(1, 100) 2413 emax = random.randrange(1, 100)
2358 caps = random.randrange(2) 2414 caps = random.randrange(2)
2359 clamp = random.randrange(2) 2415 clamp = random.randrange(2)
2360 2416
2361 # One module dumps 2417 # One module dumps
2362 sys.modules['decimal'] = dumper 2418 sys.modules['decimal'] = dumper
2363 c = dumper.Context( 2419 c = dumper.Context(
(...skipping 35 matching lines...) Expand 10 before | Expand all | Expand 10 after
2399 c = Context() 2455 c = Context()
2400 d = c.copy() 2456 d = c.copy()
2401 self.assertNotEqual(id(c), id(d)) 2457 self.assertNotEqual(id(c), id(d))
2402 self.assertNotEqual(id(c.flags), id(d.flags)) 2458 self.assertNotEqual(id(c.flags), id(d.flags))
2403 self.assertNotEqual(id(c.traps), id(d.traps)) 2459 self.assertNotEqual(id(c.traps), id(d.traps))
2404 k1 = set(c.flags.keys()) 2460 k1 = set(c.flags.keys())
2405 k2 = set(d.flags.keys()) 2461 k2 = set(d.flags.keys())
2406 self.assertEqual(k1, k2) 2462 self.assertEqual(k1, k2)
2407 self.assertEqual(c.flags, d.flags) 2463 self.assertEqual(c.flags, d.flags)
2408 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
2409 def test_abs(self): 2476 def test_abs(self):
2410 Decimal = self.decimal.Decimal 2477 Decimal = self.decimal.Decimal
2411 Context = self.decimal.Context 2478 Context = self.decimal.Context
2412 2479
2413 c = Context() 2480 c = Context()
2414 d = c.abs(Decimal(-1)) 2481 d = c.abs(Decimal(-1))
2415 self.assertEqual(c.abs(-1), d) 2482 self.assertEqual(c.abs(-1), d)
2416 self.assertRaises(TypeError, c.abs, '-1') 2483 self.assertRaises(TypeError, c.abs, '-1')
2417 2484
2418 def test_add(self): 2485 def test_add(self):
(...skipping 450 matching lines...) Expand 10 before | Expand all | Expand 10 after
2869 Context = self.decimal.Context 2936 Context = self.decimal.Context
2870 2937
2871 c = Context() 2938 c = Context()
2872 d = c.power(Decimal(1), Decimal(4)) 2939 d = c.power(Decimal(1), Decimal(4))
2873 self.assertEqual(c.power(1, 4), d) 2940 self.assertEqual(c.power(1, 4), d)
2874 self.assertEqual(c.power(Decimal(1), 4), d) 2941 self.assertEqual(c.power(Decimal(1), 4), d)
2875 self.assertEqual(c.power(1, Decimal(4)), d) 2942 self.assertEqual(c.power(1, Decimal(4)), d)
2876 self.assertEqual(c.power(Decimal(1), Decimal(4)), d) 2943 self.assertEqual(c.power(Decimal(1), Decimal(4)), d)
2877 self.assertRaises(TypeError, c.power, '1', 4) 2944 self.assertRaises(TypeError, c.power, '1', 4)
2878 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)
2879 2947
2880 def test_quantize(self): 2948 def test_quantize(self):
2881 Decimal = self.decimal.Decimal 2949 Decimal = self.decimal.Decimal
2882 Context = self.decimal.Context 2950 Context = self.decimal.Context
2883 2951
2884 c = Context() 2952 c = Context()
2885 d = c.quantize(Decimal(1), Decimal(2)) 2953 d = c.quantize(Decimal(1), Decimal(2))
2886 self.assertEqual(c.quantize(1, 2), d) 2954 self.assertEqual(c.quantize(1, 2), d)
2887 self.assertEqual(c.quantize(Decimal(1), 2), d) 2955 self.assertEqual(c.quantize(Decimal(1), 2), d)
2888 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
3149 with localcontext() as c4: 3217 with localcontext() as c4:
3150 self.assertEqual(c4.prec, 4) 3218 self.assertEqual(c4.prec, 4)
3151 del c4 3219 del c4
3152 3220
3153 class CContextWithStatement(ContextWithStatement): 3221 class CContextWithStatement(ContextWithStatement):
3154 decimal = C 3222 decimal = C
3155 class PyContextWithStatement(ContextWithStatement): 3223 class PyContextWithStatement(ContextWithStatement):
3156 decimal = P 3224 decimal = P
3157 3225
3158 class ContextFlags(unittest.TestCase): 3226 class ContextFlags(unittest.TestCase):
3227
3159 def test_flags_irrelevant(self): 3228 def test_flags_irrelevant(self):
3160 # check that the result (numeric result + flags raised) of an 3229 # check that the result (numeric result + flags raised) of an
3161 # arithmetic operation doesn't depend on the current flags 3230 # arithmetic operation doesn't depend on the current flags
3162 Decimal = self.decimal.Decimal 3231 Decimal = self.decimal.Decimal
3163 Context = self.decimal.Context 3232 Context = self.decimal.Context
3164 Inexact = self.decimal.Inexact 3233 Inexact = self.decimal.Inexact
3165 Rounded = self.decimal.Rounded 3234 Rounded = self.decimal.Rounded
3166 Underflow = self.decimal.Underflow 3235 Underflow = self.decimal.Underflow
3167 Clamped = self.decimal.Clamped 3236 Clamped = self.decimal.Clamped
3168 Subnormal = self.decimal.Subnormal 3237 Subnormal = self.decimal.Subnormal
(...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after
3215 # flags we actually got 3284 # flags we actually got
3216 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]
3217 new_flags.sort(key=id) 3286 new_flags.sort(key=id)
3218 3287
3219 self.assertEqual(ans, new_ans, 3288 self.assertEqual(ans, new_ans,
3220 "operation produces different answers depending on flags set: " + 3289 "operation produces different answers depending on flags set: " +
3221 "expected %s, got %s." % (ans, new_ans)) 3290 "expected %s, got %s." % (ans, new_ans))
3222 self.assertEqual(new_flags, expected_flags, 3291 self.assertEqual(new_flags, expected_flags,
3223 "operation raises different flags depending on flags set: " + 3292 "operation raises different flags depending on flags set: " +
3224 "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)
3225 3332
3226 class CContextFlags(ContextFlags): 3333 class CContextFlags(ContextFlags):
3227 decimal = C 3334 decimal = C
3228 class PyContextFlags(ContextFlags): 3335 class PyContextFlags(ContextFlags):
3229 decimal = P 3336 decimal = P
3230 3337
3231 class SpecialContexts(unittest.TestCase): 3338 class SpecialContexts(unittest.TestCase):
3232 """Test the context templates.""" 3339 """Test the context templates."""
3233 3340
3234 def test_context_templates(self): 3341 def test_context_templates(self):
(...skipping 19 matching lines...) Expand all
3254 try: 3361 try:
3255 BasicContext.prec = ExtendedContext.prec = 441 3362 BasicContext.prec = ExtendedContext.prec = 441
3256 for template in BasicContext, ExtendedContext: 3363 for template in BasicContext, ExtendedContext:
3257 setcontext(template) 3364 setcontext(template)
3258 c = getcontext() 3365 c = getcontext()
3259 self.assertIsNot(c, template) 3366 self.assertIsNot(c, template)
3260 self.assertEqual(c.prec, 441) 3367 self.assertEqual(c.prec, 441)
3261 except Exception as e: 3368 except Exception as e:
3262 ex = e.__class__ 3369 ex = e.__class__
3263 finally: 3370 finally:
3264 with protectfail(): 3371 BasicContext.prec = basic_context_prec
3265 BasicContext.prec = basic_context_prec 3372 ExtendedContext.prec = extended_context_prec
3266 ExtendedContext.prec = extended_context_prec 3373 setcontext(savecontext)
3267 setcontext(savecontext)
3268 if ex: 3374 if ex:
3269 raise ex 3375 raise ex
3270 3376
3271 def test_default_context(self): 3377 def test_default_context(self):
3272 DefaultContext = self.decimal.DefaultContext 3378 DefaultContext = self.decimal.DefaultContext
3273 BasicContext = self.decimal.BasicContext 3379 BasicContext = self.decimal.BasicContext
3274 ExtendedContext = self.decimal.ExtendedContext 3380 ExtendedContext = self.decimal.ExtendedContext
3275 getcontext = self.decimal.getcontext 3381 getcontext = self.decimal.getcontext
3276 setcontext = self.decimal.setcontext 3382 setcontext = self.decimal.setcontext
3277 InvalidOperation = self.decimal.InvalidOperation 3383 InvalidOperation = self.decimal.InvalidOperation
(...skipping 19 matching lines...) Expand all
3297 c = getcontext() 3403 c = getcontext()
3298 self.assertEqual(c.prec, saveprec) 3404 self.assertEqual(c.prec, saveprec)
3299 3405
3300 setcontext(DefaultContext) 3406 setcontext(DefaultContext)
3301 c = getcontext() 3407 c = getcontext()
3302 self.assertIsNot(c, DefaultContext) 3408 self.assertIsNot(c, DefaultContext)
3303 self.assertEqual(c.prec, 961) 3409 self.assertEqual(c.prec, 961)
3304 except Exception as e: 3410 except Exception as e:
3305 ex = e.__class__ 3411 ex = e.__class__
3306 finally: 3412 finally:
3307 with protectfail(): 3413 DefaultContext.prec = default_context_prec
3308 DefaultContext.prec = default_context_prec 3414 setcontext(savecontext)
3309 setcontext(savecontext)
3310 if ex: 3415 if ex:
3311 raise ex 3416 raise ex
3312 3417
3313 class CSpecialContexts(SpecialContexts): 3418 class CSpecialContexts(SpecialContexts):
3314 decimal = C 3419 decimal = C
3315 class PySpecialContexts(SpecialContexts): 3420 class PySpecialContexts(SpecialContexts):
3316 decimal = P 3421 decimal = P
3317 3422
3318 class ContextInputValidation(unittest.TestCase): 3423 class ContextInputValidation(unittest.TestCase):
3319 3424
(...skipping 36 matching lines...) Expand 10 before | Expand all | Expand 10 after
3356 for attr in ['capitals', 'clamp']: 3461 for attr in ['capitals', 'clamp']:
3357 self.assertRaises(ValueError, setattr, c, attr, -1) 3462 self.assertRaises(ValueError, setattr, c, attr, -1)
3358 self.assertRaises(ValueError, setattr, c, attr, 2) 3463 self.assertRaises(ValueError, setattr, c, attr, 2)
3359 self.assertRaises(TypeError, setattr, c, attr, [1,2,3]) 3464 self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
3360 3465
3361 # Invalid attribute 3466 # Invalid attribute
3362 self.assertRaises(AttributeError, setattr, c, 'emax', 100) 3467 self.assertRaises(AttributeError, setattr, c, 'emax', 100)
3363 3468
3364 # Invalid signal dict 3469 # Invalid signal dict
3365 self.assertRaises(TypeError, setattr, c, 'flags', []) 3470 self.assertRaises(TypeError, setattr, c, 'flags', [])
3366 self.assertRaises(TypeError, setattr, c, 'flags', {}) 3471 self.assertRaises(KeyError, setattr, c, 'flags', {})
3367 self.assertRaises(TypeError, setattr, c, 'traps', 3472 self.assertRaises(KeyError, setattr, c, 'traps',
3368 {'InvalidOperation':0}) 3473 {'InvalidOperation':0})
3369 3474
3370 # Attributes cannot be deleted 3475 # Attributes cannot be deleted
3371 for attr in ['prec', 'Emax', 'Emin', 'rounding', 'capitals', 'clamp', 3476 for attr in ['prec', 'Emax', 'Emin', 'rounding', 'capitals', 'clamp',
3372 'flags', 'traps']: 3477 'flags', 'traps']:
3373 self.assertRaises(AttributeError, c.__delattr__, attr) 3478 self.assertRaises(AttributeError, c.__delattr__, attr)
3374 3479
3375 # Invalid attributes 3480 # Invalid attributes
3376 self.assertRaises(TypeError, getattr, c, 9) 3481 self.assertRaises(TypeError, getattr, c, 9)
3377 self.assertRaises(TypeError, setattr, c, 9) 3482 self.assertRaises(TypeError, setattr, c, 9)
3378 3483
3379 # Invalid values in constructor 3484 # Invalid values in constructor
3380 self.assertRaises(TypeError, Context, rounding=999999) 3485 self.assertRaises(TypeError, Context, rounding=999999)
3381 self.assertRaises(TypeError, Context, rounding='xyz') 3486 self.assertRaises(TypeError, Context, rounding='xyz')
3382 self.assertRaises(ValueError, Context, clamp=2) 3487 self.assertRaises(ValueError, Context, clamp=2)
3383 self.assertRaises(ValueError, Context, capitals=-1) 3488 self.assertRaises(ValueError, Context, capitals=-1)
3384 self.assertRaises(TypeError, Context, flags=["P"]) 3489 self.assertRaises(KeyError, Context, flags=["P"])
3385 self.assertRaises(TypeError, Context, traps=["Q"]) 3490 self.assertRaises(KeyError, Context, traps=["Q"])
3386 3491
3387 # Type error in conversion 3492 # Type error in conversion
3388 self.assertRaises(TypeError, Context, flags=(0,1)) 3493 self.assertRaises(TypeError, Context, flags=(0,1))
3389 self.assertRaises(TypeError, Context, traps=(1,0)) 3494 self.assertRaises(TypeError, Context, traps=(1,0))
3390 3495
3391 class CContextInputValidation(ContextInputValidation): 3496 class CContextInputValidation(ContextInputValidation):
3392 decimal = C 3497 decimal = C
3393 class PyContextInputValidation(ContextInputValidation): 3498 class PyContextInputValidation(ContextInputValidation):
3394 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())
3395 3531
3396 class Coverage(unittest.TestCase): 3532 class Coverage(unittest.TestCase):
3397 3533
3398 def test_adjusted(self): 3534 def test_adjusted(self):
3399 Decimal = self.decimal.Decimal 3535 Decimal = self.decimal.Decimal
3400 3536
3401 self.assertEqual(Decimal('1234e9999').adjusted(), 10002) 3537 self.assertEqual(Decimal('1234e9999').adjusted(), 10002)
3402 # XXX raise? 3538 # XXX raise?
3403 self.assertEqual(Decimal('nan').adjusted(), 0) 3539 self.assertEqual(Decimal('nan').adjusted(), 0)
3404 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
3535 c.traps[InvalidOperation] = False 3671 c.traps[InvalidOperation] = False
3536 c.clear_flags() 3672 c.clear_flags()
3537 q, r = divmod(Decimal("inf"), Decimal("inf")) 3673 q, r = divmod(Decimal("inf"), Decimal("inf"))
3538 self.assertTrue(q.is_nan() and r.is_nan()) 3674 self.assertTrue(q.is_nan() and r.is_nan())
3539 self.assertTrue(c.flags[InvalidOperation]) 3675 self.assertTrue(c.flags[InvalidOperation])
3540 3676
3541 c.clear_flags() 3677 c.clear_flags()
3542 q, r = divmod(Decimal("inf"), 101) 3678 q, r = divmod(Decimal("inf"), 101)
3543 self.assertTrue(q.is_infinite() and r.is_nan()) 3679 self.assertTrue(q.is_infinite() and r.is_nan())
3544 self.assertTrue(c.flags[InvalidOperation]) 3680 self.assertTrue(c.flags[InvalidOperation])
3545 3681
3546 c.clear_flags() 3682 c.clear_flags()
3547 q, r = divmod(Decimal(0), 0) 3683 q, r = divmod(Decimal(0), 0)
3548 self.assertTrue(q.is_nan() and r.is_nan()) 3684 self.assertTrue(q.is_nan() and r.is_nan())
3549 self.assertTrue(c.flags[InvalidOperation]) 3685 self.assertTrue(c.flags[InvalidOperation])
3550 3686
3551 c.traps[DivisionByZero] = False 3687 c.traps[DivisionByZero] = False
3552 c.clear_flags() 3688 c.clear_flags()
3553 q, r = divmod(Decimal(11), 0) 3689 q, r = divmod(Decimal(11), 0)
3554 self.assertTrue(q.is_infinite() and r.is_nan()) 3690 self.assertTrue(q.is_infinite() and r.is_nan())
3555 self.assertTrue(c.flags[InvalidOperation] and 3691 self.assertTrue(c.flags[InvalidOperation] and
3556 c.flags[DivisionByZero]) 3692 c.flags[DivisionByZero])
3557 3693
3558 def test_power(self): 3694 def test_power(self):
3559 Decimal = self.decimal.Decimal 3695 Decimal = self.decimal.Decimal
3560 localcontext = self.decimal.localcontext 3696 localcontext = self.decimal.localcontext
(...skipping 27 matching lines...) Expand all
3588 x = Decimal(99).quantize(Decimal("1e1")) 3724 x = Decimal(99).quantize(Decimal("1e1"))
3589 self.assertTrue(x.is_nan()) 3725 self.assertTrue(x.is_nan())
3590 3726
3591 def test_radix(self): 3727 def test_radix(self):
3592 Decimal = self.decimal.Decimal 3728 Decimal = self.decimal.Decimal
3593 getcontext = self.decimal.getcontext 3729 getcontext = self.decimal.getcontext
3594 3730
3595 c = getcontext() 3731 c = getcontext()
3596 self.assertEqual(Decimal("1").radix(), 10) 3732 self.assertEqual(Decimal("1").radix(), 10)
3597 self.assertEqual(c.radix(), 10) 3733 self.assertEqual(c.radix(), 10)
3598 3734
3599 def test_rop(self): 3735 def test_rop(self):
3600 Decimal = self.decimal.Decimal 3736 Decimal = self.decimal.Decimal
3601 3737
3602 for attr in ('__radd__', '__rsub__', '__rmul__', '__rtruediv__', 3738 for attr in ('__radd__', '__rsub__', '__rmul__', '__rtruediv__',
3603 '__rdivmod__', '__rmod__', '__rfloordiv__', '__rpow__'): 3739 '__rdivmod__', '__rmod__', '__rfloordiv__', '__rpow__'):
3604 self.assertIs(getattr(Decimal("1"), attr)("xyz"), NotImplemented) 3740 self.assertIs(getattr(Decimal("1"), attr)("xyz"), NotImplemented)
3605 3741
3606 def test_round(self): 3742 def test_round(self):
3607 # Python3 behavior: round() returns Decimal 3743 # Python3 behavior: round() returns Decimal
3608 Decimal = self.decimal.Decimal 3744 Decimal = self.decimal.Decimal
(...skipping 213 matching lines...) Expand 10 before | Expand all | Expand 10 after
3822 def test_py__round(self): 3958 def test_py__round(self):
3823 # Coverage 3959 # Coverage
3824 Decimal = P.Decimal 3960 Decimal = P.Decimal
3825 ROUND_UP = P.ROUND_UP 3961 ROUND_UP = P.ROUND_UP
3826 3962
3827 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP) 3963 self.assertRaises(ValueError, Decimal("3.1234")._round, 0, ROUND_UP)
3828 3964
3829 class CFunctionality(unittest.TestCase): 3965 class CFunctionality(unittest.TestCase):
3830 """Extra functionality in _decimal""" 3966 """Extra functionality in _decimal"""
3831 3967
3968 @requires_extra_functionality
3832 def test_c_ieee_context(self): 3969 def test_c_ieee_context(self):
3833 # issue 8786: Add support for IEEE 754 contexts to decimal module. 3970 # issue 8786: Add support for IEEE 754 contexts to decimal module.
3834 IEEEContext = C.IEEEContext 3971 IEEEContext = C.IEEEContext
3835 DECIMAL32 = C.DECIMAL32 3972 DECIMAL32 = C.DECIMAL32
3836 DECIMAL64 = C.DECIMAL64 3973 DECIMAL64 = C.DECIMAL64
3837 DECIMAL128 = C.DECIMAL128 3974 DECIMAL128 = C.DECIMAL128
3838 3975
3839 def assert_rest(self, context): 3976 def assert_rest(self, context):
3840 self.assertEqual(context.clamp, 1) 3977 self.assertEqual(context.clamp, 1)
3841 assert_signals(self, context, 'traps', []) 3978 assert_signals(self, context, 'traps', [])
(...skipping 14 matching lines...) Expand all
3856 c = IEEEContext(DECIMAL128) 3993 c = IEEEContext(DECIMAL128)
3857 self.assertEqual(c.prec, 34) 3994 self.assertEqual(c.prec, 34)
3858 self.assertEqual(c.Emax, 6144) 3995 self.assertEqual(c.Emax, 6144)
3859 self.assertEqual(c.Emin, -6143) 3996 self.assertEqual(c.Emin, -6143)
3860 assert_rest(self, c) 3997 assert_rest(self, c)
3861 3998
3862 # Invalid values 3999 # Invalid values
3863 self.assertRaises(OverflowError, IEEEContext, 2**63) 4000 self.assertRaises(OverflowError, IEEEContext, 2**63)
3864 self.assertRaises(ValueError, IEEEContext, -1) 4001 self.assertRaises(ValueError, IEEEContext, -1)
3865 self.assertRaises(ValueError, IEEEContext, 1024) 4002 self.assertRaises(ValueError, IEEEContext, 1024)
3866
3867 def test_apply(self):
3868 # Decimal("9.9999999").apply() applies the current context.
3869 Decimal = C.Decimal
3870 localcontext = C.localcontext
3871
3872 with localcontext() as c:
3873 c.prec = 5
3874 c.Emax = 99999
3875 c.Emin = -99999
3876
3877 d = c.copy()
3878 d.prec = 4
3879
3880 x = Decimal("123456")
3881 self.assertEqual(str(x.apply()), "1.2346E+5")
3882 self.assertEqual(str(c.apply(x)), "1.2346E+5")
3883
3884 self.assertEqual(str(x.apply(d)), "1.235E+5")
3885 self.assertEqual(str(d.apply(x)), "1.235E+5")
3886
3887 self.assertRaises(TypeError, x.apply, "p")
3888 self.assertRaises(TypeError, x.apply, "p", "q")
3889 self.assertRaises(TypeError, c.apply, "p")
3890
3891 x = Decimal(1171**2221)
3892 self.assertEqual(str(x.apply()), "1.8402E+6815")
3893 self.assertEqual(str(c.apply(x)), "1.8402E+6815")
3894 self.assertEqual(str(d.apply(x)), "1.840E+6815")
3895 4003
3896 @requires_IEEE_754 4004 @requires_IEEE_754
3897 def test_c_float_operation(self): 4005 def test_c_float_operation(self):
3898 Decimal = C.Decimal 4006 Decimal = C.Decimal
3899 FloatOperation= C.FloatOperation 4007 FloatOperation= C.FloatOperation
3900 localcontext = C.localcontext 4008 localcontext = C.localcontext
3901 4009
3902 with localcontext() as c: 4010 with localcontext() as c:
3903 c.clear_flags() 4011 c.clear_flags()
3904 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
4009 test_containers(c, sig) 4117 test_containers(c, sig)
4010 4118
4011 c.traps[FloatOperation] = True 4119 c.traps[FloatOperation] = True
4012 doit(c, signal=FloatOperation) 4120 doit(c, signal=FloatOperation)
4013 test_containers(c, FloatOperation) 4121 test_containers(c, FloatOperation)
4014 4122
4015 def test_c_float_operation_default(self): 4123 def test_c_float_operation_default(self):
4016 Decimal = C.Decimal 4124 Decimal = C.Decimal
4017 Context = C.Context 4125 Context = C.Context
4018 Inexact = C.Inexact 4126 Inexact = C.Inexact
4019 DecInexact = C.DecInexact
4020 FloatOperation= C.FloatOperation 4127 FloatOperation= C.FloatOperation
4021 DecFloatOperation= C.DecFloatOperation
4022 4128
4023 context = Context() 4129 context = Context()
4024 self.assertFalse(context.flags[FloatOperation]) 4130 self.assertFalse(context.flags[FloatOperation])
4025 self.assertFalse(context.traps[FloatOperation]) 4131 self.assertFalse(context.traps[FloatOperation])
4026 self.assertFalse(context._flags&DecFloatOperation) 4132
4027 self.assertFalse(context._traps&DecFloatOperation) 4133 context.clear_traps()
4028 4134 context.traps[Inexact] = True
4029 context.settraps([Inexact, FloatOperation]) 4135 context.traps[FloatOperation] = True
4030 self.assertEqual(context._traps, DecInexact|DecFloatOperation)
4031 self.assertTrue(context.traps[FloatOperation]) 4136 self.assertTrue(context.traps[FloatOperation])
4032 self.assertTrue(context.traps[Inexact]) 4137 self.assertTrue(context.traps[Inexact])
4033 4138
4034 def test_c_powmod(self): 4139 @requires_extra_functionality
4035 Decimal = C.Decimal
4036 Context = C.Context
4037
4038 c = Context()
4039 d = c.powmod(Decimal(1), Decimal(4), Decimal(2))
4040 self.assertEqual(c.powmod(1, 4, 2), d)
4041 self.assertEqual(c.powmod(Decimal(1), 4, 2), d)
4042 self.assertEqual(c.powmod(1, Decimal(4), 2), d)
4043 self.assertEqual(c.powmod(1, 4, Decimal(2)), d)
4044 self.assertEqual(c.powmod(Decimal(1), Decimal(4), 2), d)
4045 self.assertRaises(TypeError, c.powmod, '1', 4, 2)
4046 self.assertRaises(TypeError, c.powmod, 1, '4', 2)
4047 self.assertRaises(TypeError, c.powmod, 1, 4, '2')
4048
4049 def test_c_context(self): 4140 def test_c_context(self):
4050 Context = C.Context 4141 Context = C.Context
4051 4142
4052 c = Context(flags=C.DecClamped, traps=C.DecRounded) 4143 c = Context(flags=C.DecClamped, traps=C.DecRounded)
4053 self.assertEqual(c._flags, C.DecClamped) 4144 self.assertEqual(c._flags, C.DecClamped)
4054 self.assertEqual(c._traps, C.DecRounded) 4145 self.assertEqual(c._traps, C.DecRounded)
4055 4146
4056 def test_sundry(self): 4147 @requires_extra_functionality
4057 Decimal = C.Decimal
4058
4059 # mpd_isinteger
4060 self.assertTrue(Decimal("1.234e5").is_integer())
4061 self.assertTrue(Decimal("snan").is_special())
4062
4063 # Extra functions
4064 self.assertEqual(Decimal(-1).abs(), 1)
4065 self.assertEqual(Decimal(1).minus(), -1)
4066 self.assertEqual(Decimal(1).plus(), 1)
4067 self.assertEqual(Decimal(1).add(1), 2)
4068 self.assertEqual(Decimal(12).div(2), 6)
4069 self.assertEqual(Decimal(10).divint(7), 1)
4070 self.assertEqual(Decimal(10).mul(12), 120)
4071 self.assertEqual(Decimal(10).rem(7), 3)
4072 self.assertEqual(Decimal(10).sub(7), 3)
4073 self.assertEqual(Decimal(10).divmod(7), (1, 3))
4074
4075 def test_constants(self): 4148 def test_constants(self):
4076 # Condition flags 4149 # Condition flags
4077 cond = ( 4150 cond = (
4078 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero, 4151 C.DecClamped, C.DecConversionSyntax, C.DecDivisionByZero,
4079 C.DecDivisionImpossible, C.DecDivisionUndefined, 4152 C.DecDivisionImpossible, C.DecDivisionUndefined,
4080 C.DecFpuError, C.DecInexact, C.DecInvalidContext, 4153 C.DecFpuError, C.DecInexact, C.DecInvalidContext,
4081 C.DecInvalidOperation, C.DecMallocError, 4154 C.DecInvalidOperation, C.DecMallocError,
4082 C.DecFloatOperation, C.DecOverflow, C.DecRounded, 4155 C.DecFloatOperation, C.DecOverflow, C.DecRounded,
4083 C.DecSubnormal, C.DecUnderflow 4156 C.DecSubnormal, C.DecUnderflow
4084 ) 4157 )
4085 4158
4086 # Architecture dependent context limits 4159 # IEEEContext
4087 if C.MAX_EMAX > 425000000:
4088 self.assertEqual(C.MAX_PREC, 999999999999999999)
4089 self.assertEqual(C.MAX_EMAX, 999999999999999999)
4090 self.assertEqual(C.MIN_EMIN, -999999999999999999)
4091 self.assertEqual(C.MIN_ETINY, -1999999999999999997)
4092 else:
4093 self.assertEqual(C.MAX_PREC, 425000000)
4094 self.assertEqual(C.MAX_EMAX, 425000000)
4095 self.assertEqual(C.MIN_EMIN, -425000000)
4096 self.assertEqual(C.MIN_ETINY, -849999999)
4097
4098 » # IEEEContext
4099 self.assertEqual(C.DECIMAL32, 32) 4160 self.assertEqual(C.DECIMAL32, 32)
4100 self.assertEqual(C.DECIMAL64, 64) 4161 self.assertEqual(C.DECIMAL64, 64)
4101 self.assertEqual(C.DECIMAL128, 128) 4162 self.assertEqual(C.DECIMAL128, 128)
4102 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512) 4163 self.assertEqual(C.IEEE_CONTEXT_MAX_BITS, 512)
4103 4164
4104 # Rounding modes 4165 # Rounding modes
4105 for i, v in enumerate(RoundingModes[C]): 4166 for i, v in enumerate(RoundingModes[C]):
4106 self.assertEqual(v, i) 4167 self.assertEqual(v, i)
4107 self.assertEqual(C.ROUND_TRUNC, 8) 4168 self.assertEqual(C.ROUND_TRUNC, 8)
4108 4169
(...skipping 15 matching lines...) Expand all
4124 C.DecDivisionByZero) 4185 C.DecDivisionByZero)
4125 4186
4126 self.assertEqual(C.DecTraps, 4187 self.assertEqual(C.DecTraps,
4127 C.DecErrors|C.DecOverflow|C.DecUnderflow) 4188 C.DecErrors|C.DecOverflow|C.DecUnderflow)
4128 4189
4129 class CWhitebox(unittest.TestCase): 4190 class CWhitebox(unittest.TestCase):
4130 """Whitebox testing for _decimal""" 4191 """Whitebox testing for _decimal"""
4131 4192
4132 def test_bignum(self): 4193 def test_bignum(self):
4133 # Not exactly whitebox, but too slow with pydecimal. 4194 # Not exactly whitebox, but too slow with pydecimal.
4134 if hasattr(C, 'setfailpoint'):
4135 random.seed(randseed)
4136 4195
4137 Decimal = C.Decimal 4196 Decimal = C.Decimal
4138 localcontext = C.localcontext 4197 localcontext = C.localcontext
4139 4198
4140 b1 = 10**35 4199 b1 = 10**35
4141 b2 = 10**36 4200 b2 = 10**36
4142 with localcontext() as c: 4201 with localcontext() as c:
4143 c.prec = 1000000 4202 c.prec = 1000000
4144 r = 1 if hasattr(C, 'setfailpoint') else 5 4203 for i in range(5):
4145 for i in range(r):
4146 a = random.randrange(b1, b2) 4204 a = random.randrange(b1, b2)
4147 b = random.randrange(1000, 1200) 4205 b = random.randrange(1000, 1200)
4148 x = a ** b 4206 x = a ** b
4149 y = Decimal(a) ** Decimal(b) 4207 y = Decimal(a) ** Decimal(b)
4150 self.assertEqual(x, y) 4208 self.assertEqual(x, y)
4209
4210 def test_invalid_construction(self):
4211 self.assertRaises(TypeError, C.Decimal, 9, "xyz")
4151 4212
4152 def test_c_input_restriction(self): 4213 def test_c_input_restriction(self):
4153 # Too large for _decimal to be converted exactly 4214 # Too large for _decimal to be converted exactly
4154 Decimal = C.Decimal 4215 Decimal = C.Decimal
4155 InvalidOperation = C.InvalidOperation 4216 InvalidOperation = C.InvalidOperation
4156 Context = C.Context 4217 Context = C.Context
4157 localcontext = C.localcontext 4218 localcontext = C.localcontext
4158 4219
4159 with localcontext(Context()): 4220 with localcontext(Context()):
4160 self.assertRaises(InvalidOperation, Decimal, 4221 self.assertRaises(InvalidOperation, Decimal,
(...skipping 26 matching lines...) Expand all
4187 "flags=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \ 4248 "flags=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \
4188 "FloatOperation, Overflow, Rounded, Subnormal, Underflow], " \ 4249 "FloatOperation, Overflow, Rounded, Subnormal, Underflow], " \
4189 "traps=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \ 4250 "traps=[Clamped, InvalidOperation, DivisionByZero, Inexact, " \
4190 "FloatOperation, Overflow, Rounded, Subnormal, Underflow])" 4251 "FloatOperation, Overflow, Rounded, Subnormal, Underflow])"
4191 self.assertEqual(s, t) 4252 self.assertEqual(s, t)
4192 4253
4193 def test_c_context_errors(self): 4254 def test_c_context_errors(self):
4194 Context = C.Context 4255 Context = C.Context
4195 InvalidOperation = C.InvalidOperation 4256 InvalidOperation = C.InvalidOperation
4196 Overflow = C.Overflow 4257 Overflow = C.Overflow
4258 localcontext = C.localcontext
4259 getcontext = C.getcontext
4260 setcontext = C.setcontext
4197 HAVE_CONFIG_64 = (C.MAX_PREC > 425000000) 4261 HAVE_CONFIG_64 = (C.MAX_PREC > 425000000)
4198 4262
4199 c = Context() 4263 c = Context()
4200 4264
4201 # SignalDict: input validation 4265 # SignalDict: input validation
4202 self.assertRaises(TypeError, c.flags.__setitem__, 801, 0) 4266 self.assertRaises(KeyError, c.flags.__setitem__, 801, 0)
4203 self.assertRaises(TypeError, c.traps.__setitem__, 801, 0) 4267 self.assertRaises(KeyError, c.traps.__setitem__, 801, 0)
4204 self.assertRaises(ValueError, c.flags.__delitem__, Overflow) 4268 self.assertRaises(ValueError, c.flags.__delitem__, Overflow)
4205 self.assertRaises(ValueError, c.traps.__delitem__, InvalidOperation) 4269 self.assertRaises(ValueError, c.traps.__delitem__, InvalidOperation)
4206 self.assertRaises(TypeError, setattr, c, 'flags', ['x']) 4270 self.assertRaises(TypeError, setattr, c, 'flags', ['x'])
4207 self.assertRaises(TypeError, setattr, c,'traps', ['y']) 4271 self.assertRaises(TypeError, setattr, c,'traps', ['y'])
4208 self.assertRaises(TypeError, setattr, c, 'flags', {0:1}) 4272 self.assertRaises(KeyError, setattr, c, 'flags', {0:1})
4209 self.assertRaises(TypeError, setattr, c, 'traps', {0:1}) 4273 self.assertRaises(KeyError, setattr, c, 'traps', {0:1})
4210
4211 self.assertRaises(TypeError, c.setflags, ['x'])
4212 self.assertRaises(TypeError, c.settraps, ['y'])
4213 self.assertRaises(TypeError, c.setflags, 'x')
4214 self.assertRaises(TypeError, c.settraps, 'y')
4215 4274
4216 # Input corner cases 4275 # Input corner cases
4217 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
4218 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
4219 4278
4220 # prec, Emax, Emin 4279 # prec, Emax, Emin
4221 for attr in ['prec', 'Emax']: 4280 for attr in ['prec', 'Emax']:
4222 self.assertRaises(ValueError, setattr, c, attr, gt_max_emax) 4281 self.assertRaises(ValueError, setattr, c, attr, gt_max_emax)
4223 self.assertRaises(ValueError, setattr, c, 'Emin', -gt_max_emax) 4282 self.assertRaises(ValueError, setattr, c, 'Emin', -gt_max_emax)
4224 4283
4225 # prec, Emax, Emin in context constructor 4284 # prec, Emax, Emin in context constructor
4226 self.assertRaises(ValueError, Context, prec=gt_max_emax) 4285 self.assertRaises(ValueError, Context, prec=gt_max_emax)
4227 self.assertRaises(ValueError, Context, Emax=gt_max_emax) 4286 self.assertRaises(ValueError, Context, Emax=gt_max_emax)
4228 self.assertRaises(ValueError, Context, Emin=-gt_max_emax) 4287 self.assertRaises(ValueError, Context, Emin=-gt_max_emax)
4229 4288
4230 # Overflow in conversion 4289 # Overflow in conversion
4231 self.assertRaises(OverflowError, Context, prec=int_max+1) 4290 self.assertRaises(OverflowError, Context, prec=int_max+1)
4232 self.assertRaises(OverflowError, Context, Emax=int_max+1) 4291 self.assertRaises(OverflowError, Context, Emax=int_max+1)
4233 self.assertRaises(OverflowError, Context, Emin=-int_max-2) 4292 self.assertRaises(OverflowError, Context, Emin=-int_max-2)
4234 self.assertRaises(OverflowError, Context, rounding=int_max+1) 4293 self.assertRaises(OverflowError, Context, rounding=int_max+1)
4235 self.assertRaises(OverflowError, Context, clamp=int_max+1) 4294 self.assertRaises(OverflowError, Context, clamp=int_max+1)
4236 self.assertRaises(OverflowError, Context, capitals=int_max+1) 4295 self.assertRaises(OverflowError, Context, capitals=int_max+1)
4237 self.assertRaises(OverflowError, Context, _allcr=int_max+1) 4296 self.assertRaises(OverflowError, Context, _allcr=int_max+1)
4238 4297
4239 # OverflowError, general ValueError 4298 # OverflowError, general ValueError
4240 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp', '_allcr'): 4299 for attr in ('prec', 'Emin', 'Emax', 'capitals', 'clamp'):
4241 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4300 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4242 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4301 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4243 if sys.platform != 'win32': 4302 if sys.platform != 'win32':
4244 self.assertRaises(ValueError, setattr, c, attr, int_max) 4303 self.assertRaises(ValueError, setattr, c, attr, int_max)
4245 self.assertRaises(ValueError, setattr, c, attr, -int_max-1) 4304 self.assertRaises(ValueError, setattr, c, attr, -int_max-1)
4246 4305
4247 # OverflowError, general TypeError 4306 # OverflowError, general TypeError
4248 for attr in ('rounding', '_flags', '_traps'): 4307 for attr in ('rounding',):
4249 self.assertRaises(OverflowError, setattr, c, attr, int_max+1) 4308 self.assertRaises(OverflowError, setattr, c, attr, int_max+1)
4250 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2) 4309 self.assertRaises(OverflowError, setattr, c, attr, -int_max-2)
4251 if sys.platform != 'win32': 4310 if sys.platform != 'win32':
4252 self.assertRaises(TypeError, setattr, c, attr, int_max) 4311 self.assertRaises(TypeError, setattr, c, attr, int_max)
4253 self.assertRaises(TypeError, setattr, c, attr, -int_max-1) 4312 self.assertRaises(TypeError, setattr, c, attr, -int_max-1)
4254 4313
4255 # OverflowError: unsafe_prec, unsafe_emin, unsafe_emax 4314 # OverflowError: _unsafe_setprec, _unsafe_setemin, _unsafe_setemax
4256 self.assertRaises(OverflowError, getattr(c, 'unsafe_setprec'), int_max+1 ) 4315 if C.MAX_PREC == 425000000:
4257 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemax'), int_max+1 ) 4316 self.assertRaises(OverflowError, getattr(c, '_unsafe_setprec'),
4258 self.assertRaises(OverflowError, getattr(c, 'unsafe_setemin'), -int_max- 2) 4317 int_max+1)
4259 4318 self.assertRaises(OverflowError, getattr(c, '_unsafe_setemax'),
4260 # capitals, clamp, _allcr 4319 int_max+1)
4261 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']:
4262 self.assertRaises(ValueError, setattr, c, attr, -1) 4337 self.assertRaises(ValueError, setattr, c, attr, -1)
4263 self.assertRaises(ValueError, setattr, c, attr, 2) 4338 self.assertRaises(ValueError, setattr, c, attr, 2)
4264 self.assertRaises(TypeError, setattr, c, attr, [1,2,3]) 4339 self.assertRaises(TypeError, setattr, c, attr, [1,2,3])
4265 if HAVE_CONFIG_64: 4340 if HAVE_CONFIG_64:
4266 self.assertRaises(ValueError, setattr, c, attr, 2**32) 4341 self.assertRaises(ValueError, setattr, c, attr, 2**32)
4267 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)
4268 4390
4269 self.assertRaises(ValueError, Context, _allcr=2) 4391 self.assertRaises(ValueError, Context, _allcr=2)
4270 4392
4271 # _flags, _traps 4393 # _flags, _traps
4272 for attr in ['_flags', '_traps']: 4394 for attr in ['_flags', '_traps']:
4273 self.assertRaises(TypeError, setattr, c, attr, 999999) 4395 self.assertRaises(TypeError, setattr, c, attr, 999999)
4274 self.assertRaises(TypeError, setattr, c, attr, 'x') 4396 self.assertRaises(TypeError, setattr, c, attr, 'x')
4275 4397
4276 def test_c_valid_context(self): 4398 def test_c_valid_context(self):
4277 # These tests are for code coverage in _decimal. 4399 # These tests are for code coverage in _decimal.
4278 DefaultContext = C.DefaultContext 4400 DefaultContext = C.DefaultContext
4279 ROUND_HALF_UP = C.ROUND_HALF_UP 4401 ROUND_HALF_UP = C.ROUND_HALF_UP
4280 Clamped = C.Clamped 4402 Clamped = C.Clamped
4281 Underflow = C.Underflow 4403 Underflow = C.Underflow
4282 Inexact = C.Inexact 4404 Inexact = C.Inexact
4283 Rounded = C.Rounded 4405 Rounded = C.Rounded
4284 Subnormal = C.Subnormal 4406 Subnormal = C.Subnormal
4285 DecClamped = C.DecClamped
4286 DecUnderflow = C.DecUnderflow
4287 DecInexact = C.DecInexact
4288 DecRounded = C.DecRounded
4289 DecSubnormal = C.DecSubnormal
4290 4407
4291 c = DefaultContext.copy() 4408 c = DefaultContext.copy()
4292 4409
4293 # Exercise all getters and setters 4410 # Exercise all getters and setters
4294 c.prec = 34 4411 c.prec = 34
4295 c.rounding = ROUND_HALF_UP 4412 c.rounding = ROUND_HALF_UP
4296 c.Emax = 3000 4413 c.Emax = 3000
4297 c.Emin = -3000 4414 c.Emin = -3000
4298 c.capitals = 1 4415 c.capitals = 1
4299 c.clamp = 0 4416 c.clamp = 0
4300 c._flags = DecUnderflow
4301 c._traps = DecClamped
4302 c._allcr = 0
4303 4417
4304 self.assertEqual(c.prec, 34) 4418 self.assertEqual(c.prec, 34)
4305 self.assertEqual(c.rounding, ROUND_HALF_UP) 4419 self.assertEqual(c.rounding, ROUND_HALF_UP)
4306 self.assertEqual(c.Emin, -3000) 4420 self.assertEqual(c.Emin, -3000)
4307 self.assertEqual(c.Emax, 3000) 4421 self.assertEqual(c.Emax, 3000)
4308 self.assertEqual(c.capitals, 1) 4422 self.assertEqual(c.capitals, 1)
4309 self.assertEqual(c.clamp, 0) 4423 self.assertEqual(c.clamp, 0)
4310 self.assertEqual(c._flags, DecUnderflow)
4311 self.assertEqual(c._traps, DecClamped)
4312 self.assertEqual(c._allcr, 0)
4313 4424
4314 self.assertEqual(c.Etiny(), -3033) 4425 self.assertEqual(c.Etiny(), -3033)
4315 self.assertEqual(c.Etop(), 2967) 4426 self.assertEqual(c.Etop(), 2967)
4316 4427
4317 # Set traps/flags from list
4318 c.settraps([Clamped, Underflow])
4319 self.assertEqual(c._traps, DecClamped|DecUnderflow)
4320
4321 c.setflags([Inexact, Rounded, Subnormal])
4322 self.assertEqual(c._flags, DecInexact|DecRounded|DecSubnormal)
4323
4324 # Exercise all unsafe setters 4428 # Exercise all unsafe setters
4325 c.unsafe_setprec(999999999) 4429 if C.MAX_PREC == 425000000:
4326 c.unsafe_setemax(999999999) 4430 c._unsafe_setprec(999999999)
4327 c.unsafe_setemin(-999999999) 4431 c._unsafe_setemax(999999999)
4328 4432 c._unsafe_setemin(-999999999)
4329 self.assertEqual(c.prec, 999999999) 4433 self.assertEqual(c.prec, 999999999)
4330 self.assertEqual(c.Emax, 999999999) 4434 self.assertEqual(c.Emax, 999999999)
4331 self.assertEqual(c.Emin, -999999999) 4435 self.assertEqual(c.Emin, -999999999)
4332 4436
4333 def test_c_round(self): 4437 def test_c_round(self):
4334 # Restricted input. 4438 # Restricted input.
4335 Decimal = C.Decimal 4439 Decimal = C.Decimal
4336 InvalidOperation = C.InvalidOperation 4440 InvalidOperation = C.InvalidOperation
4337 localcontext = C.localcontext 4441 localcontext = C.localcontext
4338 MAX_EMAX = C.MAX_EMAX 4442 MAX_EMAX = C.MAX_EMAX
4339 MIN_ETINY = C.MIN_ETINY 4443 MIN_ETINY = C.MIN_ETINY
4340 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
4341 4445
(...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after
4408 4512
4409 def test_c_funcs(self): 4513 def test_c_funcs(self):
4410 # Invalid arguments 4514 # Invalid arguments
4411 Decimal = C.Decimal 4515 Decimal = C.Decimal
4412 InvalidOperation = C.InvalidOperation 4516 InvalidOperation = C.InvalidOperation
4413 DivisionByZero = C.DivisionByZero 4517 DivisionByZero = C.DivisionByZero
4414 ROUND_UP = C.ROUND_UP 4518 ROUND_UP = C.ROUND_UP
4415 getcontext = C.getcontext 4519 getcontext = C.getcontext
4416 localcontext = C.localcontext 4520 localcontext = C.localcontext
4417 4521
4418 self.assertEqual(Decimal('9.99e10').to_sci_string(), '9.99E+10')
4419 self.assertEqual(Decimal('9.99e10').to_eng_string(), '99.9E+9') 4522 self.assertEqual(Decimal('9.99e10').to_eng_string(), '99.9E+9')
4420 4523
4421 self.assertRaises(TypeError, pow, Decimal(1), 2, "3") 4524 self.assertRaises(TypeError, pow, Decimal(1), 2, "3")
4422 self.assertRaises(TypeError, Decimal(9).number_class, "x", "y") 4525 self.assertRaises(TypeError, Decimal(9).number_class, "x", "y")
4423 self.assertRaises(TypeError, Decimal(9).divmod, 8, "x", "y")
4424 self.assertRaises(TypeError, Decimal(9).same_quantum, 3, "x", "y") 4526 self.assertRaises(TypeError, Decimal(9).same_quantum, 3, "x", "y")
4425 self.assertRaises(TypeError, Decimal(9).to_sci, 3, "x", "y")
4426 self.assertRaises(TypeError, Decimal(9).to_eng, 3, "x", "y")
4427
4428 self.assertEqual(Decimal("1.234e2007").sign(), 1)
4429 self.assertEqual(Decimal("-1.234e2007").sign(), -1)
4430 4527
4431 self.assertRaises( 4528 self.assertRaises(
4432 TypeError, 4529 TypeError,
4433 Decimal("1.23456789").quantize, Decimal('1e-100000'), [] 4530 Decimal("1.23456789").quantize, Decimal('1e-100000'), []
4434 ) 4531 )
4435 self.assertRaises( 4532 self.assertRaises(
4436 TypeError, 4533 TypeError,
4437 Decimal("1.23456789").quantize, Decimal('1e-100000'), getcontext() 4534 Decimal("1.23456789").quantize, Decimal('1e-100000'), getcontext()
4438 ) 4535 )
4439 self.assertRaises( 4536 self.assertRaises(
(...skipping 13 matching lines...) Expand all
4453 self.assertRaises(TypeError, c.canonical, 200) 4550 self.assertRaises(TypeError, c.canonical, 200)
4454 self.assertRaises(TypeError, c.is_canonical, 200) 4551 self.assertRaises(TypeError, c.is_canonical, 200)
4455 self.assertRaises(TypeError, c.divmod, 9, 8, "x", "y") 4552 self.assertRaises(TypeError, c.divmod, 9, 8, "x", "y")
4456 self.assertRaises(TypeError, c.same_quantum, 9, 3, "x", "y") 4553 self.assertRaises(TypeError, c.same_quantum, 9, 3, "x", "y")
4457 4554
4458 self.assertEqual(str(c.canonical(Decimal(200))), '200') 4555 self.assertEqual(str(c.canonical(Decimal(200))), '200')
4459 self.assertEqual(c.radix(), 10) 4556 self.assertEqual(c.radix(), 10)
4460 4557
4461 c.traps[DivisionByZero] = True 4558 c.traps[DivisionByZero] = True
4462 self.assertRaises(DivisionByZero, Decimal(9).__divmod__, 0) 4559 self.assertRaises(DivisionByZero, Decimal(9).__divmod__, 0)
4463 self.assertRaises(DivisionByZero, Decimal(9).divmod, 0)
4464 self.assertRaises(DivisionByZero, c.divmod, 9, 0) 4560 self.assertRaises(DivisionByZero, c.divmod, 9, 0)
4465 self.assertTrue(c.flags[InvalidOperation]) 4561 self.assertTrue(c.flags[InvalidOperation])
4466 4562
4467 c.clear_flags() 4563 c.clear_flags()
4468 c.traps[InvalidOperation] = True 4564 c.traps[InvalidOperation] = True
4469 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0) 4565 self.assertRaises(InvalidOperation, Decimal(9).__divmod__, 0)
4470 self.assertRaises(InvalidOperation, Decimal(9).divmod, 0)
4471 self.assertRaises(InvalidOperation, c.divmod, 9, 0) 4566 self.assertRaises(InvalidOperation, c.divmod, 9, 0)
4472 self.assertTrue(c.flags[DivisionByZero]) 4567 self.assertTrue(c.flags[DivisionByZero])
4473 4568
4474 c.traps[InvalidOperation] = True 4569 c.traps[InvalidOperation] = True
4475 c.prec = 2 4570 c.prec = 2
4476 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501) 4571 self.assertRaises(InvalidOperation, pow, Decimal(1000), 1, 501)
4477 4572
4478 c.prec = 10 4573 @requires_extra_functionality
4479 x = Decimal(2).invroot()
4480 self.assertEqual(str(x), '0.7071067812')
4481
4482 x = c.invroot(3)
4483 self.assertEqual(str(x), '0.5773502692')
4484
4485 c.prec = 28
4486 x = Decimal(2).power(8)
4487 self.assertEqual(str(x), '256')
4488
4489 x = Decimal(2).powmod(8, 31)
4490 self.assertEqual(str(x), '8')
4491
4492 def test_c_context_templates(self): 4574 def test_c_context_templates(self):
4493 self.assertEqual( 4575 self.assertEqual(
4494 C.BasicContext._traps, 4576 C.BasicContext._traps,
4495 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow| 4577 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow|
4496 C.DecUnderflow|C.DecClamped 4578 C.DecUnderflow|C.DecClamped
4497 ) 4579 )
4498 self.assertEqual( 4580 self.assertEqual(
4499 C.DefaultContext._traps, 4581 C.DefaultContext._traps,
4500 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow 4582 C.DecIEEEInvalidOperation|C.DecDivisionByZero|C.DecOverflow
4501 ) 4583 )
4502 4584
4585 @requires_extra_functionality
4503 def test_c_signal_dict(self): 4586 def test_c_signal_dict(self):
4504 if hasattr(C, 'setfailpoint'):
4505 random.seed(randseed)
4506 4587
4507 # SignalDict coverage 4588 # SignalDict coverage
4508 Context = C.Context 4589 Context = C.Context
4509 DefaultContext = C.DefaultContext 4590 DefaultContext = C.DefaultContext
4510 4591
4511 InvalidOperation = C.InvalidOperation 4592 InvalidOperation = C.InvalidOperation
4512 DivisionByZero = C.DivisionByZero 4593 DivisionByZero = C.DivisionByZero
4513 Overflow = C.Overflow 4594 Overflow = C.Overflow
4514 Subnormal = C.Subnormal 4595 Subnormal = C.Subnormal
4515 Underflow = C.Underflow 4596 Underflow = C.Underflow
4516 Rounded = C.Rounded 4597 Rounded = C.Rounded
4517 Inexact = C.Inexact 4598 Inexact = C.Inexact
4518 Clamped = C.Clamped 4599 Clamped = C.Clamped
4519 4600
4520 DecClamped = C.DecClamped 4601 DecClamped = C.DecClamped
4521 DecInvalidOperation = C.DecInvalidOperation 4602 DecInvalidOperation = C.DecInvalidOperation
4522 DecIEEEInvalidOperation = C.DecIEEEInvalidOperation 4603 DecIEEEInvalidOperation = C.DecIEEEInvalidOperation
4523 4604
4524 def assertIsExclusivelySet(signal, signal_dict): 4605 def assertIsExclusivelySet(signal, signal_dict):
4525 for sig in signal_dict: 4606 for sig in signal_dict:
4526 if sig == signal: 4607 if sig == signal:
4527 self.assertTrue(signal_dict[sig]) 4608 self.assertTrue(signal_dict[sig])
4528 else: 4609 else:
4529 self.assertFalse(signal_dict[sig]) 4610 self.assertFalse(signal_dict[sig])
4530 4611
4531 c = DefaultContext.copy() 4612 c = DefaultContext.copy()
4532 4613
4533 # Signal dict methods 4614 # Signal dict methods
4534 self.assertTrue(Overflow in c.traps) 4615 self.assertTrue(Overflow in c.traps)
4535 self.assertTrue(c.traps.has_key(Overflow))
4536 c.clear_traps() 4616 c.clear_traps()
4537 for k in c.traps.keys(): 4617 for k in c.traps.keys():
4538 c.traps[k] = True 4618 c.traps[k] = True
4539 for v in c.traps.values(): 4619 for v in c.traps.values():
4540 self.assertTrue(v) 4620 self.assertTrue(v)
4541 c.clear_traps() 4621 c.clear_traps()
4542 for k, v in c.traps.items(): 4622 for k, v in c.traps.items():
4543 self.assertFalse(v) 4623 self.assertFalse(v)
4544 4624
4545 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
4584 Overflow: C.DecOverflow, 4664 Overflow: C.DecOverflow,
4585 DivisionByZero: C.DecDivisionByZero, 4665 DivisionByZero: C.DecDivisionByZero,
4586 InvalidOperation: C.DecIEEEInvalidOperation 4666 InvalidOperation: C.DecIEEEInvalidOperation
4587 } 4667 }
4588 IntCond = [ 4668 IntCond = [
4589 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError, 4669 C.DecDivisionImpossible, C.DecDivisionUndefined, C.DecFpuError,
4590 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError, 4670 C.DecInvalidContext, C.DecInvalidOperation, C.DecMallocError,
4591 C.DecConversionSyntax, 4671 C.DecConversionSyntax,
4592 ] 4672 ]
4593 4673
4594 lim = 1 if hasattr(C, 'setfailpoint') else len(OrderedSignals[C]) 4674 lim = len(OrderedSignals[C])
4595 for r in range(lim): 4675 for r in range(lim):
4596 for t in range(lim): 4676 for t in range(lim):
4597 for round in RoundingModes[C]: 4677 for round in RoundingModes[C]:
4598 flags = random.sample(OrderedSignals[C], r) 4678 flags = random.sample(OrderedSignals[C], r)
4599 traps = random.sample(OrderedSignals[C], t) 4679 traps = random.sample(OrderedSignals[C], t)
4600 prec = random.randrange(1, 10000) 4680 prec = random.randrange(1, 10000)
4601 emin = random.randrange(-10000, 0) 4681 emin = random.randrange(-10000, 0)
4602 emax = random.randrange(0, 10000) 4682 emax = random.randrange(0, 10000)
4603 clamp = random.randrange(0, 2) 4683 clamp = random.randrange(0, 2)
4604 caps = random.randrange(0, 2) 4684 caps = random.randrange(0, 2)
(...skipping 22 matching lines...) Expand all
4627 4707
4628 for cond in IntCond: 4708 for cond in IntCond:
4629 c._flags = cond 4709 c._flags = cond
4630 self.assertTrue(c._flags&DecIEEEInvalidOperation) 4710 self.assertTrue(c._flags&DecIEEEInvalidOperation)
4631 assertIsExclusivelySet(InvalidOperation, c.flags) 4711 assertIsExclusivelySet(InvalidOperation, c.flags)
4632 4712
4633 for cond in IntCond: 4713 for cond in IntCond:
4634 c._traps = cond 4714 c._traps = cond
4635 self.assertTrue(c._traps&DecIEEEInvalidOperation) 4715 self.assertTrue(c._traps&DecIEEEInvalidOperation)
4636 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')
4637 4754
4638 4755
4639 all_tests = [ 4756 all_tests = [
4640 CExplicitConstructionTest, PyExplicitConstructionTest, 4757 CExplicitConstructionTest, PyExplicitConstructionTest,
4641 CImplicitConstructionTest, PyImplicitConstructionTest, 4758 CImplicitConstructionTest, PyImplicitConstructionTest,
4642 CFormatTest, PyFormatTest, 4759 CFormatTest, PyFormatTest,
4643 CArithmeticOperatorsTest, PyArithmeticOperatorsTest, 4760 CArithmeticOperatorsTest, PyArithmeticOperatorsTest,
4644 CThreadingTest, PyThreadingTest, 4761 CThreadingTest, PyThreadingTest,
4645 CUsabilityTest, PyUsabilityTest, 4762 CUsabilityTest, PyUsabilityTest,
4646 CPythonAPItests, PyPythonAPItests, 4763 CPythonAPItests, PyPythonAPItests,
4647 CContextAPItests, PyContextAPItests, 4764 CContextAPItests, PyContextAPItests,
4648 CContextWithStatement, PyContextWithStatement, 4765 CContextWithStatement, PyContextWithStatement,
4649 CContextFlags, PyContextFlags, 4766 CContextFlags, PyContextFlags,
4650 CSpecialContexts, PySpecialContexts, 4767 CSpecialContexts, PySpecialContexts,
4651 CContextInputValidation, PyContextInputValidation, 4768 CContextInputValidation, PyContextInputValidation,
4652 CCoverage, PyCoverage, 4769 CCoverage, PyCoverage,
4653 CFunctionality, PyFunctionality, 4770 CFunctionality, PyFunctionality,
4654 CWhitebox, PyWhitebox, 4771 CWhitebox, PyWhitebox,
4655 CIBMTestCases, PyIBMTestCases, 4772 CIBMTestCases, PyIBMTestCases,
4656 ] 4773 ]
4657 4774
4658 # Delete C tests if _decimal.so is not present. 4775 # Delete C tests if _decimal.so is not present.
4659 if not C: 4776 if not C:
4660 all_tests = all_tests[1::2] 4777 all_tests = all_tests[1::2]
4661 4778 else:
4662 # Wrap test functions for testing api failures. Doing this in 4779 all_tests.insert(0, CheckAttributes)
4663 # test_main() causes spurious refleaks, so it is done here. 4780
4664 if hasattr(C, 'setapicalls'):
4665 for cls in all_tests:
4666 if cls == CIBMTestCases or cls == PyIBMTestCases:
4667 newfunc = withFailpoint(getattr(cls, 'eval_equation'))
4668 setattr(cls, 'eval_equation', newfunc)
4669 else:
4670 for attr in dir(cls):
4671 if attr.startswith('test_'):
4672 if attr == 'test_threading':
4673 continue
4674 newfunc = withFailpoint(getattr(cls, attr))
4675 setattr(cls, attr, newfunc)
4676 4781
4677 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):
4678 """ Execute the tests. 4783 """ Execute the tests.
4679 4784
4680 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
4681 is enabled in regrtest.py 4786 is enabled in regrtest.py
4682 """ 4787 """
4683 4788
4684 init(C) 4789 init(C)
4685 init(P) 4790 init(P)
(...skipping 31 matching lines...) Expand 10 before | Expand all | Expand 10 after
4717 run_doctest(C, verbose, optionflags=IGNORE_EXCEPTION_DETAIL) 4822 run_doctest(C, verbose, optionflags=IGNORE_EXCEPTION_DETAIL)
4718 sys.modules['decimal'] = P 4823 sys.modules['decimal'] = P
4719 run_doctest(P, verbose) 4824 run_doctest(P, verbose)
4720 sys.modules['decimal'] = savedecimal 4825 sys.modules['decimal'] = savedecimal
4721 finally: 4826 finally:
4722 if C: C.setcontext(ORIGINAL_CONTEXT[C]) 4827 if C: C.setcontext(ORIGINAL_CONTEXT[C])
4723 P.setcontext(ORIGINAL_CONTEXT[P]) 4828 P.setcontext(ORIGINAL_CONTEXT[P])
4724 if not C: 4829 if not C:
4725 warnings.warn('C tests skipped: no module named _decimal.', 4830 warnings.warn('C tests skipped: no module named _decimal.',
4726 UserWarning) 4831 UserWarning)
4727 if not orig_sys_modules is sys.modules['decimal']: 4832 if not orig_sys_decimal is sys.modules['decimal']:
4728 raise TestFailed("Internal error: unbalanced number of changes to " 4833 raise TestFailed("Internal error: unbalanced number of changes to "
4729 "sys.modules['decimal'].") 4834 "sys.modules['decimal'].")
4730 4835
4731 4836
4732 if __name__ == '__main__': 4837 if __name__ == '__main__':
4733 import optparse 4838 import optparse
4734 p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]") 4839 p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]")
4735 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')
4736 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')
4737 (opt, args) = p.parse_args() 4842 (opt, args) = p.parse_args()
4738 4843
4739 if opt.skip: 4844 if opt.skip:
4740 test_main(arith=False, verbose=True) 4845 test_main(arith=False, verbose=True)
4741 elif args: 4846 elif args:
4742 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)
4743 else: 4848 else:
4744 test_main(arith=True, verbose=True) 4849 test_main(arith=True, verbose=True)
LEFTRIGHT

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