Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1 | # Copyright (c) 2004 Python Software Foundation. |
| 2 | # All rights reserved. |
| 3 | |
| 4 | # Written by Eric Price <eprice at tjhsst.edu> |
| 5 | # and Facundo Batista <facundo at taniquetil.com.ar> |
| 6 | # and Raymond Hettinger <python at rcn.com> |
| 7 | # and Aahz (aahz at pobox.com) |
| 8 | # and Tim Peters |
| 9 | |
| 10 | """ |
| 11 | These are the test cases for the Decimal module. |
| 12 | |
| 13 | There are two groups of tests, Arithmetic and Behaviour. The former test |
| 14 | the Decimal arithmetic using the tests provided by Mike Cowlishaw. The latter |
| 15 | test the pythonic behaviour according to PEP 327. |
| 16 | |
| 17 | Cowlishaw's tests can be downloaded from: |
| 18 | |
| 19 | www2.hursley.ibm.com/decimal/dectest.zip |
| 20 | |
| 21 | This test module can be called from command line with one parameter (Arithmetic |
| 22 | or Behaviour) to test each part, or without parameter to test both parts. If |
| 23 | you're working through IDLE, you can import this test module and call test_main() |
| 24 | with the corresponding argument. |
| 25 | """ |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 26 | from __future__ import with_statement |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 27 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 28 | import glob |
Jeffrey Yasskin | ca2b69f | 2008-02-01 06:22:46 +0000 | [diff] [blame] | 29 | import math |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 30 | import os, sys |
| 31 | import pickle, copy |
Jeffrey Yasskin | ca2b69f | 2008-02-01 06:22:46 +0000 | [diff] [blame] | 32 | import unittest |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 33 | from decimal import * |
Tim Peters | 46cc702 | 2006-03-31 04:11:16 +0000 | [diff] [blame] | 34 | from test.test_support import (TestSkipped, run_unittest, run_doctest, |
| 35 | is_resource_enabled) |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 36 | import random |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 37 | try: |
| 38 | import threading |
| 39 | except ImportError: |
| 40 | threading = None |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 41 | |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 42 | # Useful Test Constant |
| 43 | Signals = getcontext().flags.keys() |
| 44 | |
Tim Peters | 46cc702 | 2006-03-31 04:11:16 +0000 | [diff] [blame] | 45 | # Tests are built around these assumed context defaults. |
| 46 | # test_main() restores the original context. |
Neal Norwitz | ce4a9c9 | 2006-04-09 08:36:46 +0000 | [diff] [blame] | 47 | def init(): |
| 48 | global ORIGINAL_CONTEXT |
| 49 | ORIGINAL_CONTEXT = getcontext().copy() |
| 50 | DefaultContext.prec = 9 |
| 51 | DefaultContext.rounding = ROUND_HALF_EVEN |
| 52 | DefaultContext.traps = dict.fromkeys(Signals, 0) |
| 53 | setcontext(DefaultContext) |
Raymond Hettinger | 6ea4845 | 2004-07-03 12:26:21 +0000 | [diff] [blame] | 54 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 55 | TESTDATADIR = 'decimaltestdata' |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 56 | if __name__ == '__main__': |
| 57 | file = sys.argv[0] |
| 58 | else: |
| 59 | file = __file__ |
| 60 | testdir = os.path.dirname(file) or os.curdir |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 61 | directory = testdir + os.sep + TESTDATADIR + os.sep |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 62 | |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 63 | skip_expected = not os.path.isdir(directory) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 64 | |
| 65 | # Make sure it actually raises errors when not expected and caught in flags |
| 66 | # Slower, since it runs some things several times. |
| 67 | EXTENDEDERRORTEST = False |
| 68 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 69 | #Map the test cases' error names to the actual errors |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 70 | ErrorNames = {'clamped' : Clamped, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 71 | 'conversion_syntax' : InvalidOperation, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 72 | 'division_by_zero' : DivisionByZero, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 73 | 'division_impossible' : InvalidOperation, |
| 74 | 'division_undefined' : InvalidOperation, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 75 | 'inexact' : Inexact, |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 76 | 'invalid_context' : InvalidOperation, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 77 | 'invalid_operation' : InvalidOperation, |
| 78 | 'overflow' : Overflow, |
| 79 | 'rounded' : Rounded, |
| 80 | 'subnormal' : Subnormal, |
| 81 | 'underflow' : Underflow} |
| 82 | |
| 83 | |
| 84 | def Nonfunction(*args): |
| 85 | """Doesn't do anything.""" |
| 86 | return None |
| 87 | |
| 88 | RoundingDict = {'ceiling' : ROUND_CEILING, #Maps test-case names to roundings. |
| 89 | 'down' : ROUND_DOWN, |
| 90 | 'floor' : ROUND_FLOOR, |
| 91 | 'half_down' : ROUND_HALF_DOWN, |
| 92 | 'half_even' : ROUND_HALF_EVEN, |
| 93 | 'half_up' : ROUND_HALF_UP, |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 94 | 'up' : ROUND_UP, |
| 95 | '05up' : ROUND_05UP} |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 96 | |
| 97 | # Name adapter to be able to change the Decimal and Context |
| 98 | # interface without changing the test files from Cowlishaw |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 99 | nameAdapter = {'and':'logical_and', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 100 | 'apply':'_apply', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 101 | 'class':'number_class', |
| 102 | 'comparesig':'compare_signal', |
| 103 | 'comparetotal':'compare_total', |
| 104 | 'comparetotmag':'compare_total_mag', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 105 | 'copy':'copy_decimal', |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 106 | 'copyabs':'copy_abs', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 107 | 'copynegate':'copy_negate', |
| 108 | 'copysign':'copy_sign', |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 109 | 'divideint':'divide_int', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 110 | 'invert':'logical_invert', |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 111 | 'iscanonical':'is_canonical', |
| 112 | 'isfinite':'is_finite', |
| 113 | 'isinfinite':'is_infinite', |
| 114 | 'isnan':'is_nan', |
| 115 | 'isnormal':'is_normal', |
| 116 | 'isqnan':'is_qnan', |
| 117 | 'issigned':'is_signed', |
| 118 | 'issnan':'is_snan', |
| 119 | 'issubnormal':'is_subnormal', |
| 120 | 'iszero':'is_zero', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 121 | 'maxmag':'max_mag', |
| 122 | 'minmag':'min_mag', |
| 123 | 'nextminus':'next_minus', |
| 124 | 'nextplus':'next_plus', |
| 125 | 'nexttoward':'next_toward', |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 126 | 'or':'logical_or', |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 127 | 'reduce':'normalize', |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 128 | 'remaindernear':'remainder_near', |
| 129 | 'samequantum':'same_quantum', |
| 130 | 'squareroot':'sqrt', |
| 131 | 'toeng':'to_eng_string', |
| 132 | 'tointegral':'to_integral_value', |
| 133 | 'tointegralx':'to_integral_exact', |
| 134 | 'tosci':'to_sci_string', |
| 135 | 'xor':'logical_xor', |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 136 | } |
| 137 | |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 138 | # The following functions return True/False rather than a Decimal instance |
| 139 | |
| 140 | LOGICAL_FUNCTIONS = ( |
| 141 | 'is_canonical', |
| 142 | 'is_finite', |
| 143 | 'is_infinite', |
| 144 | 'is_nan', |
| 145 | 'is_normal', |
| 146 | 'is_qnan', |
| 147 | 'is_signed', |
| 148 | 'is_snan', |
| 149 | 'is_subnormal', |
| 150 | 'is_zero', |
| 151 | 'same_quantum', |
| 152 | ) |
| 153 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 154 | # For some operations (currently exp, ln, log10, power), the decNumber |
| 155 | # reference implementation imposes additional restrictions on the |
| 156 | # context and operands. These restrictions are not part of the |
| 157 | # specification; however, the effect of these restrictions does show |
| 158 | # up in some of the testcases. We skip testcases that violate these |
| 159 | # restrictions, since Decimal behaves differently from decNumber for |
| 160 | # these testcases so these testcases would otherwise fail. |
| 161 | |
| 162 | decNumberRestricted = ('power', 'ln', 'log10', 'exp') |
| 163 | DEC_MAX_MATH = 999999 |
| 164 | def outside_decNumber_bounds(v, context): |
| 165 | if (context.prec > DEC_MAX_MATH or |
| 166 | context.Emax > DEC_MAX_MATH or |
| 167 | -context.Emin > DEC_MAX_MATH): |
| 168 | return True |
| 169 | if not v._is_special and v and ( |
| 170 | len(v._int) > DEC_MAX_MATH or |
| 171 | v.adjusted() > DEC_MAX_MATH or |
| 172 | v.adjusted() < 1-2*DEC_MAX_MATH): |
| 173 | return True |
| 174 | return False |
| 175 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 176 | class DecimalTest(unittest.TestCase): |
| 177 | """Class which tests the Decimal class against the test cases. |
| 178 | |
| 179 | Changed for unittest. |
| 180 | """ |
| 181 | def setUp(self): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 182 | self.context = Context() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 183 | for key in DefaultContext.traps.keys(): |
| 184 | DefaultContext.traps[key] = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 185 | self.ignore_list = ['#'] |
| 186 | # Basically, a # means return NaN InvalidOperation. |
| 187 | # Different from a sNaN in trim |
| 188 | |
| 189 | self.ChangeDict = {'precision' : self.change_precision, |
| 190 | 'rounding' : self.change_rounding_method, |
| 191 | 'maxexponent' : self.change_max_exponent, |
| 192 | 'minexponent' : self.change_min_exponent, |
| 193 | 'clamp' : self.change_clamp} |
| 194 | |
| 195 | def tearDown(self): |
| 196 | """Cleaning up enviroment.""" |
| 197 | # leaving context in original state |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 198 | for key in DefaultContext.traps.keys(): |
| 199 | DefaultContext.traps[key] = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 200 | return |
| 201 | |
| 202 | def eval_file(self, file): |
| 203 | global skip_expected |
| 204 | if skip_expected: |
| 205 | raise TestSkipped |
| 206 | return |
| 207 | for line in open(file).xreadlines(): |
| 208 | line = line.replace('\r\n', '').replace('\n', '') |
Raymond Hettinger | 5aa478b | 2004-07-09 10:02:53 +0000 | [diff] [blame] | 209 | #print line |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 210 | try: |
| 211 | t = self.eval_line(line) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 212 | except DecimalException, exception: |
| 213 | #Exception raised where there shoudn't have been one. |
| 214 | self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line) |
| 215 | |
| 216 | return |
| 217 | |
| 218 | def eval_line(self, s): |
| 219 | if s.find(' -> ') >= 0 and s[:2] != '--' and not s.startswith(' --'): |
| 220 | s = (s.split('->')[0] + '->' + |
| 221 | s.split('->')[1].split('--')[0]).strip() |
| 222 | else: |
| 223 | s = s.split('--')[0].strip() |
| 224 | |
| 225 | for ignore in self.ignore_list: |
| 226 | if s.find(ignore) >= 0: |
| 227 | #print s.split()[0], 'NotImplemented--', ignore |
| 228 | return |
| 229 | if not s: |
| 230 | return |
| 231 | elif ':' in s: |
| 232 | return self.eval_directive(s) |
| 233 | else: |
| 234 | return self.eval_equation(s) |
| 235 | |
| 236 | def eval_directive(self, s): |
| 237 | funct, value = map(lambda x: x.strip().lower(), s.split(':')) |
| 238 | if funct == 'rounding': |
| 239 | value = RoundingDict[value] |
| 240 | else: |
| 241 | try: |
| 242 | value = int(value) |
| 243 | except ValueError: |
| 244 | pass |
| 245 | |
| 246 | funct = self.ChangeDict.get(funct, Nonfunction) |
| 247 | funct(value) |
| 248 | |
| 249 | def eval_equation(self, s): |
| 250 | #global DEFAULT_PRECISION |
| 251 | #print DEFAULT_PRECISION |
Raymond Hettinger | ed20ad8 | 2004-09-04 20:09:13 +0000 | [diff] [blame] | 252 | |
| 253 | if not TEST_ALL and random.random() < 0.90: |
| 254 | return |
| 255 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 256 | try: |
| 257 | Sides = s.split('->') |
| 258 | L = Sides[0].strip().split() |
| 259 | id = L[0] |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 260 | if DEBUG: |
| 261 | print "Test ", id, |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 262 | funct = L[1].lower() |
| 263 | valstemp = L[2:] |
| 264 | L = Sides[1].strip().split() |
| 265 | ans = L[0] |
| 266 | exceptions = L[1:] |
| 267 | except (TypeError, AttributeError, IndexError): |
Raymond Hettinger | d87ac8f | 2004-07-09 10:52:54 +0000 | [diff] [blame] | 268 | raise InvalidOperation |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 269 | def FixQuotes(val): |
| 270 | val = val.replace("''", 'SingleQuote').replace('""', 'DoubleQuote') |
| 271 | val = val.replace("'", '').replace('"', '') |
| 272 | val = val.replace('SingleQuote', "'").replace('DoubleQuote', '"') |
| 273 | return val |
| 274 | fname = nameAdapter.get(funct, funct) |
| 275 | if fname == 'rescale': |
| 276 | return |
| 277 | funct = getattr(self.context, fname) |
| 278 | vals = [] |
| 279 | conglomerate = '' |
| 280 | quote = 0 |
| 281 | theirexceptions = [ErrorNames[x.lower()] for x in exceptions] |
| 282 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 283 | for exception in Signals: |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 284 | self.context.traps[exception] = 1 #Catch these bugs... |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 285 | for exception in theirexceptions: |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 286 | self.context.traps[exception] = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 287 | for i, val in enumerate(valstemp): |
| 288 | if val.count("'") % 2 == 1: |
| 289 | quote = 1 - quote |
| 290 | if quote: |
| 291 | conglomerate = conglomerate + ' ' + val |
| 292 | continue |
| 293 | else: |
| 294 | val = conglomerate + val |
| 295 | conglomerate = '' |
| 296 | v = FixQuotes(val) |
| 297 | if fname in ('to_sci_string', 'to_eng_string'): |
| 298 | if EXTENDEDERRORTEST: |
| 299 | for error in theirexceptions: |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 300 | self.context.traps[error] = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 301 | try: |
| 302 | funct(self.context.create_decimal(v)) |
| 303 | except error: |
| 304 | pass |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 305 | except Signals, e: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 306 | self.fail("Raised %s in %s when %s disabled" % \ |
| 307 | (e, s, error)) |
| 308 | else: |
| 309 | self.fail("Did not raise %s in %s" % (error, s)) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 310 | self.context.traps[error] = 0 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 311 | v = self.context.create_decimal(v) |
| 312 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 313 | v = Decimal(v, self.context) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 314 | vals.append(v) |
| 315 | |
| 316 | ans = FixQuotes(ans) |
| 317 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 318 | # skip tests that are related to bounds imposed in the decNumber |
| 319 | # reference implementation |
| 320 | if fname in decNumberRestricted: |
| 321 | if fname == 'power': |
| 322 | if not (vals[1]._isinteger() and |
| 323 | -1999999997 <= vals[1] <= 999999999): |
| 324 | if outside_decNumber_bounds(vals[0], self.context) or \ |
| 325 | outside_decNumber_bounds(vals[1], self.context): |
| 326 | #print "Skipping test %s" % s |
| 327 | return |
| 328 | else: |
| 329 | if outside_decNumber_bounds(vals[0], self.context): |
| 330 | #print "Skipping test %s" % s |
| 331 | return |
| 332 | |
| 333 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 334 | if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'): |
| 335 | for error in theirexceptions: |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 336 | self.context.traps[error] = 1 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 337 | try: |
| 338 | funct(*vals) |
| 339 | except error: |
| 340 | pass |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 341 | except Signals, e: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 342 | self.fail("Raised %s in %s when %s disabled" % \ |
| 343 | (e, s, error)) |
| 344 | else: |
| 345 | self.fail("Did not raise %s in %s" % (error, s)) |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 346 | self.context.traps[error] = 0 |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 347 | if DEBUG: |
| 348 | print "--", self.context |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 349 | try: |
| 350 | result = str(funct(*vals)) |
Facundo Batista | 1a191df | 2007-10-02 17:01:24 +0000 | [diff] [blame] | 351 | if fname in LOGICAL_FUNCTIONS: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 352 | result = str(int(eval(result))) # 'True', 'False' -> '1', '0' |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 353 | except Signals, error: |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 354 | self.fail("Raised %s in %s" % (error, s)) |
| 355 | except: #Catch any error long enough to state the test case. |
| 356 | print "ERROR:", s |
| 357 | raise |
| 358 | |
| 359 | myexceptions = self.getexceptions() |
Raymond Hettinger | bf44069 | 2004-07-10 14:14:37 +0000 | [diff] [blame] | 360 | self.context.clear_flags() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 361 | |
| 362 | myexceptions.sort() |
| 363 | theirexceptions.sort() |
| 364 | |
| 365 | self.assertEqual(result, ans, |
| 366 | 'Incorrect answer for ' + s + ' -- got ' + result) |
| 367 | self.assertEqual(myexceptions, theirexceptions, |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 368 | 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 369 | return |
| 370 | |
| 371 | def getexceptions(self): |
Raymond Hettinger | f63ba43 | 2004-08-17 05:42:09 +0000 | [diff] [blame] | 372 | return [e for e in Signals if self.context.flags[e]] |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 373 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 374 | def change_precision(self, prec): |
| 375 | self.context.prec = prec |
| 376 | def change_rounding_method(self, rounding): |
| 377 | self.context.rounding = rounding |
| 378 | def change_min_exponent(self, exp): |
| 379 | self.context.Emin = exp |
| 380 | def change_max_exponent(self, exp): |
| 381 | self.context.Emax = exp |
| 382 | def change_clamp(self, clamp): |
| 383 | self.context._clamp = clamp |
| 384 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 385 | |
| 386 | |
| 387 | # The following classes test the behaviour of Decimal according to PEP 327 |
| 388 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 389 | class DecimalExplicitConstructionTest(unittest.TestCase): |
| 390 | '''Unit tests for Explicit Construction cases of Decimal.''' |
| 391 | |
| 392 | def test_explicit_empty(self): |
| 393 | self.assertEqual(Decimal(), Decimal("0")) |
| 394 | |
| 395 | def test_explicit_from_None(self): |
| 396 | self.assertRaises(TypeError, Decimal, None) |
| 397 | |
| 398 | def test_explicit_from_int(self): |
| 399 | |
| 400 | #positive |
| 401 | d = Decimal(45) |
| 402 | self.assertEqual(str(d), '45') |
| 403 | |
| 404 | #very large positive |
| 405 | d = Decimal(500000123) |
| 406 | self.assertEqual(str(d), '500000123') |
| 407 | |
| 408 | #negative |
| 409 | d = Decimal(-45) |
| 410 | self.assertEqual(str(d), '-45') |
| 411 | |
| 412 | #zero |
| 413 | d = Decimal(0) |
| 414 | self.assertEqual(str(d), '0') |
| 415 | |
| 416 | def test_explicit_from_string(self): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 417 | |
| 418 | #empty |
| 419 | self.assertEqual(str(Decimal('')), 'NaN') |
| 420 | |
| 421 | #int |
| 422 | self.assertEqual(str(Decimal('45')), '45') |
| 423 | |
| 424 | #float |
| 425 | self.assertEqual(str(Decimal('45.34')), '45.34') |
| 426 | |
| 427 | #engineer notation |
| 428 | self.assertEqual(str(Decimal('45e2')), '4.5E+3') |
| 429 | |
| 430 | #just not a number |
| 431 | self.assertEqual(str(Decimal('ugly')), 'NaN') |
| 432 | |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 433 | #leading and trailing whitespace permitted |
| 434 | self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4') |
| 435 | self.assertEqual(str(Decimal(' -7.89')), '-7.89') |
| 436 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 437 | def test_explicit_from_tuples(self): |
| 438 | |
| 439 | #zero |
| 440 | d = Decimal( (0, (0,), 0) ) |
| 441 | self.assertEqual(str(d), '0') |
| 442 | |
| 443 | #int |
| 444 | d = Decimal( (1, (4, 5), 0) ) |
| 445 | self.assertEqual(str(d), '-45') |
| 446 | |
| 447 | #float |
| 448 | d = Decimal( (0, (4, 5, 3, 4), -2) ) |
| 449 | self.assertEqual(str(d), '45.34') |
| 450 | |
| 451 | #weird |
| 452 | d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) |
| 453 | self.assertEqual(str(d), '-4.34913534E-17') |
| 454 | |
| 455 | #wrong number of items |
| 456 | self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1)) ) |
| 457 | |
| 458 | #bad sign |
| 459 | self.assertRaises(ValueError, Decimal, (8, (4, 3, 4, 9, 1), 2) ) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 460 | self.assertRaises(ValueError, Decimal, (0., (4, 3, 4, 9, 1), 2) ) |
| 461 | self.assertRaises(ValueError, Decimal, (Decimal(1), (4, 3, 4, 9, 1), 2)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 462 | |
| 463 | #bad exp |
| 464 | self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 'wrong!') ) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 465 | self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) ) |
| 466 | self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') ) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 467 | |
| 468 | #bad coefficients |
| 469 | self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) ) |
| 470 | self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) ) |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 471 | self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) ) |
Facundo Batista | 72bc54f | 2007-11-23 17:59:00 +0000 | [diff] [blame] | 472 | self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) ) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 473 | |
| 474 | def test_explicit_from_Decimal(self): |
| 475 | |
| 476 | #positive |
| 477 | d = Decimal(45) |
| 478 | e = Decimal(d) |
| 479 | self.assertEqual(str(e), '45') |
| 480 | self.assertNotEqual(id(d), id(e)) |
| 481 | |
| 482 | #very large positive |
| 483 | d = Decimal(500000123) |
| 484 | e = Decimal(d) |
| 485 | self.assertEqual(str(e), '500000123') |
| 486 | self.assertNotEqual(id(d), id(e)) |
| 487 | |
| 488 | #negative |
| 489 | d = Decimal(-45) |
| 490 | e = Decimal(d) |
| 491 | self.assertEqual(str(e), '-45') |
| 492 | self.assertNotEqual(id(d), id(e)) |
| 493 | |
| 494 | #zero |
| 495 | d = Decimal(0) |
| 496 | e = Decimal(d) |
| 497 | self.assertEqual(str(e), '0') |
| 498 | self.assertNotEqual(id(d), id(e)) |
| 499 | |
| 500 | def test_explicit_context_create_decimal(self): |
| 501 | |
| 502 | nc = copy.copy(getcontext()) |
| 503 | nc.prec = 3 |
| 504 | |
| 505 | # empty |
Raymond Hettinger | fed5296 | 2004-07-14 15:41:57 +0000 | [diff] [blame] | 506 | d = Decimal() |
| 507 | self.assertEqual(str(d), '0') |
| 508 | d = nc.create_decimal() |
| 509 | self.assertEqual(str(d), '0') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 510 | |
| 511 | # from None |
| 512 | self.assertRaises(TypeError, nc.create_decimal, None) |
| 513 | |
| 514 | # from int |
| 515 | d = nc.create_decimal(456) |
| 516 | self.failUnless(isinstance(d, Decimal)) |
| 517 | self.assertEqual(nc.create_decimal(45678), |
| 518 | nc.create_decimal('457E+2')) |
| 519 | |
| 520 | # from string |
| 521 | d = Decimal('456789') |
| 522 | self.assertEqual(str(d), '456789') |
| 523 | d = nc.create_decimal('456789') |
| 524 | self.assertEqual(str(d), '4.57E+5') |
Mark Dickinson | 59bc20b | 2008-01-12 01:56:00 +0000 | [diff] [blame] | 525 | # leading and trailing whitespace should result in a NaN; |
| 526 | # spaces are already checked in Cowlishaw's test-suite, so |
| 527 | # here we just check that a trailing newline results in a NaN |
| 528 | self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 529 | |
| 530 | # from tuples |
| 531 | d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) |
| 532 | self.assertEqual(str(d), '-4.34913534E-17') |
| 533 | d = nc.create_decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) |
| 534 | self.assertEqual(str(d), '-4.35E-17') |
| 535 | |
| 536 | # from Decimal |
| 537 | prevdec = Decimal(500000123) |
| 538 | d = Decimal(prevdec) |
| 539 | self.assertEqual(str(d), '500000123') |
| 540 | d = nc.create_decimal(prevdec) |
| 541 | self.assertEqual(str(d), '5.00E+8') |
| 542 | |
| 543 | |
| 544 | class DecimalImplicitConstructionTest(unittest.TestCase): |
| 545 | '''Unit tests for Implicit Construction cases of Decimal.''' |
| 546 | |
| 547 | def test_implicit_from_None(self): |
| 548 | self.assertRaises(TypeError, eval, 'Decimal(5) + None', globals()) |
| 549 | |
| 550 | def test_implicit_from_int(self): |
| 551 | #normal |
| 552 | self.assertEqual(str(Decimal(5) + 45), '50') |
| 553 | #exceeding precision |
| 554 | self.assertEqual(Decimal(5) + 123456789000, Decimal(123456789000)) |
| 555 | |
| 556 | def test_implicit_from_string(self): |
| 557 | self.assertRaises(TypeError, eval, 'Decimal(5) + "3"', globals()) |
| 558 | |
| 559 | def test_implicit_from_float(self): |
| 560 | self.assertRaises(TypeError, eval, 'Decimal(5) + 2.2', globals()) |
| 561 | |
| 562 | def test_implicit_from_Decimal(self): |
| 563 | self.assertEqual(Decimal(5) + Decimal(45), Decimal(50)) |
| 564 | |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 565 | def test_rop(self): |
| 566 | # Allow other classes to be trained to interact with Decimals |
| 567 | class E: |
| 568 | def __divmod__(self, other): |
| 569 | return 'divmod ' + str(other) |
| 570 | def __rdivmod__(self, other): |
| 571 | return str(other) + ' rdivmod' |
| 572 | def __lt__(self, other): |
| 573 | return 'lt ' + str(other) |
| 574 | def __gt__(self, other): |
| 575 | return 'gt ' + str(other) |
| 576 | def __le__(self, other): |
| 577 | return 'le ' + str(other) |
| 578 | def __ge__(self, other): |
| 579 | return 'ge ' + str(other) |
| 580 | def __eq__(self, other): |
| 581 | return 'eq ' + str(other) |
| 582 | def __ne__(self, other): |
| 583 | return 'ne ' + str(other) |
| 584 | |
| 585 | self.assertEqual(divmod(E(), Decimal(10)), 'divmod 10') |
| 586 | self.assertEqual(divmod(Decimal(10), E()), '10 rdivmod') |
| 587 | self.assertEqual(eval('Decimal(10) < E()'), 'gt 10') |
| 588 | self.assertEqual(eval('Decimal(10) > E()'), 'lt 10') |
| 589 | self.assertEqual(eval('Decimal(10) <= E()'), 'ge 10') |
| 590 | self.assertEqual(eval('Decimal(10) >= E()'), 'le 10') |
| 591 | self.assertEqual(eval('Decimal(10) == E()'), 'eq 10') |
| 592 | self.assertEqual(eval('Decimal(10) != E()'), 'ne 10') |
| 593 | |
| 594 | # insert operator methods and then exercise them |
Georg Brandl | 96c3f7f | 2006-03-28 08:06:35 +0000 | [diff] [blame] | 595 | oplist = [ |
| 596 | ('+', '__add__', '__radd__'), |
| 597 | ('-', '__sub__', '__rsub__'), |
| 598 | ('*', '__mul__', '__rmul__'), |
| 599 | ('%', '__mod__', '__rmod__'), |
| 600 | ('//', '__floordiv__', '__rfloordiv__'), |
| 601 | ('**', '__pow__', '__rpow__') |
| 602 | ] |
| 603 | if 1/2 == 0: |
| 604 | # testing with classic division, so add __div__ |
| 605 | oplist.append(('/', '__div__', '__rdiv__')) |
| 606 | else: |
| 607 | # testing with -Qnew, so add __truediv__ |
| 608 | oplist.append(('/', '__truediv__', '__rtruediv__')) |
Anthony Baxter | 4ef3a23 | 2006-03-30 12:59:11 +0000 | [diff] [blame] | 609 | |
Georg Brandl | 96c3f7f | 2006-03-28 08:06:35 +0000 | [diff] [blame] | 610 | for sym, lop, rop in oplist: |
Raymond Hettinger | 267b868 | 2005-03-27 10:47:39 +0000 | [diff] [blame] | 611 | setattr(E, lop, lambda self, other: 'str' + lop + str(other)) |
| 612 | setattr(E, rop, lambda self, other: str(other) + rop + 'str') |
| 613 | self.assertEqual(eval('E()' + sym + 'Decimal(10)'), |
| 614 | 'str' + lop + '10') |
| 615 | self.assertEqual(eval('Decimal(10)' + sym + 'E()'), |
| 616 | '10' + rop + 'str') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 617 | |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 618 | class DecimalFormatTest(unittest.TestCase): |
| 619 | '''Unit tests for the format function.''' |
| 620 | def test_formatting(self): |
| 621 | # triples giving a format, a Decimal, and the expected result |
| 622 | test_values = [ |
| 623 | ('e', '0E-15', '0e-15'), |
| 624 | ('e', '2.3E-15', '2.3e-15'), |
| 625 | ('e', '2.30E+2', '2.30e+2'), # preserve significant zeros |
| 626 | ('e', '2.30000E-15', '2.30000e-15'), |
| 627 | ('e', '1.23456789123456789e40', '1.23456789123456789e+40'), |
| 628 | ('e', '1.5', '1.5e+0'), |
| 629 | ('e', '0.15', '1.5e-1'), |
| 630 | ('e', '0.015', '1.5e-2'), |
| 631 | ('e', '0.0000000000015', '1.5e-12'), |
| 632 | ('e', '15.0', '1.50e+1'), |
| 633 | ('e', '-15', '-1.5e+1'), |
| 634 | ('e', '0', '0e+0'), |
| 635 | ('e', '0E1', '0e+1'), |
| 636 | ('e', '0.0', '0e-1'), |
| 637 | ('e', '0.00', '0e-2'), |
| 638 | ('.6e', '0E-15', '0.000000e-9'), |
| 639 | ('.6e', '0', '0.000000e+6'), |
| 640 | ('.6e', '9.999999', '9.999999e+0'), |
| 641 | ('.6e', '9.9999999', '1.000000e+1'), |
| 642 | ('.6e', '-1.23e5', '-1.230000e+5'), |
| 643 | ('.6e', '1.23456789e-3', '1.234568e-3'), |
| 644 | ('f', '0', '0'), |
| 645 | ('f', '0.0', '0.0'), |
| 646 | ('f', '0E-2', '0.00'), |
| 647 | ('f', '0.00E-8', '0.0000000000'), |
| 648 | ('f', '0E1', '0'), # loses exponent information |
| 649 | ('f', '3.2E1', '32'), |
| 650 | ('f', '3.2E2', '320'), |
| 651 | ('f', '3.20E2', '320'), |
| 652 | ('f', '3.200E2', '320.0'), |
| 653 | ('f', '3.2E-6', '0.0000032'), |
| 654 | ('.6f', '0E-15', '0.000000'), # all zeros treated equally |
| 655 | ('.6f', '0E1', '0.000000'), |
| 656 | ('.6f', '0', '0.000000'), |
| 657 | ('.0f', '0', '0'), # no decimal point |
| 658 | ('.0f', '0e-2', '0'), |
| 659 | ('.0f', '3.14159265', '3'), |
| 660 | ('.1f', '3.14159265', '3.1'), |
| 661 | ('.4f', '3.14159265', '3.1416'), |
| 662 | ('.6f', '3.14159265', '3.141593'), |
| 663 | ('.7f', '3.14159265', '3.1415926'), # round-half-even! |
| 664 | ('.8f', '3.14159265', '3.14159265'), |
| 665 | ('.9f', '3.14159265', '3.141592650'), |
| 666 | |
| 667 | ('g', '0', '0'), |
| 668 | ('g', '0.0', '0.0'), |
| 669 | ('g', '0E1', '0e+1'), |
| 670 | ('G', '0E1', '0E+1'), |
| 671 | ('g', '0E-5', '0.00000'), |
| 672 | ('g', '0E-6', '0.000000'), |
| 673 | ('g', '0E-7', '0e-7'), |
| 674 | ('g', '-0E2', '-0e+2'), |
| 675 | ('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig |
| 676 | ('.1g', '3.14159265', '3'), |
| 677 | ('.2g', '3.14159265', '3.1'), |
| 678 | ('.5g', '3.14159265', '3.1416'), |
| 679 | ('.7g', '3.14159265', '3.141593'), |
| 680 | ('.8g', '3.14159265', '3.1415926'), # round-half-even! |
| 681 | ('.9g', '3.14159265', '3.14159265'), |
| 682 | ('.10g', '3.14159265', '3.14159265'), # don't pad |
| 683 | |
| 684 | ('%', '0E1', '0%'), |
| 685 | ('%', '0E0', '0%'), |
| 686 | ('%', '0E-1', '0%'), |
| 687 | ('%', '0E-2', '0%'), |
| 688 | ('%', '0E-3', '0.0%'), |
| 689 | ('%', '0E-4', '0.00%'), |
| 690 | |
| 691 | ('.3%', '0', '0.000%'), # all zeros treated equally |
| 692 | ('.3%', '0E10', '0.000%'), |
| 693 | ('.3%', '0E-10', '0.000%'), |
| 694 | ('.3%', '2.34', '234.000%'), |
| 695 | ('.3%', '1.234567', '123.457%'), |
| 696 | ('.0%', '1.23', '123%'), |
| 697 | |
| 698 | ('e', 'NaN', 'NaN'), |
| 699 | ('f', '-NaN123', '-NaN123'), |
| 700 | ('+g', 'NaN456', '+NaN456'), |
| 701 | ('.3e', 'Inf', 'Infinity'), |
| 702 | ('.16f', '-Inf', '-Infinity'), |
| 703 | ('.0g', '-sNaN', '-sNaN'), |
| 704 | |
| 705 | ('', '1.00', '1.00'), |
| 706 | ] |
| 707 | for fmt, d, result in test_values: |
| 708 | self.assertEqual(format(Decimal(d), fmt), result) |
| 709 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 710 | class DecimalArithmeticOperatorsTest(unittest.TestCase): |
| 711 | '''Unit tests for all arithmetic operators, binary and unary.''' |
| 712 | |
| 713 | def test_addition(self): |
| 714 | |
| 715 | d1 = Decimal('-11.1') |
| 716 | d2 = Decimal('22.2') |
| 717 | |
| 718 | #two Decimals |
| 719 | self.assertEqual(d1+d2, Decimal('11.1')) |
| 720 | self.assertEqual(d2+d1, Decimal('11.1')) |
| 721 | |
| 722 | #with other type, left |
| 723 | c = d1 + 5 |
| 724 | self.assertEqual(c, Decimal('-6.1')) |
| 725 | self.assertEqual(type(c), type(d1)) |
| 726 | |
| 727 | #with other type, right |
| 728 | c = 5 + d1 |
| 729 | self.assertEqual(c, Decimal('-6.1')) |
| 730 | self.assertEqual(type(c), type(d1)) |
| 731 | |
| 732 | #inline with decimal |
| 733 | d1 += d2 |
| 734 | self.assertEqual(d1, Decimal('11.1')) |
| 735 | |
| 736 | #inline with other type |
| 737 | d1 += 5 |
| 738 | self.assertEqual(d1, Decimal('16.1')) |
| 739 | |
| 740 | def test_subtraction(self): |
| 741 | |
| 742 | d1 = Decimal('-11.1') |
| 743 | d2 = Decimal('22.2') |
| 744 | |
| 745 | #two Decimals |
| 746 | self.assertEqual(d1-d2, Decimal('-33.3')) |
| 747 | self.assertEqual(d2-d1, Decimal('33.3')) |
| 748 | |
| 749 | #with other type, left |
| 750 | c = d1 - 5 |
| 751 | self.assertEqual(c, Decimal('-16.1')) |
| 752 | self.assertEqual(type(c), type(d1)) |
| 753 | |
| 754 | #with other type, right |
| 755 | c = 5 - d1 |
| 756 | self.assertEqual(c, Decimal('16.1')) |
| 757 | self.assertEqual(type(c), type(d1)) |
| 758 | |
| 759 | #inline with decimal |
| 760 | d1 -= d2 |
| 761 | self.assertEqual(d1, Decimal('-33.3')) |
| 762 | |
| 763 | #inline with other type |
| 764 | d1 -= 5 |
| 765 | self.assertEqual(d1, Decimal('-38.3')) |
| 766 | |
| 767 | def test_multiplication(self): |
| 768 | |
| 769 | d1 = Decimal('-5') |
| 770 | d2 = Decimal('3') |
| 771 | |
| 772 | #two Decimals |
| 773 | self.assertEqual(d1*d2, Decimal('-15')) |
| 774 | self.assertEqual(d2*d1, Decimal('-15')) |
| 775 | |
| 776 | #with other type, left |
| 777 | c = d1 * 5 |
| 778 | self.assertEqual(c, Decimal('-25')) |
| 779 | self.assertEqual(type(c), type(d1)) |
| 780 | |
| 781 | #with other type, right |
| 782 | c = 5 * d1 |
| 783 | self.assertEqual(c, Decimal('-25')) |
| 784 | self.assertEqual(type(c), type(d1)) |
| 785 | |
| 786 | #inline with decimal |
| 787 | d1 *= d2 |
| 788 | self.assertEqual(d1, Decimal('-15')) |
| 789 | |
| 790 | #inline with other type |
| 791 | d1 *= 5 |
| 792 | self.assertEqual(d1, Decimal('-75')) |
| 793 | |
| 794 | def test_division(self): |
| 795 | |
| 796 | d1 = Decimal('-5') |
| 797 | d2 = Decimal('2') |
| 798 | |
| 799 | #two Decimals |
| 800 | self.assertEqual(d1/d2, Decimal('-2.5')) |
| 801 | self.assertEqual(d2/d1, Decimal('-0.4')) |
| 802 | |
| 803 | #with other type, left |
| 804 | c = d1 / 4 |
| 805 | self.assertEqual(c, Decimal('-1.25')) |
| 806 | self.assertEqual(type(c), type(d1)) |
| 807 | |
| 808 | #with other type, right |
| 809 | c = 4 / d1 |
| 810 | self.assertEqual(c, Decimal('-0.8')) |
| 811 | self.assertEqual(type(c), type(d1)) |
| 812 | |
| 813 | #inline with decimal |
| 814 | d1 /= d2 |
| 815 | self.assertEqual(d1, Decimal('-2.5')) |
| 816 | |
| 817 | #inline with other type |
| 818 | d1 /= 4 |
| 819 | self.assertEqual(d1, Decimal('-0.625')) |
| 820 | |
| 821 | def test_floor_division(self): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 822 | |
| 823 | d1 = Decimal('5') |
| 824 | d2 = Decimal('2') |
| 825 | |
| 826 | #two Decimals |
| 827 | self.assertEqual(d1//d2, Decimal('2')) |
| 828 | self.assertEqual(d2//d1, Decimal('0')) |
| 829 | |
| 830 | #with other type, left |
| 831 | c = d1 // 4 |
| 832 | self.assertEqual(c, Decimal('1')) |
| 833 | self.assertEqual(type(c), type(d1)) |
| 834 | |
| 835 | #with other type, right |
| 836 | c = 7 // d1 |
| 837 | self.assertEqual(c, Decimal('1')) |
| 838 | self.assertEqual(type(c), type(d1)) |
| 839 | |
| 840 | #inline with decimal |
| 841 | d1 //= d2 |
| 842 | self.assertEqual(d1, Decimal('2')) |
| 843 | |
| 844 | #inline with other type |
| 845 | d1 //= 2 |
| 846 | self.assertEqual(d1, Decimal('1')) |
| 847 | |
| 848 | def test_powering(self): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 849 | |
| 850 | d1 = Decimal('5') |
| 851 | d2 = Decimal('2') |
| 852 | |
| 853 | #two Decimals |
| 854 | self.assertEqual(d1**d2, Decimal('25')) |
| 855 | self.assertEqual(d2**d1, Decimal('32')) |
| 856 | |
| 857 | #with other type, left |
| 858 | c = d1 ** 4 |
| 859 | self.assertEqual(c, Decimal('625')) |
| 860 | self.assertEqual(type(c), type(d1)) |
| 861 | |
| 862 | #with other type, right |
| 863 | c = 7 ** d1 |
| 864 | self.assertEqual(c, Decimal('16807')) |
| 865 | self.assertEqual(type(c), type(d1)) |
| 866 | |
| 867 | #inline with decimal |
| 868 | d1 **= d2 |
| 869 | self.assertEqual(d1, Decimal('25')) |
| 870 | |
| 871 | #inline with other type |
| 872 | d1 **= 4 |
| 873 | self.assertEqual(d1, Decimal('390625')) |
| 874 | |
| 875 | def test_module(self): |
| 876 | |
| 877 | d1 = Decimal('5') |
| 878 | d2 = Decimal('2') |
| 879 | |
| 880 | #two Decimals |
| 881 | self.assertEqual(d1%d2, Decimal('1')) |
| 882 | self.assertEqual(d2%d1, Decimal('2')) |
| 883 | |
| 884 | #with other type, left |
| 885 | c = d1 % 4 |
| 886 | self.assertEqual(c, Decimal('1')) |
| 887 | self.assertEqual(type(c), type(d1)) |
| 888 | |
| 889 | #with other type, right |
| 890 | c = 7 % d1 |
| 891 | self.assertEqual(c, Decimal('2')) |
| 892 | self.assertEqual(type(c), type(d1)) |
| 893 | |
| 894 | #inline with decimal |
| 895 | d1 %= d2 |
| 896 | self.assertEqual(d1, Decimal('1')) |
| 897 | |
| 898 | #inline with other type |
| 899 | d1 %= 4 |
| 900 | self.assertEqual(d1, Decimal('1')) |
| 901 | |
| 902 | def test_floor_div_module(self): |
| 903 | |
| 904 | d1 = Decimal('5') |
| 905 | d2 = Decimal('2') |
| 906 | |
| 907 | #two Decimals |
| 908 | (p, q) = divmod(d1, d2) |
| 909 | self.assertEqual(p, Decimal('2')) |
| 910 | self.assertEqual(q, Decimal('1')) |
| 911 | self.assertEqual(type(p), type(d1)) |
| 912 | self.assertEqual(type(q), type(d1)) |
| 913 | |
| 914 | #with other type, left |
| 915 | (p, q) = divmod(d1, 4) |
| 916 | self.assertEqual(p, Decimal('1')) |
| 917 | self.assertEqual(q, Decimal('1')) |
| 918 | self.assertEqual(type(p), type(d1)) |
| 919 | self.assertEqual(type(q), type(d1)) |
| 920 | |
| 921 | #with other type, right |
| 922 | (p, q) = divmod(7, d1) |
| 923 | self.assertEqual(p, Decimal('1')) |
| 924 | self.assertEqual(q, Decimal('2')) |
| 925 | self.assertEqual(type(p), type(d1)) |
| 926 | self.assertEqual(type(q), type(d1)) |
| 927 | |
| 928 | def test_unary_operators(self): |
| 929 | self.assertEqual(+Decimal(45), Decimal(+45)) # + |
| 930 | self.assertEqual(-Decimal(45), Decimal(-45)) # - |
| 931 | self.assertEqual(abs(Decimal(45)), abs(Decimal(-45))) # abs |
| 932 | |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 933 | def test_nan_comparisons(self): |
| 934 | n = Decimal('NaN') |
| 935 | s = Decimal('sNaN') |
| 936 | i = Decimal('Inf') |
| 937 | f = Decimal('2') |
| 938 | for x, y in [(n, n), (n, i), (i, n), (n, f), (f, n), |
| 939 | (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)]: |
| 940 | self.assert_(x != y) |
| 941 | self.assert_(not (x == y)) |
| 942 | self.assert_(not (x < y)) |
| 943 | self.assert_(not (x <= y)) |
| 944 | self.assert_(not (x > y)) |
| 945 | self.assert_(not (x >= y)) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 946 | |
| 947 | # The following are two functions used to test threading in the next class |
| 948 | |
| 949 | def thfunc1(cls): |
| 950 | d1 = Decimal(1) |
| 951 | d3 = Decimal(3) |
Facundo Batista | 6415667 | 2008-03-22 02:45:37 +0000 | [diff] [blame] | 952 | test1 = d1/d3 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 953 | cls.synchro.wait() |
Facundo Batista | 6415667 | 2008-03-22 02:45:37 +0000 | [diff] [blame] | 954 | test2 = d1/d3 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 955 | cls.finish1.set() |
Facundo Batista | 6415667 | 2008-03-22 02:45:37 +0000 | [diff] [blame] | 956 | |
| 957 | cls.assertEqual(test1, Decimal('0.333333333')) |
| 958 | cls.assertEqual(test2, Decimal('0.333333333')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 959 | return |
| 960 | |
| 961 | def thfunc2(cls): |
| 962 | d1 = Decimal(1) |
| 963 | d3 = Decimal(3) |
Facundo Batista | 6415667 | 2008-03-22 02:45:37 +0000 | [diff] [blame] | 964 | test1 = d1/d3 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 965 | thiscontext = getcontext() |
| 966 | thiscontext.prec = 18 |
Facundo Batista | 6415667 | 2008-03-22 02:45:37 +0000 | [diff] [blame] | 967 | test2 = d1/d3 |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 968 | cls.synchro.set() |
| 969 | cls.finish2.set() |
Facundo Batista | 6415667 | 2008-03-22 02:45:37 +0000 | [diff] [blame] | 970 | |
| 971 | cls.assertEqual(test1, Decimal('0.333333333')) |
| 972 | cls.assertEqual(test2, Decimal('0.333333333333333333')) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 973 | return |
| 974 | |
| 975 | |
| 976 | class DecimalUseOfContextTest(unittest.TestCase): |
| 977 | '''Unit tests for Use of Context cases in Decimal.''' |
| 978 | |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 979 | try: |
| 980 | import threading |
| 981 | except ImportError: |
| 982 | threading = None |
| 983 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 984 | # Take care executing this test from IDLE, there's an issue in threading |
| 985 | # that hangs IDLE and I couldn't find it |
| 986 | |
| 987 | def test_threading(self): |
| 988 | #Test the "threading isolation" of a Context. |
| 989 | |
| 990 | self.synchro = threading.Event() |
| 991 | self.finish1 = threading.Event() |
| 992 | self.finish2 = threading.Event() |
| 993 | |
| 994 | th1 = threading.Thread(target=thfunc1, args=(self,)) |
| 995 | th2 = threading.Thread(target=thfunc2, args=(self,)) |
| 996 | |
| 997 | th1.start() |
| 998 | th2.start() |
| 999 | |
| 1000 | self.finish1.wait() |
Thomas Wouters | b3e6e8c | 2007-09-19 17:27:29 +0000 | [diff] [blame] | 1001 | self.finish2.wait() |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1002 | return |
| 1003 | |
Raymond Hettinger | 7e71fa5 | 2004-12-18 19:07:19 +0000 | [diff] [blame] | 1004 | if threading is None: |
| 1005 | del test_threading |
| 1006 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1007 | |
| 1008 | class DecimalUsabilityTest(unittest.TestCase): |
| 1009 | '''Unit tests for Usability cases of Decimal.''' |
| 1010 | |
| 1011 | def test_comparison_operators(self): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1012 | |
| 1013 | da = Decimal('23.42') |
| 1014 | db = Decimal('23.42') |
| 1015 | dc = Decimal('45') |
| 1016 | |
| 1017 | #two Decimals |
| 1018 | self.failUnless(dc > da) |
| 1019 | self.failUnless(dc >= da) |
| 1020 | self.failUnless(da < dc) |
| 1021 | self.failUnless(da <= dc) |
| 1022 | self.failUnless(da == db) |
| 1023 | self.failUnless(da != dc) |
| 1024 | self.failUnless(da <= db) |
| 1025 | self.failUnless(da >= db) |
| 1026 | self.assertEqual(cmp(dc,da), 1) |
| 1027 | self.assertEqual(cmp(da,dc), -1) |
| 1028 | self.assertEqual(cmp(da,db), 0) |
| 1029 | |
| 1030 | #a Decimal and an int |
| 1031 | self.failUnless(dc > 23) |
| 1032 | self.failUnless(23 < dc) |
| 1033 | self.failUnless(dc == 45) |
| 1034 | self.assertEqual(cmp(dc,23), 1) |
| 1035 | self.assertEqual(cmp(23,dc), -1) |
| 1036 | self.assertEqual(cmp(dc,45), 0) |
| 1037 | |
| 1038 | #a Decimal and uncomparable |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 1039 | self.assertNotEqual(da, 'ugly') |
| 1040 | self.assertNotEqual(da, 32.7) |
| 1041 | self.assertNotEqual(da, object()) |
| 1042 | self.assertNotEqual(da, object) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1043 | |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 1044 | # sortable |
| 1045 | a = map(Decimal, xrange(100)) |
| 1046 | b = a[:] |
| 1047 | random.shuffle(a) |
| 1048 | a.sort() |
| 1049 | self.assertEqual(a, b) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1050 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1051 | # with None |
| 1052 | self.assertFalse(Decimal(1) < None) |
| 1053 | self.assertTrue(Decimal(1) > None) |
| 1054 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1055 | def test_copy_and_deepcopy_methods(self): |
| 1056 | d = Decimal('43.24') |
| 1057 | c = copy.copy(d) |
| 1058 | self.assertEqual(id(c), id(d)) |
| 1059 | dc = copy.deepcopy(d) |
| 1060 | self.assertEqual(id(dc), id(d)) |
| 1061 | |
| 1062 | def test_hash_method(self): |
| 1063 | #just that it's hashable |
| 1064 | hash(Decimal(23)) |
Facundo Batista | 8c20244 | 2007-09-19 17:53:25 +0000 | [diff] [blame] | 1065 | |
| 1066 | test_values = [Decimal(sign*(2**m + n)) |
| 1067 | for m in [0, 14, 15, 16, 17, 30, 31, |
| 1068 | 32, 33, 62, 63, 64, 65, 66] |
| 1069 | for n in range(-10, 10) |
| 1070 | for sign in [-1, 1]] |
| 1071 | test_values.extend([ |
| 1072 | Decimal("-0"), # zeros |
| 1073 | Decimal("0.00"), |
| 1074 | Decimal("-0.000"), |
| 1075 | Decimal("0E10"), |
| 1076 | Decimal("-0E12"), |
| 1077 | Decimal("10.0"), # negative exponent |
| 1078 | Decimal("-23.00000"), |
| 1079 | Decimal("1230E100"), # positive exponent |
| 1080 | Decimal("-4.5678E50"), |
| 1081 | # a value for which hash(n) != hash(n % (2**64-1)) |
| 1082 | # in Python pre-2.6 |
| 1083 | Decimal(2**64 + 2**32 - 1), |
| 1084 | # selection of values which fail with the old (before |
| 1085 | # version 2.6) long.__hash__ |
| 1086 | Decimal("1.634E100"), |
| 1087 | Decimal("90.697E100"), |
| 1088 | Decimal("188.83E100"), |
| 1089 | Decimal("1652.9E100"), |
| 1090 | Decimal("56531E100"), |
| 1091 | ]) |
| 1092 | |
| 1093 | # check that hash(d) == hash(int(d)) for integral values |
| 1094 | for value in test_values: |
| 1095 | self.assertEqual(hash(value), hash(int(value))) |
| 1096 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1097 | #the same hash that to an int |
| 1098 | self.assertEqual(hash(Decimal(23)), hash(23)) |
Raymond Hettinger | bea3f6f | 2005-03-15 04:59:17 +0000 | [diff] [blame] | 1099 | self.assertRaises(TypeError, hash, Decimal('NaN')) |
| 1100 | self.assert_(hash(Decimal('Inf'))) |
| 1101 | self.assert_(hash(Decimal('-Inf'))) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1102 | |
Facundo Batista | 52b2579 | 2008-01-08 12:25:20 +0000 | [diff] [blame] | 1103 | # check that the value of the hash doesn't depend on the |
| 1104 | # current context (issue #1757) |
| 1105 | c = getcontext() |
| 1106 | old_precision = c.prec |
| 1107 | x = Decimal("123456789.1") |
| 1108 | |
| 1109 | c.prec = 6 |
| 1110 | h1 = hash(x) |
| 1111 | c.prec = 10 |
| 1112 | h2 = hash(x) |
| 1113 | c.prec = 16 |
| 1114 | h3 = hash(x) |
| 1115 | |
| 1116 | self.assertEqual(h1, h2) |
| 1117 | self.assertEqual(h1, h3) |
| 1118 | c.prec = old_precision |
| 1119 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1120 | def test_min_and_max_methods(self): |
| 1121 | |
| 1122 | d1 = Decimal('15.32') |
| 1123 | d2 = Decimal('28.5') |
| 1124 | l1 = 15 |
| 1125 | l2 = 28 |
| 1126 | |
| 1127 | #between Decimals |
| 1128 | self.failUnless(min(d1,d2) is d1) |
| 1129 | self.failUnless(min(d2,d1) is d1) |
| 1130 | self.failUnless(max(d1,d2) is d2) |
| 1131 | self.failUnless(max(d2,d1) is d2) |
| 1132 | |
| 1133 | #between Decimal and long |
| 1134 | self.failUnless(min(d1,l2) is d1) |
| 1135 | self.failUnless(min(l2,d1) is d1) |
| 1136 | self.failUnless(max(l1,d2) is d2) |
| 1137 | self.failUnless(max(d2,l1) is d2) |
| 1138 | |
| 1139 | def test_as_nonzero(self): |
| 1140 | #as false |
| 1141 | self.failIf(Decimal(0)) |
| 1142 | #as true |
| 1143 | self.failUnless(Decimal('0.372')) |
| 1144 | |
| 1145 | def test_tostring_methods(self): |
| 1146 | #Test str and repr methods. |
| 1147 | |
| 1148 | d = Decimal('15.32') |
| 1149 | self.assertEqual(str(d), '15.32') # str |
Raymond Hettinger | abe3237 | 2008-02-14 02:41:22 +0000 | [diff] [blame] | 1150 | self.assertEqual(repr(d), "Decimal('15.32')") # repr |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1151 | |
| 1152 | def test_tonum_methods(self): |
| 1153 | #Test float, int and long methods. |
| 1154 | |
| 1155 | d1 = Decimal('66') |
| 1156 | d2 = Decimal('15.32') |
| 1157 | |
| 1158 | #int |
| 1159 | self.assertEqual(int(d1), 66) |
| 1160 | self.assertEqual(int(d2), 15) |
| 1161 | |
| 1162 | #long |
| 1163 | self.assertEqual(long(d1), 66) |
| 1164 | self.assertEqual(long(d2), 15) |
| 1165 | |
| 1166 | #float |
| 1167 | self.assertEqual(float(d1), 66) |
| 1168 | self.assertEqual(float(d2), 15.32) |
| 1169 | |
| 1170 | def test_eval_round_trip(self): |
| 1171 | |
| 1172 | #with zero |
| 1173 | d = Decimal( (0, (0,), 0) ) |
| 1174 | self.assertEqual(d, eval(repr(d))) |
| 1175 | |
| 1176 | #int |
| 1177 | d = Decimal( (1, (4, 5), 0) ) |
| 1178 | self.assertEqual(d, eval(repr(d))) |
| 1179 | |
| 1180 | #float |
| 1181 | d = Decimal( (0, (4, 5, 3, 4), -2) ) |
| 1182 | self.assertEqual(d, eval(repr(d))) |
| 1183 | |
| 1184 | #weird |
| 1185 | d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) |
| 1186 | self.assertEqual(d, eval(repr(d))) |
| 1187 | |
| 1188 | def test_as_tuple(self): |
| 1189 | |
| 1190 | #with zero |
| 1191 | d = Decimal(0) |
| 1192 | self.assertEqual(d.as_tuple(), (0, (0,), 0) ) |
| 1193 | |
| 1194 | #int |
| 1195 | d = Decimal(-45) |
| 1196 | self.assertEqual(d.as_tuple(), (1, (4, 5), 0) ) |
| 1197 | |
| 1198 | #complicated string |
| 1199 | d = Decimal("-4.34913534E-17") |
| 1200 | self.assertEqual(d.as_tuple(), (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) ) |
| 1201 | |
| 1202 | #inf |
| 1203 | d = Decimal("Infinity") |
| 1204 | self.assertEqual(d.as_tuple(), (0, (0,), 'F') ) |
| 1205 | |
Facundo Batista | 9b5e231 | 2007-10-19 19:25:57 +0000 | [diff] [blame] | 1206 | #leading zeros in coefficient should be stripped |
| 1207 | d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), -2) ) |
| 1208 | self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), -2) ) |
| 1209 | d = Decimal( (1, (0, 0, 0), 37) ) |
| 1210 | self.assertEqual(d.as_tuple(), (1, (0,), 37)) |
| 1211 | d = Decimal( (1, (), 37) ) |
| 1212 | self.assertEqual(d.as_tuple(), (1, (0,), 37)) |
| 1213 | |
| 1214 | #leading zeros in NaN diagnostic info should be stripped |
| 1215 | d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), 'n') ) |
| 1216 | self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), 'n') ) |
| 1217 | d = Decimal( (1, (0, 0, 0), 'N') ) |
| 1218 | self.assertEqual(d.as_tuple(), (1, (), 'N') ) |
| 1219 | d = Decimal( (1, (), 'n') ) |
| 1220 | self.assertEqual(d.as_tuple(), (1, (), 'n') ) |
| 1221 | |
| 1222 | #coefficient in infinity should be ignored |
| 1223 | d = Decimal( (0, (4, 5, 3, 4), 'F') ) |
| 1224 | self.assertEqual(d.as_tuple(), (0, (0,), 'F')) |
| 1225 | d = Decimal( (1, (0, 2, 7, 1), 'F') ) |
| 1226 | self.assertEqual(d.as_tuple(), (1, (0,), 'F')) |
| 1227 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1228 | def test_immutability_operations(self): |
| 1229 | # Do operations and check that it didn't change change internal objects. |
| 1230 | |
| 1231 | d1 = Decimal('-25e55') |
| 1232 | b1 = Decimal('-25e55') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1233 | d2 = Decimal('33e+33') |
| 1234 | b2 = Decimal('33e+33') |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1235 | |
| 1236 | def checkSameDec(operation, useOther=False): |
| 1237 | if useOther: |
| 1238 | eval("d1." + operation + "(d2)") |
| 1239 | self.assertEqual(d1._sign, b1._sign) |
| 1240 | self.assertEqual(d1._int, b1._int) |
| 1241 | self.assertEqual(d1._exp, b1._exp) |
| 1242 | self.assertEqual(d2._sign, b2._sign) |
| 1243 | self.assertEqual(d2._int, b2._int) |
| 1244 | self.assertEqual(d2._exp, b2._exp) |
| 1245 | else: |
| 1246 | eval("d1." + operation + "()") |
| 1247 | self.assertEqual(d1._sign, b1._sign) |
| 1248 | self.assertEqual(d1._int, b1._int) |
| 1249 | self.assertEqual(d1._exp, b1._exp) |
| 1250 | return |
| 1251 | |
| 1252 | Decimal(d1) |
| 1253 | self.assertEqual(d1._sign, b1._sign) |
| 1254 | self.assertEqual(d1._int, b1._int) |
| 1255 | self.assertEqual(d1._exp, b1._exp) |
| 1256 | |
| 1257 | checkSameDec("__abs__") |
| 1258 | checkSameDec("__add__", True) |
| 1259 | checkSameDec("__div__", True) |
| 1260 | checkSameDec("__divmod__", True) |
Mark Dickinson | 2fc9263 | 2008-02-06 22:10:50 +0000 | [diff] [blame] | 1261 | checkSameDec("__eq__", True) |
| 1262 | checkSameDec("__ne__", True) |
| 1263 | checkSameDec("__le__", True) |
| 1264 | checkSameDec("__lt__", True) |
| 1265 | checkSameDec("__ge__", True) |
| 1266 | checkSameDec("__gt__", True) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1267 | checkSameDec("__float__") |
| 1268 | checkSameDec("__floordiv__", True) |
| 1269 | checkSameDec("__hash__") |
| 1270 | checkSameDec("__int__") |
Raymond Hettinger | 5a05364 | 2008-01-24 19:05:29 +0000 | [diff] [blame] | 1271 | checkSameDec("__trunc__") |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1272 | checkSameDec("__long__") |
| 1273 | checkSameDec("__mod__", True) |
| 1274 | checkSameDec("__mul__", True) |
| 1275 | checkSameDec("__neg__") |
| 1276 | checkSameDec("__nonzero__") |
| 1277 | checkSameDec("__pos__") |
| 1278 | checkSameDec("__pow__", True) |
| 1279 | checkSameDec("__radd__", True) |
| 1280 | checkSameDec("__rdiv__", True) |
| 1281 | checkSameDec("__rdivmod__", True) |
| 1282 | checkSameDec("__repr__") |
| 1283 | checkSameDec("__rfloordiv__", True) |
| 1284 | checkSameDec("__rmod__", True) |
| 1285 | checkSameDec("__rmul__", True) |
| 1286 | checkSameDec("__rpow__", True) |
| 1287 | checkSameDec("__rsub__", True) |
| 1288 | checkSameDec("__str__") |
| 1289 | checkSameDec("__sub__", True) |
| 1290 | checkSameDec("__truediv__", True) |
| 1291 | checkSameDec("adjusted") |
| 1292 | checkSameDec("as_tuple") |
| 1293 | checkSameDec("compare", True) |
| 1294 | checkSameDec("max", True) |
| 1295 | checkSameDec("min", True) |
| 1296 | checkSameDec("normalize") |
| 1297 | checkSameDec("quantize", True) |
| 1298 | checkSameDec("remainder_near", True) |
| 1299 | checkSameDec("same_quantum", True) |
| 1300 | checkSameDec("sqrt") |
| 1301 | checkSameDec("to_eng_string") |
| 1302 | checkSameDec("to_integral") |
| 1303 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1304 | def test_subclassing(self): |
| 1305 | # Different behaviours when subclassing Decimal |
| 1306 | |
| 1307 | class MyDecimal(Decimal): |
| 1308 | pass |
| 1309 | |
| 1310 | d1 = MyDecimal(1) |
| 1311 | d2 = MyDecimal(2) |
| 1312 | d = d1 + d2 |
| 1313 | self.assertTrue(type(d) is Decimal) |
| 1314 | |
| 1315 | d = d1.max(d2) |
| 1316 | self.assertTrue(type(d) is Decimal) |
| 1317 | |
Mark Dickinson | 3b24ccb | 2008-03-25 14:33:23 +0000 | [diff] [blame] | 1318 | def test_implicit_context(self): |
| 1319 | # Check results when context given implicitly. (Issue 2478) |
| 1320 | c = getcontext() |
| 1321 | self.assertEqual(str(Decimal(0).sqrt()), |
| 1322 | str(c.sqrt(Decimal(0)))) |
| 1323 | |
Facundo Batista | 6c398da | 2007-09-17 17:30:13 +0000 | [diff] [blame] | 1324 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1325 | class DecimalPythonAPItests(unittest.TestCase): |
| 1326 | |
| 1327 | def test_pickle(self): |
| 1328 | d = Decimal('-3.141590000') |
| 1329 | p = pickle.dumps(d) |
| 1330 | e = pickle.loads(p) |
| 1331 | self.assertEqual(d, e) |
| 1332 | |
Raymond Hettinger | 5548be2 | 2004-07-05 18:49:38 +0000 | [diff] [blame] | 1333 | def test_int(self): |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1334 | for x in range(-250, 250): |
| 1335 | s = '%0.2f' % (x / 100.0) |
Raymond Hettinger | 5548be2 | 2004-07-05 18:49:38 +0000 | [diff] [blame] | 1336 | # should work the same as for floats |
| 1337 | self.assertEqual(int(Decimal(s)), int(float(s))) |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1338 | # should work the same as to_integral in the ROUND_DOWN mode |
Raymond Hettinger | 5548be2 | 2004-07-05 18:49:38 +0000 | [diff] [blame] | 1339 | d = Decimal(s) |
Raymond Hettinger | 605ed02 | 2004-11-24 07:28:48 +0000 | [diff] [blame] | 1340 | r = d.to_integral(ROUND_DOWN) |
Raymond Hettinger | 5548be2 | 2004-07-05 18:49:38 +0000 | [diff] [blame] | 1341 | self.assertEqual(Decimal(int(d)), r) |
| 1342 | |
Raymond Hettinger | 5a05364 | 2008-01-24 19:05:29 +0000 | [diff] [blame] | 1343 | def test_trunc(self): |
| 1344 | for x in range(-250, 250): |
| 1345 | s = '%0.2f' % (x / 100.0) |
| 1346 | # should work the same as for floats |
| 1347 | self.assertEqual(int(Decimal(s)), int(float(s))) |
| 1348 | # should work the same as to_integral in the ROUND_DOWN mode |
| 1349 | d = Decimal(s) |
| 1350 | r = d.to_integral(ROUND_DOWN) |
Jeffrey Yasskin | ca2b69f | 2008-02-01 06:22:46 +0000 | [diff] [blame] | 1351 | self.assertEqual(Decimal(math.trunc(d)), r) |
Raymond Hettinger | 5a05364 | 2008-01-24 19:05:29 +0000 | [diff] [blame] | 1352 | |
Raymond Hettinger | d9c0a7a | 2004-07-03 10:02:28 +0000 | [diff] [blame] | 1353 | class ContextAPItests(unittest.TestCase): |
| 1354 | |
| 1355 | def test_pickle(self): |
| 1356 | c = Context() |
| 1357 | e = pickle.loads(pickle.dumps(c)) |
| 1358 | for k in vars(c): |
| 1359 | v1 = vars(c)[k] |
| 1360 | v2 = vars(e)[k] |
| 1361 | self.assertEqual(v1, v2) |
| 1362 | |
Raymond Hettinger | 0aeac10 | 2004-07-05 22:53:03 +0000 | [diff] [blame] | 1363 | def test_equality_with_other_types(self): |
| 1364 | self.assert_(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}]) |
| 1365 | self.assert_(Decimal(10) not in ['a', 1.0, (1,2), {}]) |
| 1366 | |
Raymond Hettinger | 955d2b2 | 2004-08-08 20:17:45 +0000 | [diff] [blame] | 1367 | def test_copy(self): |
| 1368 | # All copies should be deep |
| 1369 | c = Context() |
| 1370 | d = c.copy() |
| 1371 | self.assertNotEqual(id(c), id(d)) |
| 1372 | self.assertNotEqual(id(c.flags), id(d.flags)) |
| 1373 | self.assertNotEqual(id(c.traps), id(d.traps)) |
| 1374 | |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 1375 | class WithStatementTest(unittest.TestCase): |
| 1376 | # Can't do these as docstrings until Python 2.6 |
| 1377 | # as doctest can't handle __future__ statements |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 1378 | |
| 1379 | def test_localcontext(self): |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 1380 | # Use a copy of the current context in the block |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 1381 | orig_ctx = getcontext() |
| 1382 | with localcontext() as enter_ctx: |
| 1383 | set_ctx = getcontext() |
| 1384 | final_ctx = getcontext() |
| 1385 | self.assert_(orig_ctx is final_ctx, 'did not restore context correctly') |
| 1386 | self.assert_(orig_ctx is not set_ctx, 'did not copy the context') |
| 1387 | self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context') |
| 1388 | |
| 1389 | def test_localcontextarg(self): |
Nick Coghlan | ced1218 | 2006-09-02 03:54:17 +0000 | [diff] [blame] | 1390 | # Use a copy of the supplied context in the block |
Nick Coghlan | 8b6999b | 2006-08-31 12:00:43 +0000 | [diff] [blame] | 1391 | orig_ctx = getcontext() |
| 1392 | new_ctx = Context(prec=42) |
| 1393 | with localcontext(new_ctx) as enter_ctx: |
| 1394 | set_ctx = getcontext() |
| 1395 | final_ctx = getcontext() |
| 1396 | self.assert_(orig_ctx is final_ctx, 'did not restore context correctly') |
| 1397 | self.assert_(set_ctx.prec == new_ctx.prec, 'did not set correct context') |
| 1398 | self.assert_(new_ctx is not set_ctx, 'did not copy the context') |
| 1399 | self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context') |
| 1400 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1401 | class ContextFlags(unittest.TestCase): |
| 1402 | def test_flags_irrelevant(self): |
| 1403 | # check that the result (numeric result + flags raised) of an |
| 1404 | # arithmetic operation doesn't depend on the current flags |
| 1405 | |
| 1406 | context = Context(prec=9, Emin = -999999999, Emax = 999999999, |
| 1407 | rounding=ROUND_HALF_EVEN, traps=[], flags=[]) |
| 1408 | |
| 1409 | # operations that raise various flags, in the form (function, arglist) |
| 1410 | operations = [ |
| 1411 | (context._apply, [Decimal("100E-1000000009")]), |
| 1412 | (context.sqrt, [Decimal(2)]), |
| 1413 | (context.add, [Decimal("1.23456789"), Decimal("9.87654321")]), |
| 1414 | (context.multiply, [Decimal("1.23456789"), Decimal("9.87654321")]), |
| 1415 | (context.subtract, [Decimal("1.23456789"), Decimal("9.87654321")]), |
| 1416 | ] |
| 1417 | |
| 1418 | # try various flags individually, then a whole lot at once |
| 1419 | flagsets = [[Inexact], [Rounded], [Underflow], [Clamped], [Subnormal], |
| 1420 | [Inexact, Rounded, Underflow, Clamped, Subnormal]] |
| 1421 | |
| 1422 | for fn, args in operations: |
| 1423 | # find answer and flags raised using a clean context |
| 1424 | context.clear_flags() |
| 1425 | ans = fn(*args) |
| 1426 | flags = [k for k, v in context.flags.items() if v] |
| 1427 | |
| 1428 | for extra_flags in flagsets: |
| 1429 | # set flags, before calling operation |
| 1430 | context.clear_flags() |
| 1431 | for flag in extra_flags: |
| 1432 | context._raise_error(flag) |
| 1433 | new_ans = fn(*args) |
| 1434 | |
| 1435 | # flags that we expect to be set after the operation |
| 1436 | expected_flags = list(flags) |
| 1437 | for flag in extra_flags: |
| 1438 | if flag not in expected_flags: |
| 1439 | expected_flags.append(flag) |
| 1440 | expected_flags.sort() |
| 1441 | |
| 1442 | # flags we actually got |
| 1443 | new_flags = [k for k,v in context.flags.items() if v] |
| 1444 | new_flags.sort() |
| 1445 | |
| 1446 | self.assertEqual(ans, new_ans, |
| 1447 | "operation produces different answers depending on flags set: " + |
| 1448 | "expected %s, got %s." % (ans, new_ans)) |
| 1449 | self.assertEqual(new_flags, expected_flags, |
| 1450 | "operation raises different flags depending on flags set: " + |
| 1451 | "expected %s, got %s" % (expected_flags, new_flags)) |
| 1452 | |
| 1453 | def test_main(arith=False, verbose=None, todo_tests=None, debug=None): |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1454 | """ Execute the tests. |
| 1455 | |
Raymond Hettinger | ed20ad8 | 2004-09-04 20:09:13 +0000 | [diff] [blame] | 1456 | Runs all arithmetic tests if arith is True or if the "decimal" resource |
| 1457 | is enabled in regrtest.py |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1458 | """ |
Raymond Hettinger | ed20ad8 | 2004-09-04 20:09:13 +0000 | [diff] [blame] | 1459 | |
Neal Norwitz | ce4a9c9 | 2006-04-09 08:36:46 +0000 | [diff] [blame] | 1460 | init() |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1461 | global TEST_ALL, DEBUG |
Raymond Hettinger | ed20ad8 | 2004-09-04 20:09:13 +0000 | [diff] [blame] | 1462 | TEST_ALL = arith or is_resource_enabled('decimal') |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1463 | DEBUG = debug |
Raymond Hettinger | ed20ad8 | 2004-09-04 20:09:13 +0000 | [diff] [blame] | 1464 | |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1465 | if todo_tests is None: |
| 1466 | test_classes = [ |
| 1467 | DecimalExplicitConstructionTest, |
| 1468 | DecimalImplicitConstructionTest, |
| 1469 | DecimalArithmeticOperatorsTest, |
Mark Dickinson | 1ddf1d8 | 2008-02-29 02:16:37 +0000 | [diff] [blame] | 1470 | DecimalFormatTest, |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1471 | DecimalUseOfContextTest, |
| 1472 | DecimalUsabilityTest, |
| 1473 | DecimalPythonAPItests, |
| 1474 | ContextAPItests, |
| 1475 | DecimalTest, |
| 1476 | WithStatementTest, |
| 1477 | ContextFlags |
| 1478 | ] |
| 1479 | else: |
| 1480 | test_classes = [DecimalTest] |
| 1481 | |
| 1482 | # Dynamically build custom test definition for each file in the test |
| 1483 | # directory and add the definitions to the DecimalTest class. This |
| 1484 | # procedure insures that new files do not get skipped. |
| 1485 | for filename in os.listdir(directory): |
| 1486 | if '.decTest' not in filename or filename.startswith("."): |
| 1487 | continue |
| 1488 | head, tail = filename.split('.') |
| 1489 | if todo_tests is not None and head not in todo_tests: |
| 1490 | continue |
| 1491 | tester = lambda self, f=filename: self.eval_file(directory + f) |
| 1492 | setattr(DecimalTest, 'test_' + head, tester) |
| 1493 | del filename, head, tail, tester |
| 1494 | |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1495 | |
Tim Peters | 46cc702 | 2006-03-31 04:11:16 +0000 | [diff] [blame] | 1496 | try: |
| 1497 | run_unittest(*test_classes) |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1498 | if todo_tests is None: |
| 1499 | import decimal as DecimalModule |
| 1500 | run_doctest(DecimalModule, verbose) |
Tim Peters | 46cc702 | 2006-03-31 04:11:16 +0000 | [diff] [blame] | 1501 | finally: |
| 1502 | setcontext(ORIGINAL_CONTEXT) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1503 | |
| 1504 | if __name__ == '__main__': |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1505 | import optparse |
| 1506 | p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]") |
| 1507 | p.add_option('--debug', '-d', action='store_true', help='shows the test number and context before each test') |
| 1508 | p.add_option('--skip', '-s', action='store_true', help='skip over 90% of the arithmetic tests') |
| 1509 | (opt, args) = p.parse_args() |
| 1510 | |
| 1511 | if opt.skip: |
| 1512 | test_main(arith=False, verbose=True) |
| 1513 | elif args: |
| 1514 | test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug) |
Raymond Hettinger | 7c85fa4 | 2004-07-01 11:01:35 +0000 | [diff] [blame] | 1515 | else: |
Facundo Batista | 353750c | 2007-09-13 18:13:15 +0000 | [diff] [blame] | 1516 | test_main(arith=True, verbose=True) |