blob: e82a9b9023677deb05367e8e3a939dd8857b3f48 [file] [log] [blame]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001# 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"""
11These are the test cases for the Decimal module.
12
13There are two groups of tests, Arithmetic and Behaviour. The former test
14the Decimal arithmetic using the tests provided by Mike Cowlishaw. The latter
15test the pythonic behaviour according to PEP 327.
16
17Cowlishaw's tests can be downloaded from:
18
19 www2.hursley.ibm.com/decimal/dectest.zip
20
21This test module can be called from command line with one parameter (Arithmetic
22or Behaviour) to test each part, or without parameter to test both parts. If
23you're working through IDLE, you can import this test module and call test_main()
24with the corresponding argument.
25"""
26
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027import glob
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +000028import math
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000029import os, sys
30import pickle, copy
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +000031import unittest
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000032from decimal import *
Raymond Hettinger45fd4762009-02-03 03:42:07 +000033import numbers
Tim Peters46cc7022006-03-31 04:11:16 +000034from test.test_support import (TestSkipped, run_unittest, run_doctest,
35 is_resource_enabled)
Raymond Hettinger0aeac102004-07-05 22:53:03 +000036import random
Raymond Hettinger7e71fa52004-12-18 19:07:19 +000037try:
38 import threading
39except ImportError:
40 threading = None
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000041
Raymond Hettingerfed52962004-07-14 15:41:57 +000042# Useful Test Constant
43Signals = getcontext().flags.keys()
44
Tim Peters46cc7022006-03-31 04:11:16 +000045# Tests are built around these assumed context defaults.
46# test_main() restores the original context.
Neal Norwitzce4a9c92006-04-09 08:36:46 +000047def init():
48 global ORIGINAL_CONTEXT
49 ORIGINAL_CONTEXT = getcontext().copy()
Facundo Batistaee340e52008-05-02 17:39:00 +000050 DefaultTestContext = Context(
51 prec = 9,
52 rounding = ROUND_HALF_EVEN,
53 traps = dict.fromkeys(Signals, 0)
54 )
55 setcontext(DefaultTestContext)
Raymond Hettinger6ea48452004-07-03 12:26:21 +000056
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000057TESTDATADIR = 'decimaltestdata'
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +000058if __name__ == '__main__':
59 file = sys.argv[0]
60else:
61 file = __file__
62testdir = os.path.dirname(file) or os.curdir
Raymond Hettinger267b8682005-03-27 10:47:39 +000063directory = testdir + os.sep + TESTDATADIR + os.sep
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000064
Raymond Hettinger267b8682005-03-27 10:47:39 +000065skip_expected = not os.path.isdir(directory)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000066
67# Make sure it actually raises errors when not expected and caught in flags
68# Slower, since it runs some things several times.
69EXTENDEDERRORTEST = False
70
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000071#Map the test cases' error names to the actual errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072ErrorNames = {'clamped' : Clamped,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000073 'conversion_syntax' : InvalidOperation,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000074 'division_by_zero' : DivisionByZero,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000075 'division_impossible' : InvalidOperation,
76 'division_undefined' : InvalidOperation,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077 'inexact' : Inexact,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000078 'invalid_context' : InvalidOperation,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000079 'invalid_operation' : InvalidOperation,
80 'overflow' : Overflow,
81 'rounded' : Rounded,
82 'subnormal' : Subnormal,
83 'underflow' : Underflow}
84
85
86def Nonfunction(*args):
87 """Doesn't do anything."""
88 return None
89
90RoundingDict = {'ceiling' : ROUND_CEILING, #Maps test-case names to roundings.
91 'down' : ROUND_DOWN,
92 'floor' : ROUND_FLOOR,
93 'half_down' : ROUND_HALF_DOWN,
94 'half_even' : ROUND_HALF_EVEN,
95 'half_up' : ROUND_HALF_UP,
Facundo Batista353750c2007-09-13 18:13:15 +000096 'up' : ROUND_UP,
97 '05up' : ROUND_05UP}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000098
99# Name adapter to be able to change the Decimal and Context
100# interface without changing the test files from Cowlishaw
Facundo Batista1a191df2007-10-02 17:01:24 +0000101nameAdapter = {'and':'logical_and',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102 'apply':'_apply',
Facundo Batista353750c2007-09-13 18:13:15 +0000103 'class':'number_class',
104 'comparesig':'compare_signal',
105 'comparetotal':'compare_total',
106 'comparetotmag':'compare_total_mag',
Facundo Batista353750c2007-09-13 18:13:15 +0000107 'copy':'copy_decimal',
Facundo Batista1a191df2007-10-02 17:01:24 +0000108 'copyabs':'copy_abs',
Facundo Batista353750c2007-09-13 18:13:15 +0000109 'copynegate':'copy_negate',
110 'copysign':'copy_sign',
Facundo Batista1a191df2007-10-02 17:01:24 +0000111 'divideint':'divide_int',
Facundo Batista353750c2007-09-13 18:13:15 +0000112 'invert':'logical_invert',
Facundo Batista1a191df2007-10-02 17:01:24 +0000113 'iscanonical':'is_canonical',
114 'isfinite':'is_finite',
115 'isinfinite':'is_infinite',
116 'isnan':'is_nan',
117 'isnormal':'is_normal',
118 'isqnan':'is_qnan',
119 'issigned':'is_signed',
120 'issnan':'is_snan',
121 'issubnormal':'is_subnormal',
122 'iszero':'is_zero',
Facundo Batista353750c2007-09-13 18:13:15 +0000123 'maxmag':'max_mag',
124 'minmag':'min_mag',
125 'nextminus':'next_minus',
126 'nextplus':'next_plus',
127 'nexttoward':'next_toward',
Facundo Batista1a191df2007-10-02 17:01:24 +0000128 'or':'logical_or',
Facundo Batista353750c2007-09-13 18:13:15 +0000129 'reduce':'normalize',
Facundo Batista1a191df2007-10-02 17:01:24 +0000130 'remaindernear':'remainder_near',
131 'samequantum':'same_quantum',
132 'squareroot':'sqrt',
133 'toeng':'to_eng_string',
134 'tointegral':'to_integral_value',
135 'tointegralx':'to_integral_exact',
136 'tosci':'to_sci_string',
137 'xor':'logical_xor',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000138 }
139
Facundo Batista1a191df2007-10-02 17:01:24 +0000140# The following functions return True/False rather than a Decimal instance
141
142LOGICAL_FUNCTIONS = (
143 'is_canonical',
144 'is_finite',
145 'is_infinite',
146 'is_nan',
147 'is_normal',
148 'is_qnan',
149 'is_signed',
150 'is_snan',
151 'is_subnormal',
152 'is_zero',
153 'same_quantum',
154 )
155
Facundo Batista353750c2007-09-13 18:13:15 +0000156# For some operations (currently exp, ln, log10, power), the decNumber
157# reference implementation imposes additional restrictions on the
158# context and operands. These restrictions are not part of the
159# specification; however, the effect of these restrictions does show
160# up in some of the testcases. We skip testcases that violate these
161# restrictions, since Decimal behaves differently from decNumber for
162# these testcases so these testcases would otherwise fail.
163
164decNumberRestricted = ('power', 'ln', 'log10', 'exp')
165DEC_MAX_MATH = 999999
166def outside_decNumber_bounds(v, context):
167 if (context.prec > DEC_MAX_MATH or
168 context.Emax > DEC_MAX_MATH or
169 -context.Emin > DEC_MAX_MATH):
170 return True
171 if not v._is_special and v and (
Facundo Batista353750c2007-09-13 18:13:15 +0000172 v.adjusted() > DEC_MAX_MATH or
173 v.adjusted() < 1-2*DEC_MAX_MATH):
174 return True
175 return False
176
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000177class DecimalTest(unittest.TestCase):
178 """Class which tests the Decimal class against the test cases.
179
180 Changed for unittest.
181 """
182 def setUp(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000183 self.context = Context()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000184 self.ignore_list = ['#']
185 # Basically, a # means return NaN InvalidOperation.
186 # Different from a sNaN in trim
187
188 self.ChangeDict = {'precision' : self.change_precision,
189 'rounding' : self.change_rounding_method,
190 'maxexponent' : self.change_max_exponent,
191 'minexponent' : self.change_min_exponent,
192 'clamp' : self.change_clamp}
193
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000194 def eval_file(self, file):
195 global skip_expected
196 if skip_expected:
197 raise TestSkipped
198 return
199 for line in open(file).xreadlines():
200 line = line.replace('\r\n', '').replace('\n', '')
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000201 #print line
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000202 try:
203 t = self.eval_line(line)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000204 except DecimalException, exception:
205 #Exception raised where there shoudn't have been one.
206 self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
207
208 return
209
210 def eval_line(self, s):
211 if s.find(' -> ') >= 0 and s[:2] != '--' and not s.startswith(' --'):
212 s = (s.split('->')[0] + '->' +
213 s.split('->')[1].split('--')[0]).strip()
214 else:
215 s = s.split('--')[0].strip()
216
217 for ignore in self.ignore_list:
218 if s.find(ignore) >= 0:
219 #print s.split()[0], 'NotImplemented--', ignore
220 return
221 if not s:
222 return
223 elif ':' in s:
224 return self.eval_directive(s)
225 else:
226 return self.eval_equation(s)
227
228 def eval_directive(self, s):
229 funct, value = map(lambda x: x.strip().lower(), s.split(':'))
230 if funct == 'rounding':
231 value = RoundingDict[value]
232 else:
233 try:
234 value = int(value)
235 except ValueError:
236 pass
237
238 funct = self.ChangeDict.get(funct, Nonfunction)
239 funct(value)
240
241 def eval_equation(self, s):
242 #global DEFAULT_PRECISION
243 #print DEFAULT_PRECISION
Raymond Hettingered20ad82004-09-04 20:09:13 +0000244
245 if not TEST_ALL and random.random() < 0.90:
246 return
247
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000248 try:
249 Sides = s.split('->')
250 L = Sides[0].strip().split()
251 id = L[0]
Facundo Batista353750c2007-09-13 18:13:15 +0000252 if DEBUG:
253 print "Test ", id,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000254 funct = L[1].lower()
255 valstemp = L[2:]
256 L = Sides[1].strip().split()
257 ans = L[0]
258 exceptions = L[1:]
259 except (TypeError, AttributeError, IndexError):
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000260 raise InvalidOperation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000261 def FixQuotes(val):
262 val = val.replace("''", 'SingleQuote').replace('""', 'DoubleQuote')
263 val = val.replace("'", '').replace('"', '')
264 val = val.replace('SingleQuote', "'").replace('DoubleQuote', '"')
265 return val
266 fname = nameAdapter.get(funct, funct)
267 if fname == 'rescale':
268 return
269 funct = getattr(self.context, fname)
270 vals = []
271 conglomerate = ''
272 quote = 0
273 theirexceptions = [ErrorNames[x.lower()] for x in exceptions]
274
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000275 for exception in Signals:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000276 self.context.traps[exception] = 1 #Catch these bugs...
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000277 for exception in theirexceptions:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000278 self.context.traps[exception] = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000279 for i, val in enumerate(valstemp):
280 if val.count("'") % 2 == 1:
281 quote = 1 - quote
282 if quote:
283 conglomerate = conglomerate + ' ' + val
284 continue
285 else:
286 val = conglomerate + val
287 conglomerate = ''
288 v = FixQuotes(val)
289 if fname in ('to_sci_string', 'to_eng_string'):
290 if EXTENDEDERRORTEST:
291 for error in theirexceptions:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000292 self.context.traps[error] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000293 try:
294 funct(self.context.create_decimal(v))
295 except error:
296 pass
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000297 except Signals, e:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000298 self.fail("Raised %s in %s when %s disabled" % \
299 (e, s, error))
300 else:
301 self.fail("Did not raise %s in %s" % (error, s))
Raymond Hettingerbf440692004-07-10 14:14:37 +0000302 self.context.traps[error] = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000303 v = self.context.create_decimal(v)
304 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000305 v = Decimal(v, self.context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306 vals.append(v)
307
308 ans = FixQuotes(ans)
309
Facundo Batista353750c2007-09-13 18:13:15 +0000310 # skip tests that are related to bounds imposed in the decNumber
311 # reference implementation
312 if fname in decNumberRestricted:
313 if fname == 'power':
314 if not (vals[1]._isinteger() and
315 -1999999997 <= vals[1] <= 999999999):
316 if outside_decNumber_bounds(vals[0], self.context) or \
317 outside_decNumber_bounds(vals[1], self.context):
318 #print "Skipping test %s" % s
319 return
320 else:
321 if outside_decNumber_bounds(vals[0], self.context):
322 #print "Skipping test %s" % s
323 return
324
325
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000326 if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'):
327 for error in theirexceptions:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000328 self.context.traps[error] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000329 try:
330 funct(*vals)
331 except error:
332 pass
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000333 except Signals, e:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 self.fail("Raised %s in %s when %s disabled" % \
335 (e, s, error))
336 else:
337 self.fail("Did not raise %s in %s" % (error, s))
Raymond Hettingerbf440692004-07-10 14:14:37 +0000338 self.context.traps[error] = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000339 if DEBUG:
340 print "--", self.context
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 try:
342 result = str(funct(*vals))
Facundo Batista1a191df2007-10-02 17:01:24 +0000343 if fname in LOGICAL_FUNCTIONS:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 result = str(int(eval(result))) # 'True', 'False' -> '1', '0'
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000345 except Signals, error:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000346 self.fail("Raised %s in %s" % (error, s))
347 except: #Catch any error long enough to state the test case.
348 print "ERROR:", s
349 raise
350
351 myexceptions = self.getexceptions()
Raymond Hettingerbf440692004-07-10 14:14:37 +0000352 self.context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000353
354 myexceptions.sort()
355 theirexceptions.sort()
356
357 self.assertEqual(result, ans,
358 'Incorrect answer for ' + s + ' -- got ' + result)
359 self.assertEqual(myexceptions, theirexceptions,
Facundo Batista353750c2007-09-13 18:13:15 +0000360 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000361 return
362
363 def getexceptions(self):
Raymond Hettingerf63ba432004-08-17 05:42:09 +0000364 return [e for e in Signals if self.context.flags[e]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000365
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366 def change_precision(self, prec):
367 self.context.prec = prec
368 def change_rounding_method(self, rounding):
369 self.context.rounding = rounding
370 def change_min_exponent(self, exp):
371 self.context.Emin = exp
372 def change_max_exponent(self, exp):
373 self.context.Emax = exp
374 def change_clamp(self, clamp):
375 self.context._clamp = clamp
376
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000377
378
379# The following classes test the behaviour of Decimal according to PEP 327
380
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000381class DecimalExplicitConstructionTest(unittest.TestCase):
382 '''Unit tests for Explicit Construction cases of Decimal.'''
383
384 def test_explicit_empty(self):
385 self.assertEqual(Decimal(), Decimal("0"))
386
387 def test_explicit_from_None(self):
388 self.assertRaises(TypeError, Decimal, None)
389
390 def test_explicit_from_int(self):
391
392 #positive
393 d = Decimal(45)
394 self.assertEqual(str(d), '45')
395
396 #very large positive
397 d = Decimal(500000123)
398 self.assertEqual(str(d), '500000123')
399
400 #negative
401 d = Decimal(-45)
402 self.assertEqual(str(d), '-45')
403
404 #zero
405 d = Decimal(0)
406 self.assertEqual(str(d), '0')
407
408 def test_explicit_from_string(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000409
410 #empty
411 self.assertEqual(str(Decimal('')), 'NaN')
412
413 #int
414 self.assertEqual(str(Decimal('45')), '45')
415
416 #float
417 self.assertEqual(str(Decimal('45.34')), '45.34')
418
419 #engineer notation
420 self.assertEqual(str(Decimal('45e2')), '4.5E+3')
421
422 #just not a number
423 self.assertEqual(str(Decimal('ugly')), 'NaN')
424
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000425 #leading and trailing whitespace permitted
426 self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4')
427 self.assertEqual(str(Decimal(' -7.89')), '-7.89')
428
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000429 #unicode strings should be permitted
430 self.assertEqual(str(Decimal(u'0E-017')), '0E-17')
431 self.assertEqual(str(Decimal(u'45')), '45')
432 self.assertEqual(str(Decimal(u'-Inf')), '-Infinity')
433 self.assertEqual(str(Decimal(u'NaN123')), 'NaN123')
434
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000435 def test_explicit_from_tuples(self):
436
437 #zero
438 d = Decimal( (0, (0,), 0) )
439 self.assertEqual(str(d), '0')
440
441 #int
442 d = Decimal( (1, (4, 5), 0) )
443 self.assertEqual(str(d), '-45')
444
445 #float
446 d = Decimal( (0, (4, 5, 3, 4), -2) )
447 self.assertEqual(str(d), '45.34')
448
449 #weird
450 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
451 self.assertEqual(str(d), '-4.34913534E-17')
452
453 #wrong number of items
454 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1)) )
455
456 #bad sign
457 self.assertRaises(ValueError, Decimal, (8, (4, 3, 4, 9, 1), 2) )
Facundo Batista9b5e2312007-10-19 19:25:57 +0000458 self.assertRaises(ValueError, Decimal, (0., (4, 3, 4, 9, 1), 2) )
459 self.assertRaises(ValueError, Decimal, (Decimal(1), (4, 3, 4, 9, 1), 2))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000460
461 #bad exp
462 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 'wrong!') )
Facundo Batista9b5e2312007-10-19 19:25:57 +0000463 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) )
464 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000465
466 #bad coefficients
467 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) )
468 self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) )
Facundo Batista9b5e2312007-10-19 19:25:57 +0000469 self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) )
Facundo Batista72bc54f2007-11-23 17:59:00 +0000470 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000471
472 def test_explicit_from_Decimal(self):
473
474 #positive
475 d = Decimal(45)
476 e = Decimal(d)
477 self.assertEqual(str(e), '45')
478 self.assertNotEqual(id(d), id(e))
479
480 #very large positive
481 d = Decimal(500000123)
482 e = Decimal(d)
483 self.assertEqual(str(e), '500000123')
484 self.assertNotEqual(id(d), id(e))
485
486 #negative
487 d = Decimal(-45)
488 e = Decimal(d)
489 self.assertEqual(str(e), '-45')
490 self.assertNotEqual(id(d), id(e))
491
492 #zero
493 d = Decimal(0)
494 e = Decimal(d)
495 self.assertEqual(str(e), '0')
496 self.assertNotEqual(id(d), id(e))
497
498 def test_explicit_context_create_decimal(self):
499
500 nc = copy.copy(getcontext())
501 nc.prec = 3
502
503 # empty
Raymond Hettingerfed52962004-07-14 15:41:57 +0000504 d = Decimal()
505 self.assertEqual(str(d), '0')
506 d = nc.create_decimal()
507 self.assertEqual(str(d), '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000508
509 # from None
510 self.assertRaises(TypeError, nc.create_decimal, None)
511
512 # from int
513 d = nc.create_decimal(456)
514 self.failUnless(isinstance(d, Decimal))
515 self.assertEqual(nc.create_decimal(45678),
516 nc.create_decimal('457E+2'))
517
518 # from string
519 d = Decimal('456789')
520 self.assertEqual(str(d), '456789')
521 d = nc.create_decimal('456789')
522 self.assertEqual(str(d), '4.57E+5')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000523 # leading and trailing whitespace should result in a NaN;
524 # spaces are already checked in Cowlishaw's test-suite, so
525 # here we just check that a trailing newline results in a NaN
526 self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000527
528 # from tuples
529 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
530 self.assertEqual(str(d), '-4.34913534E-17')
531 d = nc.create_decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
532 self.assertEqual(str(d), '-4.35E-17')
533
534 # from Decimal
535 prevdec = Decimal(500000123)
536 d = Decimal(prevdec)
537 self.assertEqual(str(d), '500000123')
538 d = nc.create_decimal(prevdec)
539 self.assertEqual(str(d), '5.00E+8')
540
Mark Dickinson9a6e6452009-08-02 11:01:01 +0000541 def test_unicode_digits(self):
542 test_values = {
543 u'\uff11': '1',
544 u'\u0660.\u0660\u0663\u0667\u0662e-\u0663' : '0.0000372',
545 u'-nan\u0c68\u0c6a\u0c66\u0c66' : '-NaN2400',
546 }
547 for input, expected in test_values.items():
548 self.assertEqual(str(Decimal(input)), expected)
549
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000550
551class DecimalImplicitConstructionTest(unittest.TestCase):
552 '''Unit tests for Implicit Construction cases of Decimal.'''
553
554 def test_implicit_from_None(self):
555 self.assertRaises(TypeError, eval, 'Decimal(5) + None', globals())
556
557 def test_implicit_from_int(self):
558 #normal
559 self.assertEqual(str(Decimal(5) + 45), '50')
560 #exceeding precision
561 self.assertEqual(Decimal(5) + 123456789000, Decimal(123456789000))
562
563 def test_implicit_from_string(self):
564 self.assertRaises(TypeError, eval, 'Decimal(5) + "3"', globals())
565
566 def test_implicit_from_float(self):
567 self.assertRaises(TypeError, eval, 'Decimal(5) + 2.2', globals())
568
569 def test_implicit_from_Decimal(self):
570 self.assertEqual(Decimal(5) + Decimal(45), Decimal(50))
571
Raymond Hettinger267b8682005-03-27 10:47:39 +0000572 def test_rop(self):
573 # Allow other classes to be trained to interact with Decimals
574 class E:
575 def __divmod__(self, other):
576 return 'divmod ' + str(other)
577 def __rdivmod__(self, other):
578 return str(other) + ' rdivmod'
579 def __lt__(self, other):
580 return 'lt ' + str(other)
581 def __gt__(self, other):
582 return 'gt ' + str(other)
583 def __le__(self, other):
584 return 'le ' + str(other)
585 def __ge__(self, other):
586 return 'ge ' + str(other)
587 def __eq__(self, other):
588 return 'eq ' + str(other)
589 def __ne__(self, other):
590 return 'ne ' + str(other)
591
592 self.assertEqual(divmod(E(), Decimal(10)), 'divmod 10')
593 self.assertEqual(divmod(Decimal(10), E()), '10 rdivmod')
594 self.assertEqual(eval('Decimal(10) < E()'), 'gt 10')
595 self.assertEqual(eval('Decimal(10) > E()'), 'lt 10')
596 self.assertEqual(eval('Decimal(10) <= E()'), 'ge 10')
597 self.assertEqual(eval('Decimal(10) >= E()'), 'le 10')
598 self.assertEqual(eval('Decimal(10) == E()'), 'eq 10')
599 self.assertEqual(eval('Decimal(10) != E()'), 'ne 10')
600
601 # insert operator methods and then exercise them
Georg Brandl96c3f7f2006-03-28 08:06:35 +0000602 oplist = [
603 ('+', '__add__', '__radd__'),
604 ('-', '__sub__', '__rsub__'),
605 ('*', '__mul__', '__rmul__'),
606 ('%', '__mod__', '__rmod__'),
607 ('//', '__floordiv__', '__rfloordiv__'),
608 ('**', '__pow__', '__rpow__')
609 ]
610 if 1/2 == 0:
611 # testing with classic division, so add __div__
612 oplist.append(('/', '__div__', '__rdiv__'))
613 else:
614 # testing with -Qnew, so add __truediv__
615 oplist.append(('/', '__truediv__', '__rtruediv__'))
Anthony Baxter4ef3a232006-03-30 12:59:11 +0000616
Georg Brandl96c3f7f2006-03-28 08:06:35 +0000617 for sym, lop, rop in oplist:
Raymond Hettinger267b8682005-03-27 10:47:39 +0000618 setattr(E, lop, lambda self, other: 'str' + lop + str(other))
619 setattr(E, rop, lambda self, other: str(other) + rop + 'str')
620 self.assertEqual(eval('E()' + sym + 'Decimal(10)'),
621 'str' + lop + '10')
622 self.assertEqual(eval('Decimal(10)' + sym + 'E()'),
623 '10' + rop + 'str')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624
Mark Dickinson1ddf1d82008-02-29 02:16:37 +0000625class DecimalFormatTest(unittest.TestCase):
626 '''Unit tests for the format function.'''
627 def test_formatting(self):
628 # triples giving a format, a Decimal, and the expected result
629 test_values = [
630 ('e', '0E-15', '0e-15'),
631 ('e', '2.3E-15', '2.3e-15'),
632 ('e', '2.30E+2', '2.30e+2'), # preserve significant zeros
633 ('e', '2.30000E-15', '2.30000e-15'),
634 ('e', '1.23456789123456789e40', '1.23456789123456789e+40'),
635 ('e', '1.5', '1.5e+0'),
636 ('e', '0.15', '1.5e-1'),
637 ('e', '0.015', '1.5e-2'),
638 ('e', '0.0000000000015', '1.5e-12'),
639 ('e', '15.0', '1.50e+1'),
640 ('e', '-15', '-1.5e+1'),
641 ('e', '0', '0e+0'),
642 ('e', '0E1', '0e+1'),
643 ('e', '0.0', '0e-1'),
644 ('e', '0.00', '0e-2'),
645 ('.6e', '0E-15', '0.000000e-9'),
646 ('.6e', '0', '0.000000e+6'),
647 ('.6e', '9.999999', '9.999999e+0'),
648 ('.6e', '9.9999999', '1.000000e+1'),
649 ('.6e', '-1.23e5', '-1.230000e+5'),
650 ('.6e', '1.23456789e-3', '1.234568e-3'),
651 ('f', '0', '0'),
652 ('f', '0.0', '0.0'),
653 ('f', '0E-2', '0.00'),
654 ('f', '0.00E-8', '0.0000000000'),
655 ('f', '0E1', '0'), # loses exponent information
656 ('f', '3.2E1', '32'),
657 ('f', '3.2E2', '320'),
658 ('f', '3.20E2', '320'),
659 ('f', '3.200E2', '320.0'),
660 ('f', '3.2E-6', '0.0000032'),
661 ('.6f', '0E-15', '0.000000'), # all zeros treated equally
662 ('.6f', '0E1', '0.000000'),
663 ('.6f', '0', '0.000000'),
664 ('.0f', '0', '0'), # no decimal point
665 ('.0f', '0e-2', '0'),
666 ('.0f', '3.14159265', '3'),
667 ('.1f', '3.14159265', '3.1'),
668 ('.4f', '3.14159265', '3.1416'),
669 ('.6f', '3.14159265', '3.141593'),
670 ('.7f', '3.14159265', '3.1415926'), # round-half-even!
671 ('.8f', '3.14159265', '3.14159265'),
672 ('.9f', '3.14159265', '3.141592650'),
673
674 ('g', '0', '0'),
675 ('g', '0.0', '0.0'),
676 ('g', '0E1', '0e+1'),
677 ('G', '0E1', '0E+1'),
678 ('g', '0E-5', '0.00000'),
679 ('g', '0E-6', '0.000000'),
680 ('g', '0E-7', '0e-7'),
681 ('g', '-0E2', '-0e+2'),
682 ('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig
683 ('.1g', '3.14159265', '3'),
684 ('.2g', '3.14159265', '3.1'),
685 ('.5g', '3.14159265', '3.1416'),
686 ('.7g', '3.14159265', '3.141593'),
687 ('.8g', '3.14159265', '3.1415926'), # round-half-even!
688 ('.9g', '3.14159265', '3.14159265'),
689 ('.10g', '3.14159265', '3.14159265'), # don't pad
690
691 ('%', '0E1', '0%'),
692 ('%', '0E0', '0%'),
693 ('%', '0E-1', '0%'),
694 ('%', '0E-2', '0%'),
695 ('%', '0E-3', '0.0%'),
696 ('%', '0E-4', '0.00%'),
697
698 ('.3%', '0', '0.000%'), # all zeros treated equally
699 ('.3%', '0E10', '0.000%'),
700 ('.3%', '0E-10', '0.000%'),
701 ('.3%', '2.34', '234.000%'),
702 ('.3%', '1.234567', '123.457%'),
703 ('.0%', '1.23', '123%'),
704
705 ('e', 'NaN', 'NaN'),
706 ('f', '-NaN123', '-NaN123'),
707 ('+g', 'NaN456', '+NaN456'),
708 ('.3e', 'Inf', 'Infinity'),
709 ('.16f', '-Inf', '-Infinity'),
710 ('.0g', '-sNaN', '-sNaN'),
711
712 ('', '1.00', '1.00'),
Mark Dickinson71416822009-03-17 18:07:41 +0000713
714 # check alignment
715 ('<6', '123', '123 '),
716 ('>6', '123', ' 123'),
717 ('^6', '123', ' 123 '),
718 ('=+6', '123', '+ 123'),
Mark Dickinson1ddf1d82008-02-29 02:16:37 +0000719 ]
720 for fmt, d, result in test_values:
721 self.assertEqual(format(Decimal(d), fmt), result)
722
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000723class DecimalArithmeticOperatorsTest(unittest.TestCase):
724 '''Unit tests for all arithmetic operators, binary and unary.'''
725
726 def test_addition(self):
727
728 d1 = Decimal('-11.1')
729 d2 = Decimal('22.2')
730
731 #two Decimals
732 self.assertEqual(d1+d2, Decimal('11.1'))
733 self.assertEqual(d2+d1, Decimal('11.1'))
734
735 #with other type, left
736 c = d1 + 5
737 self.assertEqual(c, Decimal('-6.1'))
738 self.assertEqual(type(c), type(d1))
739
740 #with other type, right
741 c = 5 + d1
742 self.assertEqual(c, Decimal('-6.1'))
743 self.assertEqual(type(c), type(d1))
744
745 #inline with decimal
746 d1 += d2
747 self.assertEqual(d1, Decimal('11.1'))
748
749 #inline with other type
750 d1 += 5
751 self.assertEqual(d1, Decimal('16.1'))
752
753 def test_subtraction(self):
754
755 d1 = Decimal('-11.1')
756 d2 = Decimal('22.2')
757
758 #two Decimals
759 self.assertEqual(d1-d2, Decimal('-33.3'))
760 self.assertEqual(d2-d1, Decimal('33.3'))
761
762 #with other type, left
763 c = d1 - 5
764 self.assertEqual(c, Decimal('-16.1'))
765 self.assertEqual(type(c), type(d1))
766
767 #with other type, right
768 c = 5 - d1
769 self.assertEqual(c, Decimal('16.1'))
770 self.assertEqual(type(c), type(d1))
771
772 #inline with decimal
773 d1 -= d2
774 self.assertEqual(d1, Decimal('-33.3'))
775
776 #inline with other type
777 d1 -= 5
778 self.assertEqual(d1, Decimal('-38.3'))
779
780 def test_multiplication(self):
781
782 d1 = Decimal('-5')
783 d2 = Decimal('3')
784
785 #two Decimals
786 self.assertEqual(d1*d2, Decimal('-15'))
787 self.assertEqual(d2*d1, Decimal('-15'))
788
789 #with other type, left
790 c = d1 * 5
791 self.assertEqual(c, Decimal('-25'))
792 self.assertEqual(type(c), type(d1))
793
794 #with other type, right
795 c = 5 * d1
796 self.assertEqual(c, Decimal('-25'))
797 self.assertEqual(type(c), type(d1))
798
799 #inline with decimal
800 d1 *= d2
801 self.assertEqual(d1, Decimal('-15'))
802
803 #inline with other type
804 d1 *= 5
805 self.assertEqual(d1, Decimal('-75'))
806
807 def test_division(self):
808
809 d1 = Decimal('-5')
810 d2 = Decimal('2')
811
812 #two Decimals
813 self.assertEqual(d1/d2, Decimal('-2.5'))
814 self.assertEqual(d2/d1, Decimal('-0.4'))
815
816 #with other type, left
817 c = d1 / 4
818 self.assertEqual(c, Decimal('-1.25'))
819 self.assertEqual(type(c), type(d1))
820
821 #with other type, right
822 c = 4 / d1
823 self.assertEqual(c, Decimal('-0.8'))
824 self.assertEqual(type(c), type(d1))
825
826 #inline with decimal
827 d1 /= d2
828 self.assertEqual(d1, Decimal('-2.5'))
829
830 #inline with other type
831 d1 /= 4
832 self.assertEqual(d1, Decimal('-0.625'))
833
834 def test_floor_division(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000835
836 d1 = Decimal('5')
837 d2 = Decimal('2')
838
839 #two Decimals
840 self.assertEqual(d1//d2, Decimal('2'))
841 self.assertEqual(d2//d1, Decimal('0'))
842
843 #with other type, left
844 c = d1 // 4
845 self.assertEqual(c, Decimal('1'))
846 self.assertEqual(type(c), type(d1))
847
848 #with other type, right
849 c = 7 // d1
850 self.assertEqual(c, Decimal('1'))
851 self.assertEqual(type(c), type(d1))
852
853 #inline with decimal
854 d1 //= d2
855 self.assertEqual(d1, Decimal('2'))
856
857 #inline with other type
858 d1 //= 2
859 self.assertEqual(d1, Decimal('1'))
860
861 def test_powering(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000862
863 d1 = Decimal('5')
864 d2 = Decimal('2')
865
866 #two Decimals
867 self.assertEqual(d1**d2, Decimal('25'))
868 self.assertEqual(d2**d1, Decimal('32'))
869
870 #with other type, left
871 c = d1 ** 4
872 self.assertEqual(c, Decimal('625'))
873 self.assertEqual(type(c), type(d1))
874
875 #with other type, right
876 c = 7 ** d1
877 self.assertEqual(c, Decimal('16807'))
878 self.assertEqual(type(c), type(d1))
879
880 #inline with decimal
881 d1 **= d2
882 self.assertEqual(d1, Decimal('25'))
883
884 #inline with other type
885 d1 **= 4
886 self.assertEqual(d1, Decimal('390625'))
887
888 def test_module(self):
889
890 d1 = Decimal('5')
891 d2 = Decimal('2')
892
893 #two Decimals
894 self.assertEqual(d1%d2, Decimal('1'))
895 self.assertEqual(d2%d1, Decimal('2'))
896
897 #with other type, left
898 c = d1 % 4
899 self.assertEqual(c, Decimal('1'))
900 self.assertEqual(type(c), type(d1))
901
902 #with other type, right
903 c = 7 % d1
904 self.assertEqual(c, Decimal('2'))
905 self.assertEqual(type(c), type(d1))
906
907 #inline with decimal
908 d1 %= d2
909 self.assertEqual(d1, Decimal('1'))
910
911 #inline with other type
912 d1 %= 4
913 self.assertEqual(d1, Decimal('1'))
914
915 def test_floor_div_module(self):
916
917 d1 = Decimal('5')
918 d2 = Decimal('2')
919
920 #two Decimals
921 (p, q) = divmod(d1, d2)
922 self.assertEqual(p, Decimal('2'))
923 self.assertEqual(q, Decimal('1'))
924 self.assertEqual(type(p), type(d1))
925 self.assertEqual(type(q), type(d1))
926
927 #with other type, left
928 (p, q) = divmod(d1, 4)
929 self.assertEqual(p, Decimal('1'))
930 self.assertEqual(q, Decimal('1'))
931 self.assertEqual(type(p), type(d1))
932 self.assertEqual(type(q), type(d1))
933
934 #with other type, right
935 (p, q) = divmod(7, d1)
936 self.assertEqual(p, Decimal('1'))
937 self.assertEqual(q, Decimal('2'))
938 self.assertEqual(type(p), type(d1))
939 self.assertEqual(type(q), type(d1))
940
941 def test_unary_operators(self):
942 self.assertEqual(+Decimal(45), Decimal(+45)) # +
943 self.assertEqual(-Decimal(45), Decimal(-45)) # -
944 self.assertEqual(abs(Decimal(45)), abs(Decimal(-45))) # abs
945
Mark Dickinson2fc92632008-02-06 22:10:50 +0000946 def test_nan_comparisons(self):
947 n = Decimal('NaN')
948 s = Decimal('sNaN')
949 i = Decimal('Inf')
950 f = Decimal('2')
951 for x, y in [(n, n), (n, i), (i, n), (n, f), (f, n),
952 (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)]:
953 self.assert_(x != y)
954 self.assert_(not (x == y))
955 self.assert_(not (x < y))
956 self.assert_(not (x <= y))
957 self.assert_(not (x > y))
958 self.assert_(not (x >= y))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000959
960# The following are two functions used to test threading in the next class
961
962def thfunc1(cls):
963 d1 = Decimal(1)
964 d3 = Decimal(3)
Facundo Batista64156672008-03-22 02:45:37 +0000965 test1 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000966 cls.synchro.wait()
Facundo Batista64156672008-03-22 02:45:37 +0000967 test2 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000968 cls.finish1.set()
Facundo Batista64156672008-03-22 02:45:37 +0000969
Facundo Batistaee340e52008-05-02 17:39:00 +0000970 cls.assertEqual(test1, Decimal('0.3333333333333333333333333333'))
971 cls.assertEqual(test2, Decimal('0.3333333333333333333333333333'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000972 return
973
974def thfunc2(cls):
975 d1 = Decimal(1)
976 d3 = Decimal(3)
Facundo Batista64156672008-03-22 02:45:37 +0000977 test1 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000978 thiscontext = getcontext()
979 thiscontext.prec = 18
Facundo Batista64156672008-03-22 02:45:37 +0000980 test2 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981 cls.synchro.set()
982 cls.finish2.set()
Facundo Batista64156672008-03-22 02:45:37 +0000983
Facundo Batistaee340e52008-05-02 17:39:00 +0000984 cls.assertEqual(test1, Decimal('0.3333333333333333333333333333'))
Facundo Batista64156672008-03-22 02:45:37 +0000985 cls.assertEqual(test2, Decimal('0.333333333333333333'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986 return
987
988
989class DecimalUseOfContextTest(unittest.TestCase):
990 '''Unit tests for Use of Context cases in Decimal.'''
991
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000992 try:
993 import threading
994 except ImportError:
995 threading = None
996
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997 # Take care executing this test from IDLE, there's an issue in threading
998 # that hangs IDLE and I couldn't find it
999
1000 def test_threading(self):
1001 #Test the "threading isolation" of a Context.
1002
1003 self.synchro = threading.Event()
1004 self.finish1 = threading.Event()
1005 self.finish2 = threading.Event()
1006
1007 th1 = threading.Thread(target=thfunc1, args=(self,))
1008 th2 = threading.Thread(target=thfunc2, args=(self,))
1009
1010 th1.start()
1011 th2.start()
1012
1013 self.finish1.wait()
Thomas Woutersb3e6e8c2007-09-19 17:27:29 +00001014 self.finish2.wait()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015 return
1016
Raymond Hettinger7e71fa52004-12-18 19:07:19 +00001017 if threading is None:
1018 del test_threading
1019
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001020
1021class DecimalUsabilityTest(unittest.TestCase):
1022 '''Unit tests for Usability cases of Decimal.'''
1023
1024 def test_comparison_operators(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025
1026 da = Decimal('23.42')
1027 db = Decimal('23.42')
1028 dc = Decimal('45')
1029
1030 #two Decimals
1031 self.failUnless(dc > da)
1032 self.failUnless(dc >= da)
1033 self.failUnless(da < dc)
1034 self.failUnless(da <= dc)
1035 self.failUnless(da == db)
1036 self.failUnless(da != dc)
1037 self.failUnless(da <= db)
1038 self.failUnless(da >= db)
1039 self.assertEqual(cmp(dc,da), 1)
1040 self.assertEqual(cmp(da,dc), -1)
1041 self.assertEqual(cmp(da,db), 0)
1042
1043 #a Decimal and an int
1044 self.failUnless(dc > 23)
1045 self.failUnless(23 < dc)
1046 self.failUnless(dc == 45)
1047 self.assertEqual(cmp(dc,23), 1)
1048 self.assertEqual(cmp(23,dc), -1)
1049 self.assertEqual(cmp(dc,45), 0)
1050
1051 #a Decimal and uncomparable
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001052 self.assertNotEqual(da, 'ugly')
1053 self.assertNotEqual(da, 32.7)
1054 self.assertNotEqual(da, object())
1055 self.assertNotEqual(da, object)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001056
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001057 # sortable
1058 a = map(Decimal, xrange(100))
1059 b = a[:]
1060 random.shuffle(a)
1061 a.sort()
1062 self.assertEqual(a, b)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063
Facundo Batista353750c2007-09-13 18:13:15 +00001064 # with None
1065 self.assertFalse(Decimal(1) < None)
1066 self.assertTrue(Decimal(1) > None)
1067
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001068 def test_copy_and_deepcopy_methods(self):
1069 d = Decimal('43.24')
1070 c = copy.copy(d)
1071 self.assertEqual(id(c), id(d))
1072 dc = copy.deepcopy(d)
1073 self.assertEqual(id(dc), id(d))
1074
1075 def test_hash_method(self):
1076 #just that it's hashable
1077 hash(Decimal(23))
Facundo Batista8c202442007-09-19 17:53:25 +00001078
1079 test_values = [Decimal(sign*(2**m + n))
1080 for m in [0, 14, 15, 16, 17, 30, 31,
1081 32, 33, 62, 63, 64, 65, 66]
1082 for n in range(-10, 10)
1083 for sign in [-1, 1]]
1084 test_values.extend([
1085 Decimal("-0"), # zeros
1086 Decimal("0.00"),
1087 Decimal("-0.000"),
1088 Decimal("0E10"),
1089 Decimal("-0E12"),
1090 Decimal("10.0"), # negative exponent
1091 Decimal("-23.00000"),
1092 Decimal("1230E100"), # positive exponent
1093 Decimal("-4.5678E50"),
1094 # a value for which hash(n) != hash(n % (2**64-1))
1095 # in Python pre-2.6
1096 Decimal(2**64 + 2**32 - 1),
1097 # selection of values which fail with the old (before
1098 # version 2.6) long.__hash__
1099 Decimal("1.634E100"),
1100 Decimal("90.697E100"),
1101 Decimal("188.83E100"),
1102 Decimal("1652.9E100"),
1103 Decimal("56531E100"),
1104 ])
1105
1106 # check that hash(d) == hash(int(d)) for integral values
1107 for value in test_values:
1108 self.assertEqual(hash(value), hash(int(value)))
1109
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001110 #the same hash that to an int
1111 self.assertEqual(hash(Decimal(23)), hash(23))
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +00001112 self.assertRaises(TypeError, hash, Decimal('NaN'))
1113 self.assert_(hash(Decimal('Inf')))
1114 self.assert_(hash(Decimal('-Inf')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115
Facundo Batista52b25792008-01-08 12:25:20 +00001116 # check that the value of the hash doesn't depend on the
1117 # current context (issue #1757)
1118 c = getcontext()
1119 old_precision = c.prec
1120 x = Decimal("123456789.1")
1121
1122 c.prec = 6
1123 h1 = hash(x)
1124 c.prec = 10
1125 h2 = hash(x)
1126 c.prec = 16
1127 h3 = hash(x)
1128
1129 self.assertEqual(h1, h2)
1130 self.assertEqual(h1, h3)
1131 c.prec = old_precision
1132
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001133 def test_min_and_max_methods(self):
1134
1135 d1 = Decimal('15.32')
1136 d2 = Decimal('28.5')
1137 l1 = 15
1138 l2 = 28
1139
1140 #between Decimals
1141 self.failUnless(min(d1,d2) is d1)
1142 self.failUnless(min(d2,d1) is d1)
1143 self.failUnless(max(d1,d2) is d2)
1144 self.failUnless(max(d2,d1) is d2)
1145
1146 #between Decimal and long
1147 self.failUnless(min(d1,l2) is d1)
1148 self.failUnless(min(l2,d1) is d1)
1149 self.failUnless(max(l1,d2) is d2)
1150 self.failUnless(max(d2,l1) is d2)
1151
1152 def test_as_nonzero(self):
1153 #as false
1154 self.failIf(Decimal(0))
1155 #as true
1156 self.failUnless(Decimal('0.372'))
1157
1158 def test_tostring_methods(self):
1159 #Test str and repr methods.
1160
1161 d = Decimal('15.32')
1162 self.assertEqual(str(d), '15.32') # str
Raymond Hettingerabe32372008-02-14 02:41:22 +00001163 self.assertEqual(repr(d), "Decimal('15.32')") # repr
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164
Mark Dickinson8e85ffa2008-03-25 18:47:59 +00001165 # result type of string methods should be str, not unicode
1166 unicode_inputs = [u'123.4', u'0.5E2', u'Infinity', u'sNaN',
1167 u'-0.0E100', u'-NaN001', u'-Inf']
1168
1169 for u in unicode_inputs:
1170 d = Decimal(u)
1171 self.assertEqual(type(str(d)), str)
1172 self.assertEqual(type(repr(d)), str)
1173 self.assertEqual(type(d.to_eng_string()), str)
1174
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175 def test_tonum_methods(self):
1176 #Test float, int and long methods.
1177
1178 d1 = Decimal('66')
1179 d2 = Decimal('15.32')
1180
1181 #int
1182 self.assertEqual(int(d1), 66)
1183 self.assertEqual(int(d2), 15)
1184
1185 #long
1186 self.assertEqual(long(d1), 66)
1187 self.assertEqual(long(d2), 15)
1188
1189 #float
1190 self.assertEqual(float(d1), 66)
1191 self.assertEqual(float(d2), 15.32)
1192
1193 def test_eval_round_trip(self):
1194
1195 #with zero
1196 d = Decimal( (0, (0,), 0) )
1197 self.assertEqual(d, eval(repr(d)))
1198
1199 #int
1200 d = Decimal( (1, (4, 5), 0) )
1201 self.assertEqual(d, eval(repr(d)))
1202
1203 #float
1204 d = Decimal( (0, (4, 5, 3, 4), -2) )
1205 self.assertEqual(d, eval(repr(d)))
1206
1207 #weird
1208 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
1209 self.assertEqual(d, eval(repr(d)))
1210
1211 def test_as_tuple(self):
1212
1213 #with zero
1214 d = Decimal(0)
1215 self.assertEqual(d.as_tuple(), (0, (0,), 0) )
1216
1217 #int
1218 d = Decimal(-45)
1219 self.assertEqual(d.as_tuple(), (1, (4, 5), 0) )
1220
1221 #complicated string
1222 d = Decimal("-4.34913534E-17")
1223 self.assertEqual(d.as_tuple(), (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
1224
1225 #inf
1226 d = Decimal("Infinity")
1227 self.assertEqual(d.as_tuple(), (0, (0,), 'F') )
1228
Facundo Batista9b5e2312007-10-19 19:25:57 +00001229 #leading zeros in coefficient should be stripped
1230 d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), -2) )
1231 self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), -2) )
1232 d = Decimal( (1, (0, 0, 0), 37) )
1233 self.assertEqual(d.as_tuple(), (1, (0,), 37))
1234 d = Decimal( (1, (), 37) )
1235 self.assertEqual(d.as_tuple(), (1, (0,), 37))
1236
1237 #leading zeros in NaN diagnostic info should be stripped
1238 d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), 'n') )
1239 self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), 'n') )
1240 d = Decimal( (1, (0, 0, 0), 'N') )
1241 self.assertEqual(d.as_tuple(), (1, (), 'N') )
1242 d = Decimal( (1, (), 'n') )
1243 self.assertEqual(d.as_tuple(), (1, (), 'n') )
1244
1245 #coefficient in infinity should be ignored
1246 d = Decimal( (0, (4, 5, 3, 4), 'F') )
1247 self.assertEqual(d.as_tuple(), (0, (0,), 'F'))
1248 d = Decimal( (1, (0, 2, 7, 1), 'F') )
1249 self.assertEqual(d.as_tuple(), (1, (0,), 'F'))
1250
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001251 def test_immutability_operations(self):
1252 # Do operations and check that it didn't change change internal objects.
1253
1254 d1 = Decimal('-25e55')
1255 b1 = Decimal('-25e55')
Facundo Batista353750c2007-09-13 18:13:15 +00001256 d2 = Decimal('33e+33')
1257 b2 = Decimal('33e+33')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001258
1259 def checkSameDec(operation, useOther=False):
1260 if useOther:
1261 eval("d1." + operation + "(d2)")
1262 self.assertEqual(d1._sign, b1._sign)
1263 self.assertEqual(d1._int, b1._int)
1264 self.assertEqual(d1._exp, b1._exp)
1265 self.assertEqual(d2._sign, b2._sign)
1266 self.assertEqual(d2._int, b2._int)
1267 self.assertEqual(d2._exp, b2._exp)
1268 else:
1269 eval("d1." + operation + "()")
1270 self.assertEqual(d1._sign, b1._sign)
1271 self.assertEqual(d1._int, b1._int)
1272 self.assertEqual(d1._exp, b1._exp)
1273 return
1274
1275 Decimal(d1)
1276 self.assertEqual(d1._sign, b1._sign)
1277 self.assertEqual(d1._int, b1._int)
1278 self.assertEqual(d1._exp, b1._exp)
1279
1280 checkSameDec("__abs__")
1281 checkSameDec("__add__", True)
1282 checkSameDec("__div__", True)
1283 checkSameDec("__divmod__", True)
Mark Dickinson2fc92632008-02-06 22:10:50 +00001284 checkSameDec("__eq__", True)
1285 checkSameDec("__ne__", True)
1286 checkSameDec("__le__", True)
1287 checkSameDec("__lt__", True)
1288 checkSameDec("__ge__", True)
1289 checkSameDec("__gt__", True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001290 checkSameDec("__float__")
1291 checkSameDec("__floordiv__", True)
1292 checkSameDec("__hash__")
1293 checkSameDec("__int__")
Raymond Hettinger5a053642008-01-24 19:05:29 +00001294 checkSameDec("__trunc__")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001295 checkSameDec("__long__")
1296 checkSameDec("__mod__", True)
1297 checkSameDec("__mul__", True)
1298 checkSameDec("__neg__")
1299 checkSameDec("__nonzero__")
1300 checkSameDec("__pos__")
1301 checkSameDec("__pow__", True)
1302 checkSameDec("__radd__", True)
1303 checkSameDec("__rdiv__", True)
1304 checkSameDec("__rdivmod__", True)
1305 checkSameDec("__repr__")
1306 checkSameDec("__rfloordiv__", True)
1307 checkSameDec("__rmod__", True)
1308 checkSameDec("__rmul__", True)
1309 checkSameDec("__rpow__", True)
1310 checkSameDec("__rsub__", True)
1311 checkSameDec("__str__")
1312 checkSameDec("__sub__", True)
1313 checkSameDec("__truediv__", True)
1314 checkSameDec("adjusted")
1315 checkSameDec("as_tuple")
1316 checkSameDec("compare", True)
1317 checkSameDec("max", True)
1318 checkSameDec("min", True)
1319 checkSameDec("normalize")
1320 checkSameDec("quantize", True)
1321 checkSameDec("remainder_near", True)
1322 checkSameDec("same_quantum", True)
1323 checkSameDec("sqrt")
1324 checkSameDec("to_eng_string")
1325 checkSameDec("to_integral")
1326
Facundo Batista6c398da2007-09-17 17:30:13 +00001327 def test_subclassing(self):
1328 # Different behaviours when subclassing Decimal
1329
1330 class MyDecimal(Decimal):
1331 pass
1332
1333 d1 = MyDecimal(1)
1334 d2 = MyDecimal(2)
1335 d = d1 + d2
1336 self.assertTrue(type(d) is Decimal)
1337
1338 d = d1.max(d2)
1339 self.assertTrue(type(d) is Decimal)
1340
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00001341 def test_implicit_context(self):
1342 # Check results when context given implicitly. (Issue 2478)
1343 c = getcontext()
1344 self.assertEqual(str(Decimal(0).sqrt()),
1345 str(c.sqrt(Decimal(0))))
1346
Facundo Batista6c398da2007-09-17 17:30:13 +00001347
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001348class DecimalPythonAPItests(unittest.TestCase):
1349
Raymond Hettinger45fd4762009-02-03 03:42:07 +00001350 def test_abc(self):
1351 self.assert_(issubclass(Decimal, numbers.Number))
1352 self.assert_(not issubclass(Decimal, numbers.Real))
1353 self.assert_(isinstance(Decimal(0), numbers.Number))
1354 self.assert_(not isinstance(Decimal(0), numbers.Real))
1355
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356 def test_pickle(self):
1357 d = Decimal('-3.141590000')
1358 p = pickle.dumps(d)
1359 e = pickle.loads(p)
1360 self.assertEqual(d, e)
1361
Raymond Hettinger5548be22004-07-05 18:49:38 +00001362 def test_int(self):
Raymond Hettinger605ed022004-11-24 07:28:48 +00001363 for x in range(-250, 250):
1364 s = '%0.2f' % (x / 100.0)
Raymond Hettinger5548be22004-07-05 18:49:38 +00001365 # should work the same as for floats
1366 self.assertEqual(int(Decimal(s)), int(float(s)))
Raymond Hettinger605ed022004-11-24 07:28:48 +00001367 # should work the same as to_integral in the ROUND_DOWN mode
Raymond Hettinger5548be22004-07-05 18:49:38 +00001368 d = Decimal(s)
Raymond Hettinger605ed022004-11-24 07:28:48 +00001369 r = d.to_integral(ROUND_DOWN)
Raymond Hettinger5548be22004-07-05 18:49:38 +00001370 self.assertEqual(Decimal(int(d)), r)
1371
Raymond Hettinger5a053642008-01-24 19:05:29 +00001372 def test_trunc(self):
1373 for x in range(-250, 250):
1374 s = '%0.2f' % (x / 100.0)
1375 # should work the same as for floats
1376 self.assertEqual(int(Decimal(s)), int(float(s)))
1377 # should work the same as to_integral in the ROUND_DOWN mode
1378 d = Decimal(s)
1379 r = d.to_integral(ROUND_DOWN)
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001380 self.assertEqual(Decimal(math.trunc(d)), r)
Raymond Hettinger5a053642008-01-24 19:05:29 +00001381
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00001382class ContextAPItests(unittest.TestCase):
1383
1384 def test_pickle(self):
1385 c = Context()
1386 e = pickle.loads(pickle.dumps(c))
1387 for k in vars(c):
1388 v1 = vars(c)[k]
1389 v2 = vars(e)[k]
1390 self.assertEqual(v1, v2)
1391
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001392 def test_equality_with_other_types(self):
1393 self.assert_(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}])
1394 self.assert_(Decimal(10) not in ['a', 1.0, (1,2), {}])
1395
Raymond Hettinger955d2b22004-08-08 20:17:45 +00001396 def test_copy(self):
1397 # All copies should be deep
1398 c = Context()
1399 d = c.copy()
1400 self.assertNotEqual(id(c), id(d))
1401 self.assertNotEqual(id(c.flags), id(d.flags))
1402 self.assertNotEqual(id(c.traps), id(d.traps))
1403
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001404class WithStatementTest(unittest.TestCase):
1405 # Can't do these as docstrings until Python 2.6
1406 # as doctest can't handle __future__ statements
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001407
1408 def test_localcontext(self):
Nick Coghlanced12182006-09-02 03:54:17 +00001409 # Use a copy of the current context in the block
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001410 orig_ctx = getcontext()
1411 with localcontext() as enter_ctx:
1412 set_ctx = getcontext()
1413 final_ctx = getcontext()
1414 self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
1415 self.assert_(orig_ctx is not set_ctx, 'did not copy the context')
1416 self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
1417
1418 def test_localcontextarg(self):
Nick Coghlanced12182006-09-02 03:54:17 +00001419 # Use a copy of the supplied context in the block
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001420 orig_ctx = getcontext()
1421 new_ctx = Context(prec=42)
1422 with localcontext(new_ctx) as enter_ctx:
1423 set_ctx = getcontext()
1424 final_ctx = getcontext()
1425 self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
1426 self.assert_(set_ctx.prec == new_ctx.prec, 'did not set correct context')
1427 self.assert_(new_ctx is not set_ctx, 'did not copy the context')
1428 self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
1429
Facundo Batista353750c2007-09-13 18:13:15 +00001430class ContextFlags(unittest.TestCase):
1431 def test_flags_irrelevant(self):
1432 # check that the result (numeric result + flags raised) of an
1433 # arithmetic operation doesn't depend on the current flags
1434
1435 context = Context(prec=9, Emin = -999999999, Emax = 999999999,
1436 rounding=ROUND_HALF_EVEN, traps=[], flags=[])
1437
1438 # operations that raise various flags, in the form (function, arglist)
1439 operations = [
1440 (context._apply, [Decimal("100E-1000000009")]),
1441 (context.sqrt, [Decimal(2)]),
1442 (context.add, [Decimal("1.23456789"), Decimal("9.87654321")]),
1443 (context.multiply, [Decimal("1.23456789"), Decimal("9.87654321")]),
1444 (context.subtract, [Decimal("1.23456789"), Decimal("9.87654321")]),
1445 ]
1446
1447 # try various flags individually, then a whole lot at once
1448 flagsets = [[Inexact], [Rounded], [Underflow], [Clamped], [Subnormal],
1449 [Inexact, Rounded, Underflow, Clamped, Subnormal]]
1450
1451 for fn, args in operations:
1452 # find answer and flags raised using a clean context
1453 context.clear_flags()
1454 ans = fn(*args)
1455 flags = [k for k, v in context.flags.items() if v]
1456
1457 for extra_flags in flagsets:
1458 # set flags, before calling operation
1459 context.clear_flags()
1460 for flag in extra_flags:
1461 context._raise_error(flag)
1462 new_ans = fn(*args)
1463
1464 # flags that we expect to be set after the operation
1465 expected_flags = list(flags)
1466 for flag in extra_flags:
1467 if flag not in expected_flags:
1468 expected_flags.append(flag)
1469 expected_flags.sort()
1470
1471 # flags we actually got
1472 new_flags = [k for k,v in context.flags.items() if v]
1473 new_flags.sort()
1474
1475 self.assertEqual(ans, new_ans,
1476 "operation produces different answers depending on flags set: " +
1477 "expected %s, got %s." % (ans, new_ans))
1478 self.assertEqual(new_flags, expected_flags,
1479 "operation raises different flags depending on flags set: " +
1480 "expected %s, got %s" % (expected_flags, new_flags))
1481
1482def test_main(arith=False, verbose=None, todo_tests=None, debug=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001483 """ Execute the tests.
1484
Raymond Hettingered20ad82004-09-04 20:09:13 +00001485 Runs all arithmetic tests if arith is True or if the "decimal" resource
1486 is enabled in regrtest.py
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001487 """
Raymond Hettingered20ad82004-09-04 20:09:13 +00001488
Neal Norwitzce4a9c92006-04-09 08:36:46 +00001489 init()
Facundo Batista353750c2007-09-13 18:13:15 +00001490 global TEST_ALL, DEBUG
Raymond Hettingered20ad82004-09-04 20:09:13 +00001491 TEST_ALL = arith or is_resource_enabled('decimal')
Facundo Batista353750c2007-09-13 18:13:15 +00001492 DEBUG = debug
Raymond Hettingered20ad82004-09-04 20:09:13 +00001493
Facundo Batista353750c2007-09-13 18:13:15 +00001494 if todo_tests is None:
1495 test_classes = [
1496 DecimalExplicitConstructionTest,
1497 DecimalImplicitConstructionTest,
1498 DecimalArithmeticOperatorsTest,
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00001499 DecimalFormatTest,
Facundo Batista353750c2007-09-13 18:13:15 +00001500 DecimalUseOfContextTest,
1501 DecimalUsabilityTest,
1502 DecimalPythonAPItests,
1503 ContextAPItests,
1504 DecimalTest,
1505 WithStatementTest,
1506 ContextFlags
1507 ]
1508 else:
1509 test_classes = [DecimalTest]
1510
1511 # Dynamically build custom test definition for each file in the test
1512 # directory and add the definitions to the DecimalTest class. This
1513 # procedure insures that new files do not get skipped.
1514 for filename in os.listdir(directory):
1515 if '.decTest' not in filename or filename.startswith("."):
1516 continue
1517 head, tail = filename.split('.')
1518 if todo_tests is not None and head not in todo_tests:
1519 continue
1520 tester = lambda self, f=filename: self.eval_file(directory + f)
1521 setattr(DecimalTest, 'test_' + head, tester)
1522 del filename, head, tail, tester
1523
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001524
Tim Peters46cc7022006-03-31 04:11:16 +00001525 try:
1526 run_unittest(*test_classes)
Facundo Batista353750c2007-09-13 18:13:15 +00001527 if todo_tests is None:
1528 import decimal as DecimalModule
1529 run_doctest(DecimalModule, verbose)
Tim Peters46cc7022006-03-31 04:11:16 +00001530 finally:
1531 setcontext(ORIGINAL_CONTEXT)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532
1533if __name__ == '__main__':
Facundo Batista353750c2007-09-13 18:13:15 +00001534 import optparse
1535 p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]")
1536 p.add_option('--debug', '-d', action='store_true', help='shows the test number and context before each test')
1537 p.add_option('--skip', '-s', action='store_true', help='skip over 90% of the arithmetic tests')
1538 (opt, args) = p.parse_args()
1539
1540 if opt.skip:
1541 test_main(arith=False, verbose=True)
1542 elif args:
1543 test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001545 test_main(arith=True, verbose=True)