blob: c02b813dc418dbb793d2f73e1225aae4d0829472 [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
Christian Heimes400adb02008-02-01 08:12:03 +000028import math
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000029import os, sys
30import pickle, copy
Christian Heimes400adb02008-02-01 08:12:03 +000031import unittest
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000032from decimal import *
Raymond Hettinger82417ca2009-02-03 03:54:28 +000033import numbers
Benjamin Petersonee8712c2008-05-20 21:35:26 +000034from test.support import (TestSkipped, run_unittest, run_doctest,
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000035 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
Guido van Rossumc1f779c2007-07-03 08:25:58 +000043Signals = tuple(getcontext().flags.keys())
Raymond Hettingerfed52962004-07-14 15:41:57 +000044
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000045# Tests are built around these assumed context defaults.
46# test_main() restores the original context.
47def init():
48 global ORIGINAL_CONTEXT
49 ORIGINAL_CONTEXT = getcontext().copy()
Christian Heimes81ee3ef2008-05-04 22:42:01 +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,
Thomas Wouters1b7f8912007-09-19 03:06:30 +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
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000101nameAdapter = {'and':'logical_and',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000102 'apply':'_apply',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000103 'class':'number_class',
104 'comparesig':'compare_signal',
105 'comparetotal':'compare_total',
106 'comparetotmag':'compare_total_mag',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000107 'copy':'copy_decimal',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000108 'copyabs':'copy_abs',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000109 'copynegate':'copy_negate',
110 'copysign':'copy_sign',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000111 'divideint':'divide_int',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000112 'invert':'logical_invert',
Guido van Rossum8ce8a782007-11-01 19:42:39 +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',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000123 'maxmag':'max_mag',
124 'minmag':'min_mag',
125 'nextminus':'next_minus',
126 'nextplus':'next_plus',
127 'nexttoward':'next_toward',
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000128 'or':'logical_or',
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000129 'reduce':'normalize',
Guido van Rossum8ce8a782007-11-01 19:42:39 +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
Guido van Rossum8ce8a782007-11-01 19:42:39 +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
Thomas Wouters1b7f8912007-09-19 03:06:30 +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 (
Thomas Wouters1b7f8912007-09-19 03:06:30 +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
Neal Norwitz70967602006-03-17 08:29:44 +0000199 for line in open(file):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 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)
Guido van Rossumb940e112007-01-10 16:19:56 +0000204 except DecimalException as exception:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000205 #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):
Guido van Rossumc1f779c2007-07-03 08:25:58 +0000229 funct, value = (x.strip().lower() for x in s.split(':'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230 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]
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000252 if DEBUG:
253 print("Test ", id, end=" ")
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
Guido van Rossumb940e112007-01-10 16:19:56 +0000297 except Signals as 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:
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000305 v = Decimal(v, self.context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306 vals.append(v)
307
308 ans = FixQuotes(ans)
309
Thomas Wouters1b7f8912007-09-19 03:06:30 +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
Guido van Rossumb940e112007-01-10 16:19:56 +0000333 except Signals as 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
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000339 if DEBUG:
340 print("--", self.context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000341 try:
342 result = str(funct(*vals))
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000343 if fname in LOGICAL_FUNCTIONS:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 result = str(int(eval(result))) # 'True', 'False' -> '1', '0'
Guido van Rossumb940e112007-01-10 16:19:56 +0000345 except Signals as 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.
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000348 print("ERROR:", s)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 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
Guido van Rossum47b9ff62006-08-24 00:41:19 +0000354 myexceptions.sort(key=repr)
355 theirexceptions.sort(key=repr)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000356
357 self.assertEqual(result, ans,
358 'Incorrect answer for ' + s + ' -- got ' + result)
359 self.assertEqual(myexceptions, theirexceptions,
Thomas Wouters1b7f8912007-09-19 03:06:30 +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
Christian Heimesa62da1d2008-01-12 19:39:10 +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
Benjamin Peterson41181742008-07-02 20:22:54 +0000429 #but alternate unicode digits should not
430 self.assertEqual(str(Decimal('\uff11')), 'NaN')
431
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000432 def test_explicit_from_tuples(self):
433
434 #zero
435 d = Decimal( (0, (0,), 0) )
436 self.assertEqual(str(d), '0')
437
438 #int
439 d = Decimal( (1, (4, 5), 0) )
440 self.assertEqual(str(d), '-45')
441
442 #float
443 d = Decimal( (0, (4, 5, 3, 4), -2) )
444 self.assertEqual(str(d), '45.34')
445
446 #weird
447 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
448 self.assertEqual(str(d), '-4.34913534E-17')
449
450 #wrong number of items
451 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1)) )
452
453 #bad sign
454 self.assertRaises(ValueError, Decimal, (8, (4, 3, 4, 9, 1), 2) )
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000455 self.assertRaises(ValueError, Decimal, (0., (4, 3, 4, 9, 1), 2) )
456 self.assertRaises(ValueError, Decimal, (Decimal(1), (4, 3, 4, 9, 1), 2))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000457
458 #bad exp
459 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 'wrong!') )
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000460 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) )
461 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000462
463 #bad coefficients
464 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) )
465 self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) )
Guido van Rossum8ce8a782007-11-01 19:42:39 +0000466 self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) )
Guido van Rossum0d3fb8a2007-11-26 23:23:18 +0000467 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000468
469 def test_explicit_from_Decimal(self):
470
471 #positive
472 d = Decimal(45)
473 e = Decimal(d)
474 self.assertEqual(str(e), '45')
475 self.assertNotEqual(id(d), id(e))
476
477 #very large positive
478 d = Decimal(500000123)
479 e = Decimal(d)
480 self.assertEqual(str(e), '500000123')
481 self.assertNotEqual(id(d), id(e))
482
483 #negative
484 d = Decimal(-45)
485 e = Decimal(d)
486 self.assertEqual(str(e), '-45')
487 self.assertNotEqual(id(d), id(e))
488
489 #zero
490 d = Decimal(0)
491 e = Decimal(d)
492 self.assertEqual(str(e), '0')
493 self.assertNotEqual(id(d), id(e))
494
495 def test_explicit_context_create_decimal(self):
496
497 nc = copy.copy(getcontext())
498 nc.prec = 3
499
500 # empty
Raymond Hettingerfed52962004-07-14 15:41:57 +0000501 d = Decimal()
502 self.assertEqual(str(d), '0')
503 d = nc.create_decimal()
504 self.assertEqual(str(d), '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505
506 # from None
507 self.assertRaises(TypeError, nc.create_decimal, None)
508
509 # from int
510 d = nc.create_decimal(456)
511 self.failUnless(isinstance(d, Decimal))
512 self.assertEqual(nc.create_decimal(45678),
513 nc.create_decimal('457E+2'))
514
515 # from string
516 d = Decimal('456789')
517 self.assertEqual(str(d), '456789')
518 d = nc.create_decimal('456789')
519 self.assertEqual(str(d), '4.57E+5')
Christian Heimesa62da1d2008-01-12 19:39:10 +0000520 # leading and trailing whitespace should result in a NaN;
521 # spaces are already checked in Cowlishaw's test-suite, so
522 # here we just check that a trailing newline results in a NaN
523 self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524
525 # from tuples
526 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
527 self.assertEqual(str(d), '-4.34913534E-17')
528 d = nc.create_decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
529 self.assertEqual(str(d), '-4.35E-17')
530
531 # from Decimal
532 prevdec = Decimal(500000123)
533 d = Decimal(prevdec)
534 self.assertEqual(str(d), '500000123')
535 d = nc.create_decimal(prevdec)
536 self.assertEqual(str(d), '5.00E+8')
537
538
539class DecimalImplicitConstructionTest(unittest.TestCase):
540 '''Unit tests for Implicit Construction cases of Decimal.'''
541
542 def test_implicit_from_None(self):
543 self.assertRaises(TypeError, eval, 'Decimal(5) + None', globals())
544
545 def test_implicit_from_int(self):
546 #normal
547 self.assertEqual(str(Decimal(5) + 45), '50')
548 #exceeding precision
549 self.assertEqual(Decimal(5) + 123456789000, Decimal(123456789000))
550
551 def test_implicit_from_string(self):
552 self.assertRaises(TypeError, eval, 'Decimal(5) + "3"', globals())
553
554 def test_implicit_from_float(self):
555 self.assertRaises(TypeError, eval, 'Decimal(5) + 2.2', globals())
556
557 def test_implicit_from_Decimal(self):
558 self.assertEqual(Decimal(5) + Decimal(45), Decimal(50))
559
Raymond Hettinger267b8682005-03-27 10:47:39 +0000560 def test_rop(self):
561 # Allow other classes to be trained to interact with Decimals
562 class E:
563 def __divmod__(self, other):
564 return 'divmod ' + str(other)
565 def __rdivmod__(self, other):
566 return str(other) + ' rdivmod'
567 def __lt__(self, other):
568 return 'lt ' + str(other)
569 def __gt__(self, other):
570 return 'gt ' + str(other)
571 def __le__(self, other):
572 return 'le ' + str(other)
573 def __ge__(self, other):
574 return 'ge ' + str(other)
575 def __eq__(self, other):
576 return 'eq ' + str(other)
577 def __ne__(self, other):
578 return 'ne ' + str(other)
579
580 self.assertEqual(divmod(E(), Decimal(10)), 'divmod 10')
581 self.assertEqual(divmod(Decimal(10), E()), '10 rdivmod')
582 self.assertEqual(eval('Decimal(10) < E()'), 'gt 10')
583 self.assertEqual(eval('Decimal(10) > E()'), 'lt 10')
584 self.assertEqual(eval('Decimal(10) <= E()'), 'ge 10')
585 self.assertEqual(eval('Decimal(10) >= E()'), 'le 10')
586 self.assertEqual(eval('Decimal(10) == E()'), 'eq 10')
587 self.assertEqual(eval('Decimal(10) != E()'), 'ne 10')
588
589 # insert operator methods and then exercise them
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000590 oplist = [
591 ('+', '__add__', '__radd__'),
592 ('-', '__sub__', '__rsub__'),
593 ('*', '__mul__', '__rmul__'),
Thomas Woutersdcc6d322006-04-21 11:30:52 +0000594 ('/', '__truediv__', '__rtruediv__'),
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000595 ('%', '__mod__', '__rmod__'),
596 ('//', '__floordiv__', '__rfloordiv__'),
597 ('**', '__pow__', '__rpow__')
598 ]
Raymond Hettinger267b8682005-03-27 10:47:39 +0000599
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000600 for sym, lop, rop in oplist:
Raymond Hettinger267b8682005-03-27 10:47:39 +0000601 setattr(E, lop, lambda self, other: 'str' + lop + str(other))
602 setattr(E, rop, lambda self, other: str(other) + rop + 'str')
603 self.assertEqual(eval('E()' + sym + 'Decimal(10)'),
604 'str' + lop + '10')
605 self.assertEqual(eval('Decimal(10)' + sym + 'E()'),
606 '10' + rop + 'str')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000607
Mark Dickinson79f52032009-03-17 23:12:51 +0000608
Christian Heimesf16baeb2008-02-29 14:57:44 +0000609class DecimalFormatTest(unittest.TestCase):
610 '''Unit tests for the format function.'''
611 def test_formatting(self):
612 # triples giving a format, a Decimal, and the expected result
613 test_values = [
614 ('e', '0E-15', '0e-15'),
615 ('e', '2.3E-15', '2.3e-15'),
616 ('e', '2.30E+2', '2.30e+2'), # preserve significant zeros
617 ('e', '2.30000E-15', '2.30000e-15'),
618 ('e', '1.23456789123456789e40', '1.23456789123456789e+40'),
619 ('e', '1.5', '1.5e+0'),
620 ('e', '0.15', '1.5e-1'),
621 ('e', '0.015', '1.5e-2'),
622 ('e', '0.0000000000015', '1.5e-12'),
623 ('e', '15.0', '1.50e+1'),
624 ('e', '-15', '-1.5e+1'),
625 ('e', '0', '0e+0'),
626 ('e', '0E1', '0e+1'),
627 ('e', '0.0', '0e-1'),
628 ('e', '0.00', '0e-2'),
629 ('.6e', '0E-15', '0.000000e-9'),
630 ('.6e', '0', '0.000000e+6'),
631 ('.6e', '9.999999', '9.999999e+0'),
632 ('.6e', '9.9999999', '1.000000e+1'),
633 ('.6e', '-1.23e5', '-1.230000e+5'),
634 ('.6e', '1.23456789e-3', '1.234568e-3'),
635 ('f', '0', '0'),
636 ('f', '0.0', '0.0'),
637 ('f', '0E-2', '0.00'),
638 ('f', '0.00E-8', '0.0000000000'),
639 ('f', '0E1', '0'), # loses exponent information
640 ('f', '3.2E1', '32'),
641 ('f', '3.2E2', '320'),
642 ('f', '3.20E2', '320'),
643 ('f', '3.200E2', '320.0'),
644 ('f', '3.2E-6', '0.0000032'),
645 ('.6f', '0E-15', '0.000000'), # all zeros treated equally
646 ('.6f', '0E1', '0.000000'),
647 ('.6f', '0', '0.000000'),
648 ('.0f', '0', '0'), # no decimal point
649 ('.0f', '0e-2', '0'),
650 ('.0f', '3.14159265', '3'),
651 ('.1f', '3.14159265', '3.1'),
652 ('.4f', '3.14159265', '3.1416'),
653 ('.6f', '3.14159265', '3.141593'),
654 ('.7f', '3.14159265', '3.1415926'), # round-half-even!
655 ('.8f', '3.14159265', '3.14159265'),
656 ('.9f', '3.14159265', '3.141592650'),
657
658 ('g', '0', '0'),
659 ('g', '0.0', '0.0'),
660 ('g', '0E1', '0e+1'),
661 ('G', '0E1', '0E+1'),
662 ('g', '0E-5', '0.00000'),
663 ('g', '0E-6', '0.000000'),
664 ('g', '0E-7', '0e-7'),
665 ('g', '-0E2', '-0e+2'),
666 ('.0g', '3.14159265', '3'), # 0 sig fig -> 1 sig fig
667 ('.1g', '3.14159265', '3'),
668 ('.2g', '3.14159265', '3.1'),
669 ('.5g', '3.14159265', '3.1416'),
670 ('.7g', '3.14159265', '3.141593'),
671 ('.8g', '3.14159265', '3.1415926'), # round-half-even!
672 ('.9g', '3.14159265', '3.14159265'),
673 ('.10g', '3.14159265', '3.14159265'), # don't pad
674
675 ('%', '0E1', '0%'),
676 ('%', '0E0', '0%'),
677 ('%', '0E-1', '0%'),
678 ('%', '0E-2', '0%'),
679 ('%', '0E-3', '0.0%'),
680 ('%', '0E-4', '0.00%'),
681
682 ('.3%', '0', '0.000%'), # all zeros treated equally
683 ('.3%', '0E10', '0.000%'),
684 ('.3%', '0E-10', '0.000%'),
685 ('.3%', '2.34', '234.000%'),
686 ('.3%', '1.234567', '123.457%'),
687 ('.0%', '1.23', '123%'),
688
689 ('e', 'NaN', 'NaN'),
690 ('f', '-NaN123', '-NaN123'),
691 ('+g', 'NaN456', '+NaN456'),
692 ('.3e', 'Inf', 'Infinity'),
693 ('.16f', '-Inf', '-Infinity'),
694 ('.0g', '-sNaN', '-sNaN'),
695
696 ('', '1.00', '1.00'),
Mark Dickinsonad416342009-03-17 18:10:15 +0000697
Mark Dickinson79f52032009-03-17 23:12:51 +0000698 # test alignment and padding
Mark Dickinsonad416342009-03-17 18:10:15 +0000699 ('<6', '123', '123 '),
700 ('>6', '123', ' 123'),
701 ('^6', '123', ' 123 '),
702 ('=+6', '123', '+ 123'),
Mark Dickinson79f52032009-03-17 23:12:51 +0000703 ('#<10', 'NaN', 'NaN#######'),
704 ('#<10', '-4.3', '-4.3######'),
705 ('#<+10', '0.0130', '+0.0130###'),
706 ('#< 10', '0.0130', ' 0.0130###'),
707 ('@>10', '-Inf', '@-Infinity'),
708 ('#>5', '-Inf', '-Infinity'),
709 ('?^5', '123', '?123?'),
710 ('%^6', '123', '%123%%'),
711 (' ^6', '-45.6', '-45.6 '),
712 ('/=10', '-45.6', '-/////45.6'),
713 ('/=+10', '45.6', '+/////45.6'),
714 ('/= 10', '45.6', ' /////45.6'),
715
716 # thousands separator
717 (',', '1234567', '1,234,567'),
718 (',', '123456', '123,456'),
719 (',', '12345', '12,345'),
720 (',', '1234', '1,234'),
721 (',', '123', '123'),
722 (',', '12', '12'),
723 (',', '1', '1'),
724 (',', '0', '0'),
725 (',', '-1234567', '-1,234,567'),
726 (',', '-123456', '-123,456'),
727 ('7,', '123456', '123,456'),
728 ('8,', '123456', '123,456 '),
729 ('08,', '123456', '0,123,456'), # special case: extra 0 needed
730 ('+08,', '123456', '+123,456'), # but not if there's a sign
731 (' 08,', '123456', ' 123,456'),
732 ('08,', '-123456', '-123,456'),
733 ('+09,', '123456', '+0,123,456'),
734 # ... with fractional part...
735 ('07,', '1234.56', '1,234.56'),
736 ('08,', '1234.56', '1,234.56'),
737 ('09,', '1234.56', '01,234.56'),
738 ('010,', '1234.56', '001,234.56'),
739 ('011,', '1234.56', '0,001,234.56'),
740 ('012,', '1234.56', '0,001,234.56'),
741 ('08,.1f', '1234.5', '01,234.5'),
742 # no thousands separators in fraction part
743 (',', '1.23456789', '1.23456789'),
744 (',%', '123.456789', '12,345.6789%'),
745 (',e', '123456', '1.23456e+5'),
746 (',E', '123456', '1.23456E+5'),
Christian Heimesf16baeb2008-02-29 14:57:44 +0000747 ]
748 for fmt, d, result in test_values:
749 self.assertEqual(format(Decimal(d), fmt), result)
750
Mark Dickinson79f52032009-03-17 23:12:51 +0000751 def test_n_format(self):
752 try:
753 from locale import CHAR_MAX
754 except ImportError:
755 return
756
757 # Set up some localeconv-like dictionaries
758 en_US = {
759 'decimal_point' : '.',
760 'grouping' : [3, 3, 0],
761 'thousands_sep': ','
762 }
763
764 fr_FR = {
765 'decimal_point' : ',',
766 'grouping' : [CHAR_MAX],
767 'thousands_sep' : ''
768 }
769
770 ru_RU = {
771 'decimal_point' : ',',
772 'grouping' : [3, 3, 0],
773 'thousands_sep' : ' '
774 }
775
776 crazy = {
777 'decimal_point' : '&',
778 'grouping' : [1, 4, 2, CHAR_MAX],
779 'thousands_sep' : '-'
780 }
781
782
783 def get_fmt(x, locale, fmt='n'):
784 return Decimal.__format__(Decimal(x), fmt, _localeconv=locale)
785
786 self.assertEqual(get_fmt(Decimal('12.7'), en_US), '12.7')
787 self.assertEqual(get_fmt(Decimal('12.7'), fr_FR), '12,7')
788 self.assertEqual(get_fmt(Decimal('12.7'), ru_RU), '12,7')
789 self.assertEqual(get_fmt(Decimal('12.7'), crazy), '1-2&7')
790
791 self.assertEqual(get_fmt(123456789, en_US), '123,456,789')
792 self.assertEqual(get_fmt(123456789, fr_FR), '123456789')
793 self.assertEqual(get_fmt(123456789, ru_RU), '123 456 789')
794 self.assertEqual(get_fmt(1234567890123, crazy), '123456-78-9012-3')
795
796 self.assertEqual(get_fmt(123456789, en_US, '.6n'), '1.23457e+8')
797 self.assertEqual(get_fmt(123456789, fr_FR, '.6n'), '1,23457e+8')
798 self.assertEqual(get_fmt(123456789, ru_RU, '.6n'), '1,23457e+8')
799 self.assertEqual(get_fmt(123456789, crazy, '.6n'), '1&23457e+8')
800
801
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000802class DecimalArithmeticOperatorsTest(unittest.TestCase):
803 '''Unit tests for all arithmetic operators, binary and unary.'''
804
805 def test_addition(self):
806
807 d1 = Decimal('-11.1')
808 d2 = Decimal('22.2')
809
810 #two Decimals
811 self.assertEqual(d1+d2, Decimal('11.1'))
812 self.assertEqual(d2+d1, Decimal('11.1'))
813
814 #with other type, left
815 c = d1 + 5
816 self.assertEqual(c, Decimal('-6.1'))
817 self.assertEqual(type(c), type(d1))
818
819 #with other type, right
820 c = 5 + d1
821 self.assertEqual(c, Decimal('-6.1'))
822 self.assertEqual(type(c), type(d1))
823
824 #inline with decimal
825 d1 += d2
826 self.assertEqual(d1, Decimal('11.1'))
827
828 #inline with other type
829 d1 += 5
830 self.assertEqual(d1, Decimal('16.1'))
831
832 def test_subtraction(self):
833
834 d1 = Decimal('-11.1')
835 d2 = Decimal('22.2')
836
837 #two Decimals
838 self.assertEqual(d1-d2, Decimal('-33.3'))
839 self.assertEqual(d2-d1, Decimal('33.3'))
840
841 #with other type, left
842 c = d1 - 5
843 self.assertEqual(c, Decimal('-16.1'))
844 self.assertEqual(type(c), type(d1))
845
846 #with other type, right
847 c = 5 - d1
848 self.assertEqual(c, Decimal('16.1'))
849 self.assertEqual(type(c), type(d1))
850
851 #inline with decimal
852 d1 -= d2
853 self.assertEqual(d1, Decimal('-33.3'))
854
855 #inline with other type
856 d1 -= 5
857 self.assertEqual(d1, Decimal('-38.3'))
858
859 def test_multiplication(self):
860
861 d1 = Decimal('-5')
862 d2 = Decimal('3')
863
864 #two Decimals
865 self.assertEqual(d1*d2, Decimal('-15'))
866 self.assertEqual(d2*d1, Decimal('-15'))
867
868 #with other type, left
869 c = d1 * 5
870 self.assertEqual(c, Decimal('-25'))
871 self.assertEqual(type(c), type(d1))
872
873 #with other type, right
874 c = 5 * d1
875 self.assertEqual(c, Decimal('-25'))
876 self.assertEqual(type(c), type(d1))
877
878 #inline with decimal
879 d1 *= d2
880 self.assertEqual(d1, Decimal('-15'))
881
882 #inline with other type
883 d1 *= 5
884 self.assertEqual(d1, Decimal('-75'))
885
886 def test_division(self):
887
888 d1 = Decimal('-5')
889 d2 = Decimal('2')
890
891 #two Decimals
892 self.assertEqual(d1/d2, Decimal('-2.5'))
893 self.assertEqual(d2/d1, Decimal('-0.4'))
894
895 #with other type, left
896 c = d1 / 4
897 self.assertEqual(c, Decimal('-1.25'))
898 self.assertEqual(type(c), type(d1))
899
900 #with other type, right
901 c = 4 / d1
902 self.assertEqual(c, Decimal('-0.8'))
903 self.assertEqual(type(c), type(d1))
904
905 #inline with decimal
906 d1 /= d2
907 self.assertEqual(d1, Decimal('-2.5'))
908
909 #inline with other type
910 d1 /= 4
911 self.assertEqual(d1, Decimal('-0.625'))
912
913 def test_floor_division(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000914
915 d1 = Decimal('5')
916 d2 = Decimal('2')
917
918 #two Decimals
919 self.assertEqual(d1//d2, Decimal('2'))
920 self.assertEqual(d2//d1, Decimal('0'))
921
922 #with other type, left
923 c = d1 // 4
924 self.assertEqual(c, Decimal('1'))
925 self.assertEqual(type(c), type(d1))
926
927 #with other type, right
928 c = 7 // d1
929 self.assertEqual(c, Decimal('1'))
930 self.assertEqual(type(c), type(d1))
931
932 #inline with decimal
933 d1 //= d2
934 self.assertEqual(d1, Decimal('2'))
935
936 #inline with other type
937 d1 //= 2
938 self.assertEqual(d1, Decimal('1'))
939
940 def test_powering(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000941
942 d1 = Decimal('5')
943 d2 = Decimal('2')
944
945 #two Decimals
946 self.assertEqual(d1**d2, Decimal('25'))
947 self.assertEqual(d2**d1, Decimal('32'))
948
949 #with other type, left
950 c = d1 ** 4
951 self.assertEqual(c, Decimal('625'))
952 self.assertEqual(type(c), type(d1))
953
954 #with other type, right
955 c = 7 ** d1
956 self.assertEqual(c, Decimal('16807'))
957 self.assertEqual(type(c), type(d1))
958
959 #inline with decimal
960 d1 **= d2
961 self.assertEqual(d1, Decimal('25'))
962
963 #inline with other type
964 d1 **= 4
965 self.assertEqual(d1, Decimal('390625'))
966
967 def test_module(self):
968
969 d1 = Decimal('5')
970 d2 = Decimal('2')
971
972 #two Decimals
973 self.assertEqual(d1%d2, Decimal('1'))
974 self.assertEqual(d2%d1, Decimal('2'))
975
976 #with other type, left
977 c = d1 % 4
978 self.assertEqual(c, Decimal('1'))
979 self.assertEqual(type(c), type(d1))
980
981 #with other type, right
982 c = 7 % d1
983 self.assertEqual(c, Decimal('2'))
984 self.assertEqual(type(c), type(d1))
985
986 #inline with decimal
987 d1 %= d2
988 self.assertEqual(d1, Decimal('1'))
989
990 #inline with other type
991 d1 %= 4
992 self.assertEqual(d1, Decimal('1'))
993
994 def test_floor_div_module(self):
995
996 d1 = Decimal('5')
997 d2 = Decimal('2')
998
999 #two Decimals
1000 (p, q) = divmod(d1, d2)
1001 self.assertEqual(p, Decimal('2'))
1002 self.assertEqual(q, Decimal('1'))
1003 self.assertEqual(type(p), type(d1))
1004 self.assertEqual(type(q), type(d1))
1005
1006 #with other type, left
1007 (p, q) = divmod(d1, 4)
1008 self.assertEqual(p, Decimal('1'))
1009 self.assertEqual(q, Decimal('1'))
1010 self.assertEqual(type(p), type(d1))
1011 self.assertEqual(type(q), type(d1))
1012
1013 #with other type, right
1014 (p, q) = divmod(7, d1)
1015 self.assertEqual(p, Decimal('1'))
1016 self.assertEqual(q, Decimal('2'))
1017 self.assertEqual(type(p), type(d1))
1018 self.assertEqual(type(q), type(d1))
1019
1020 def test_unary_operators(self):
1021 self.assertEqual(+Decimal(45), Decimal(+45)) # +
1022 self.assertEqual(-Decimal(45), Decimal(-45)) # -
1023 self.assertEqual(abs(Decimal(45)), abs(Decimal(-45))) # abs
1024
Christian Heimes77c02eb2008-02-09 02:18:51 +00001025 def test_nan_comparisons(self):
1026 n = Decimal('NaN')
1027 s = Decimal('sNaN')
1028 i = Decimal('Inf')
1029 f = Decimal('2')
1030 for x, y in [(n, n), (n, i), (i, n), (n, f), (f, n),
1031 (s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)]:
1032 self.assert_(x != y)
1033 self.assert_(not (x == y))
1034 self.assert_(not (x < y))
1035 self.assert_(not (x <= y))
1036 self.assert_(not (x > y))
1037 self.assert_(not (x >= y))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038
1039# The following are two functions used to test threading in the next class
1040
1041def thfunc1(cls):
1042 d1 = Decimal(1)
1043 d3 = Decimal(3)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001044 test1 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001045 cls.synchro.wait()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001046 test2 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047 cls.finish1.set()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001048
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001049 cls.assertEqual(test1, Decimal('0.3333333333333333333333333333'))
1050 cls.assertEqual(test2, Decimal('0.3333333333333333333333333333'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 return
1052
1053def thfunc2(cls):
1054 d1 = Decimal(1)
1055 d3 = Decimal(3)
Christian Heimesfe337bf2008-03-23 21:54:12 +00001056 test1 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057 thiscontext = getcontext()
1058 thiscontext.prec = 18
Christian Heimesfe337bf2008-03-23 21:54:12 +00001059 test2 = d1/d3
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001060 cls.synchro.set()
1061 cls.finish2.set()
Christian Heimesfe337bf2008-03-23 21:54:12 +00001062
Christian Heimes81ee3ef2008-05-04 22:42:01 +00001063 cls.assertEqual(test1, Decimal('0.3333333333333333333333333333'))
Christian Heimesfe337bf2008-03-23 21:54:12 +00001064 cls.assertEqual(test2, Decimal('0.333333333333333333'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001065 return
1066
1067
1068class DecimalUseOfContextTest(unittest.TestCase):
1069 '''Unit tests for Use of Context cases in Decimal.'''
1070
Raymond Hettinger7e71fa52004-12-18 19:07:19 +00001071 try:
1072 import threading
1073 except ImportError:
1074 threading = None
1075
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001076 # Take care executing this test from IDLE, there's an issue in threading
1077 # that hangs IDLE and I couldn't find it
1078
1079 def test_threading(self):
1080 #Test the "threading isolation" of a Context.
1081
1082 self.synchro = threading.Event()
1083 self.finish1 = threading.Event()
1084 self.finish2 = threading.Event()
1085
1086 th1 = threading.Thread(target=thfunc1, args=(self,))
1087 th2 = threading.Thread(target=thfunc2, args=(self,))
1088
1089 th1.start()
1090 th2.start()
1091
1092 self.finish1.wait()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001093 self.finish2.wait()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094 return
1095
Raymond Hettinger7e71fa52004-12-18 19:07:19 +00001096 if threading is None:
1097 del test_threading
1098
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001099
1100class DecimalUsabilityTest(unittest.TestCase):
1101 '''Unit tests for Usability cases of Decimal.'''
1102
1103 def test_comparison_operators(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001104
1105 da = Decimal('23.42')
1106 db = Decimal('23.42')
1107 dc = Decimal('45')
1108
1109 #two Decimals
1110 self.failUnless(dc > da)
1111 self.failUnless(dc >= da)
1112 self.failUnless(da < dc)
1113 self.failUnless(da <= dc)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001114 self.assertEqual(da, db)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115 self.failUnless(da != dc)
1116 self.failUnless(da <= db)
1117 self.failUnless(da >= db)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001118
1119 #a Decimal and an int
1120 self.failUnless(dc > 23)
1121 self.failUnless(23 < dc)
Guido van Rossume61fd5b2007-07-11 12:20:59 +00001122 self.assertEqual(dc, 45)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001123
1124 #a Decimal and uncomparable
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001125 self.assertNotEqual(da, 'ugly')
1126 self.assertNotEqual(da, 32.7)
1127 self.assertNotEqual(da, object())
1128 self.assertNotEqual(da, object)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001130 # sortable
Guido van Rossumc1f779c2007-07-03 08:25:58 +00001131 a = list(map(Decimal, range(100)))
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001132 b = a[:]
1133 random.shuffle(a)
1134 a.sort()
1135 self.assertEqual(a, b)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001136
1137 def test_copy_and_deepcopy_methods(self):
1138 d = Decimal('43.24')
1139 c = copy.copy(d)
1140 self.assertEqual(id(c), id(d))
1141 dc = copy.deepcopy(d)
1142 self.assertEqual(id(dc), id(d))
1143
1144 def test_hash_method(self):
1145 #just that it's hashable
1146 hash(Decimal(23))
Thomas Wouters8ce81f72007-09-20 18:22:40 +00001147
1148 test_values = [Decimal(sign*(2**m + n))
1149 for m in [0, 14, 15, 16, 17, 30, 31,
1150 32, 33, 62, 63, 64, 65, 66]
1151 for n in range(-10, 10)
1152 for sign in [-1, 1]]
1153 test_values.extend([
1154 Decimal("-0"), # zeros
1155 Decimal("0.00"),
1156 Decimal("-0.000"),
1157 Decimal("0E10"),
1158 Decimal("-0E12"),
1159 Decimal("10.0"), # negative exponent
1160 Decimal("-23.00000"),
1161 Decimal("1230E100"), # positive exponent
1162 Decimal("-4.5678E50"),
1163 # a value for which hash(n) != hash(n % (2**64-1))
1164 # in Python pre-2.6
1165 Decimal(2**64 + 2**32 - 1),
1166 # selection of values which fail with the old (before
1167 # version 2.6) long.__hash__
1168 Decimal("1.634E100"),
1169 Decimal("90.697E100"),
1170 Decimal("188.83E100"),
1171 Decimal("1652.9E100"),
1172 Decimal("56531E100"),
1173 ])
1174
1175 # check that hash(d) == hash(int(d)) for integral values
1176 for value in test_values:
1177 self.assertEqual(hash(value), hash(int(value)))
1178
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001179 #the same hash that to an int
1180 self.assertEqual(hash(Decimal(23)), hash(23))
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +00001181 self.assertRaises(TypeError, hash, Decimal('NaN'))
1182 self.assert_(hash(Decimal('Inf')))
1183 self.assert_(hash(Decimal('-Inf')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
Christian Heimes2380ac72008-01-09 00:17:24 +00001185 # check that the value of the hash doesn't depend on the
1186 # current context (issue #1757)
1187 c = getcontext()
1188 old_precision = c.prec
1189 x = Decimal("123456789.1")
1190
1191 c.prec = 6
1192 h1 = hash(x)
1193 c.prec = 10
1194 h2 = hash(x)
1195 c.prec = 16
1196 h3 = hash(x)
1197
1198 self.assertEqual(h1, h2)
1199 self.assertEqual(h1, h3)
1200 c.prec = old_precision
1201
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 def test_min_and_max_methods(self):
1203
1204 d1 = Decimal('15.32')
1205 d2 = Decimal('28.5')
1206 l1 = 15
1207 l2 = 28
1208
1209 #between Decimals
1210 self.failUnless(min(d1,d2) is d1)
1211 self.failUnless(min(d2,d1) is d1)
1212 self.failUnless(max(d1,d2) is d2)
1213 self.failUnless(max(d2,d1) is d2)
1214
1215 #between Decimal and long
1216 self.failUnless(min(d1,l2) is d1)
1217 self.failUnless(min(l2,d1) is d1)
1218 self.failUnless(max(l1,d2) is d2)
1219 self.failUnless(max(d2,l1) is d2)
1220
1221 def test_as_nonzero(self):
1222 #as false
1223 self.failIf(Decimal(0))
1224 #as true
1225 self.failUnless(Decimal('0.372'))
1226
1227 def test_tostring_methods(self):
1228 #Test str and repr methods.
1229
1230 d = Decimal('15.32')
1231 self.assertEqual(str(d), '15.32') # str
Christian Heimes68f5fbe2008-02-14 08:27:37 +00001232 self.assertEqual(repr(d), "Decimal('15.32')") # repr
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001233
1234 def test_tonum_methods(self):
1235 #Test float, int and long methods.
1236
1237 d1 = Decimal('66')
1238 d2 = Decimal('15.32')
1239
1240 #int
1241 self.assertEqual(int(d1), 66)
1242 self.assertEqual(int(d2), 15)
1243
1244 #long
Guido van Rossume2a383d2007-01-15 16:59:06 +00001245 self.assertEqual(int(d1), 66)
1246 self.assertEqual(int(d2), 15)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001247
1248 #float
1249 self.assertEqual(float(d1), 66)
1250 self.assertEqual(float(d2), 15.32)
1251
Mark Dickinsonb27406c2008-05-09 13:42:33 +00001252 #floor
1253 test_pairs = [
1254 ('123.00', 123),
1255 ('3.2', 3),
1256 ('3.54', 3),
1257 ('3.899', 3),
1258 ('-2.3', -3),
1259 ('-11.0', -11),
1260 ('0.0', 0),
1261 ('-0E3', 0),
1262 ]
1263 for d, i in test_pairs:
1264 self.assertEqual(math.floor(Decimal(d)), i)
1265 self.assertRaises(ValueError, math.floor, Decimal('-NaN'))
1266 self.assertRaises(ValueError, math.floor, Decimal('sNaN'))
1267 self.assertRaises(ValueError, math.floor, Decimal('NaN123'))
1268 self.assertRaises(OverflowError, math.floor, Decimal('Inf'))
1269 self.assertRaises(OverflowError, math.floor, Decimal('-Inf'))
1270
1271 #ceiling
1272 test_pairs = [
1273 ('123.00', 123),
1274 ('3.2', 4),
1275 ('3.54', 4),
1276 ('3.899', 4),
1277 ('-2.3', -2),
1278 ('-11.0', -11),
1279 ('0.0', 0),
1280 ('-0E3', 0),
1281 ]
1282 for d, i in test_pairs:
1283 self.assertEqual(math.ceil(Decimal(d)), i)
1284 self.assertRaises(ValueError, math.ceil, Decimal('-NaN'))
1285 self.assertRaises(ValueError, math.ceil, Decimal('sNaN'))
1286 self.assertRaises(ValueError, math.ceil, Decimal('NaN123'))
1287 self.assertRaises(OverflowError, math.ceil, Decimal('Inf'))
1288 self.assertRaises(OverflowError, math.ceil, Decimal('-Inf'))
1289
1290 #round, single argument
1291 test_pairs = [
1292 ('123.00', 123),
1293 ('3.2', 3),
1294 ('3.54', 4),
1295 ('3.899', 4),
1296 ('-2.3', -2),
1297 ('-11.0', -11),
1298 ('0.0', 0),
1299 ('-0E3', 0),
1300 ('-3.5', -4),
1301 ('-2.5', -2),
1302 ('-1.5', -2),
1303 ('-0.5', 0),
1304 ('0.5', 0),
1305 ('1.5', 2),
1306 ('2.5', 2),
1307 ('3.5', 4),
1308 ]
1309 for d, i in test_pairs:
1310 self.assertEqual(round(Decimal(d)), i)
1311 self.assertRaises(ValueError, round, Decimal('-NaN'))
1312 self.assertRaises(ValueError, round, Decimal('sNaN'))
1313 self.assertRaises(ValueError, round, Decimal('NaN123'))
1314 self.assertRaises(OverflowError, round, Decimal('Inf'))
1315 self.assertRaises(OverflowError, round, Decimal('-Inf'))
1316
1317 #round, two arguments; this is essentially equivalent
1318 #to quantize, which is already extensively tested
1319 test_triples = [
1320 ('123.456', -4, '0E+4'),
1321 ('123.456', -3, '0E+3'),
1322 ('123.456', -2, '1E+2'),
1323 ('123.456', -1, '1.2E+2'),
1324 ('123.456', 0, '123'),
1325 ('123.456', 1, '123.5'),
1326 ('123.456', 2, '123.46'),
1327 ('123.456', 3, '123.456'),
1328 ('123.456', 4, '123.4560'),
1329 ('123.455', 2, '123.46'),
1330 ('123.445', 2, '123.44'),
1331 ('Inf', 4, 'NaN'),
1332 ('-Inf', -23, 'NaN'),
1333 ('sNaN314', 3, 'NaN314'),
1334 ]
1335 for d, n, r in test_triples:
1336 self.assertEqual(str(round(Decimal(d), n)), r)
1337
1338
1339
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001340 def test_eval_round_trip(self):
1341
1342 #with zero
1343 d = Decimal( (0, (0,), 0) )
1344 self.assertEqual(d, eval(repr(d)))
1345
1346 #int
1347 d = Decimal( (1, (4, 5), 0) )
1348 self.assertEqual(d, eval(repr(d)))
1349
1350 #float
1351 d = Decimal( (0, (4, 5, 3, 4), -2) )
1352 self.assertEqual(d, eval(repr(d)))
1353
1354 #weird
1355 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
1356 self.assertEqual(d, eval(repr(d)))
1357
1358 def test_as_tuple(self):
1359
1360 #with zero
1361 d = Decimal(0)
1362 self.assertEqual(d.as_tuple(), (0, (0,), 0) )
1363
1364 #int
1365 d = Decimal(-45)
1366 self.assertEqual(d.as_tuple(), (1, (4, 5), 0) )
1367
1368 #complicated string
1369 d = Decimal("-4.34913534E-17")
1370 self.assertEqual(d.as_tuple(), (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
1371
1372 #inf
1373 d = Decimal("Infinity")
1374 self.assertEqual(d.as_tuple(), (0, (0,), 'F') )
1375
Guido van Rossum8ce8a782007-11-01 19:42:39 +00001376 #leading zeros in coefficient should be stripped
1377 d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), -2) )
1378 self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), -2) )
1379 d = Decimal( (1, (0, 0, 0), 37) )
1380 self.assertEqual(d.as_tuple(), (1, (0,), 37))
1381 d = Decimal( (1, (), 37) )
1382 self.assertEqual(d.as_tuple(), (1, (0,), 37))
1383
1384 #leading zeros in NaN diagnostic info should be stripped
1385 d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), 'n') )
1386 self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), 'n') )
1387 d = Decimal( (1, (0, 0, 0), 'N') )
1388 self.assertEqual(d.as_tuple(), (1, (), 'N') )
1389 d = Decimal( (1, (), 'n') )
1390 self.assertEqual(d.as_tuple(), (1, (), 'n') )
1391
1392 #coefficient in infinity should be ignored
1393 d = Decimal( (0, (4, 5, 3, 4), 'F') )
1394 self.assertEqual(d.as_tuple(), (0, (0,), 'F'))
1395 d = Decimal( (1, (0, 2, 7, 1), 'F') )
1396 self.assertEqual(d.as_tuple(), (1, (0,), 'F'))
1397
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001398 def test_immutability_operations(self):
1399 # Do operations and check that it didn't change change internal objects.
1400
1401 d1 = Decimal('-25e55')
1402 b1 = Decimal('-25e55')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403 d2 = Decimal('33e+33')
1404 b2 = Decimal('33e+33')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
1406 def checkSameDec(operation, useOther=False):
1407 if useOther:
1408 eval("d1." + operation + "(d2)")
1409 self.assertEqual(d1._sign, b1._sign)
1410 self.assertEqual(d1._int, b1._int)
1411 self.assertEqual(d1._exp, b1._exp)
1412 self.assertEqual(d2._sign, b2._sign)
1413 self.assertEqual(d2._int, b2._int)
1414 self.assertEqual(d2._exp, b2._exp)
1415 else:
1416 eval("d1." + operation + "()")
1417 self.assertEqual(d1._sign, b1._sign)
1418 self.assertEqual(d1._int, b1._int)
1419 self.assertEqual(d1._exp, b1._exp)
1420 return
1421
1422 Decimal(d1)
1423 self.assertEqual(d1._sign, b1._sign)
1424 self.assertEqual(d1._int, b1._int)
1425 self.assertEqual(d1._exp, b1._exp)
1426
1427 checkSameDec("__abs__")
1428 checkSameDec("__add__", True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001429 checkSameDec("__divmod__", True)
Christian Heimes77c02eb2008-02-09 02:18:51 +00001430 checkSameDec("__eq__", True)
1431 checkSameDec("__ne__", True)
1432 checkSameDec("__le__", True)
1433 checkSameDec("__lt__", True)
1434 checkSameDec("__ge__", True)
1435 checkSameDec("__gt__", True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001436 checkSameDec("__float__")
1437 checkSameDec("__floordiv__", True)
1438 checkSameDec("__hash__")
1439 checkSameDec("__int__")
Christian Heimes969fe572008-01-25 11:23:10 +00001440 checkSameDec("__trunc__")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001441 checkSameDec("__mod__", True)
1442 checkSameDec("__mul__", True)
1443 checkSameDec("__neg__")
Jack Diederich4dafcc42006-11-28 19:15:13 +00001444 checkSameDec("__bool__")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001445 checkSameDec("__pos__")
1446 checkSameDec("__pow__", True)
1447 checkSameDec("__radd__", True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001448 checkSameDec("__rdivmod__", True)
1449 checkSameDec("__repr__")
1450 checkSameDec("__rfloordiv__", True)
1451 checkSameDec("__rmod__", True)
1452 checkSameDec("__rmul__", True)
1453 checkSameDec("__rpow__", True)
1454 checkSameDec("__rsub__", True)
1455 checkSameDec("__str__")
1456 checkSameDec("__sub__", True)
1457 checkSameDec("__truediv__", True)
1458 checkSameDec("adjusted")
1459 checkSameDec("as_tuple")
1460 checkSameDec("compare", True)
1461 checkSameDec("max", True)
1462 checkSameDec("min", True)
1463 checkSameDec("normalize")
1464 checkSameDec("quantize", True)
1465 checkSameDec("remainder_near", True)
1466 checkSameDec("same_quantum", True)
1467 checkSameDec("sqrt")
1468 checkSameDec("to_eng_string")
1469 checkSameDec("to_integral")
1470
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471 def test_subclassing(self):
1472 # Different behaviours when subclassing Decimal
1473
1474 class MyDecimal(Decimal):
1475 pass
1476
1477 d1 = MyDecimal(1)
1478 d2 = MyDecimal(2)
1479 d = d1 + d2
1480 self.assertTrue(type(d) is Decimal)
1481
1482 d = d1.max(d2)
1483 self.assertTrue(type(d) is Decimal)
1484
Christian Heimes0348fb62008-03-26 12:55:56 +00001485 def test_implicit_context(self):
1486 # Check results when context given implicitly. (Issue 2478)
1487 c = getcontext()
1488 self.assertEqual(str(Decimal(0).sqrt()),
1489 str(c.sqrt(Decimal(0))))
1490
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001491
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001492class DecimalPythonAPItests(unittest.TestCase):
1493
Raymond Hettinger82417ca2009-02-03 03:54:28 +00001494 def test_abc(self):
1495 self.assert_(issubclass(Decimal, numbers.Number))
1496 self.assert_(not issubclass(Decimal, numbers.Real))
1497 self.assert_(isinstance(Decimal(0), numbers.Number))
1498 self.assert_(not isinstance(Decimal(0), numbers.Real))
1499
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500 def test_pickle(self):
1501 d = Decimal('-3.141590000')
1502 p = pickle.dumps(d)
1503 e = pickle.loads(p)
1504 self.assertEqual(d, e)
1505
Raymond Hettinger5548be22004-07-05 18:49:38 +00001506 def test_int(self):
Raymond Hettinger605ed022004-11-24 07:28:48 +00001507 for x in range(-250, 250):
1508 s = '%0.2f' % (x / 100.0)
Raymond Hettinger5548be22004-07-05 18:49:38 +00001509 # should work the same as for floats
1510 self.assertEqual(int(Decimal(s)), int(float(s)))
Raymond Hettinger605ed022004-11-24 07:28:48 +00001511 # should work the same as to_integral in the ROUND_DOWN mode
Raymond Hettinger5548be22004-07-05 18:49:38 +00001512 d = Decimal(s)
Raymond Hettinger605ed022004-11-24 07:28:48 +00001513 r = d.to_integral(ROUND_DOWN)
Raymond Hettinger5548be22004-07-05 18:49:38 +00001514 self.assertEqual(Decimal(int(d)), r)
1515
Christian Heimes969fe572008-01-25 11:23:10 +00001516 def test_trunc(self):
1517 for x in range(-250, 250):
1518 s = '%0.2f' % (x / 100.0)
1519 # should work the same as for floats
1520 self.assertEqual(int(Decimal(s)), int(float(s)))
1521 # should work the same as to_integral in the ROUND_DOWN mode
1522 d = Decimal(s)
1523 r = d.to_integral(ROUND_DOWN)
Christian Heimes400adb02008-02-01 08:12:03 +00001524 self.assertEqual(Decimal(math.trunc(d)), r)
Christian Heimes969fe572008-01-25 11:23:10 +00001525
Raymond Hettinger771ed762009-01-03 19:20:32 +00001526 def test_from_float(self):
1527
1528 class MyDecimal(Decimal):
1529 pass
1530
1531 r = MyDecimal.from_float(0.1)
1532 self.assertEqual(type(r), MyDecimal)
1533 self.assertEqual(str(r),
1534 '0.1000000000000000055511151231257827021181583404541015625')
1535 bigint = 12345678901234567890123456789
1536 self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
1537 self.assert_(MyDecimal.from_float(float('nan')).is_qnan())
1538 self.assert_(MyDecimal.from_float(float('inf')).is_infinite())
1539 self.assert_(MyDecimal.from_float(float('-inf')).is_infinite())
1540 self.assertEqual(str(MyDecimal.from_float(float('nan'))),
1541 str(Decimal('NaN')))
1542 self.assertEqual(str(MyDecimal.from_float(float('inf'))),
1543 str(Decimal('Infinity')))
1544 self.assertEqual(str(MyDecimal.from_float(float('-inf'))),
1545 str(Decimal('-Infinity')))
1546 self.assertRaises(TypeError, MyDecimal.from_float, 'abc')
1547 for i in range(200):
1548 x = random.expovariate(0.01) * (random.random() * 2.0 - 1.0)
1549 self.assertEqual(x, float(MyDecimal.from_float(x))) # roundtrip
1550
1551 def test_create_decimal_from_float(self):
1552 context = Context(prec=5, rounding=ROUND_DOWN)
1553 self.assertEqual(
1554 context.create_decimal_from_float(math.pi),
1555 Decimal('3.1415')
1556 )
1557 context = Context(prec=5, rounding=ROUND_UP)
1558 self.assertEqual(
1559 context.create_decimal_from_float(math.pi),
1560 Decimal('3.1416')
1561 )
1562 context = Context(prec=5, traps=[Inexact])
1563 self.assertRaises(
1564 Inexact,
1565 context.create_decimal_from_float,
1566 math.pi
1567 )
1568 self.assertEqual(repr(context.create_decimal_from_float(-0.0)),
1569 "Decimal('-0')")
1570 self.assertEqual(repr(context.create_decimal_from_float(1.0)),
1571 "Decimal('1')")
1572 self.assertEqual(repr(context.create_decimal_from_float(10)),
1573 "Decimal('10')")
1574
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00001575class ContextAPItests(unittest.TestCase):
1576
1577 def test_pickle(self):
1578 c = Context()
1579 e = pickle.loads(pickle.dumps(c))
1580 for k in vars(c):
1581 v1 = vars(c)[k]
1582 v2 = vars(e)[k]
1583 self.assertEqual(v1, v2)
1584
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001585 def test_equality_with_other_types(self):
1586 self.assert_(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}])
1587 self.assert_(Decimal(10) not in ['a', 1.0, (1,2), {}])
1588
Raymond Hettinger955d2b22004-08-08 20:17:45 +00001589 def test_copy(self):
1590 # All copies should be deep
1591 c = Context()
1592 d = c.copy()
1593 self.assertNotEqual(id(c), id(d))
1594 self.assertNotEqual(id(c.flags), id(d.flags))
1595 self.assertNotEqual(id(c.traps), id(d.traps))
1596
Thomas Wouters89f507f2006-12-13 04:49:30 +00001597class WithStatementTest(unittest.TestCase):
1598 # Can't do these as docstrings until Python 2.6
1599 # as doctest can't handle __future__ statements
1600
1601 def test_localcontext(self):
1602 # Use a copy of the current context in the block
1603 orig_ctx = getcontext()
1604 with localcontext() as enter_ctx:
1605 set_ctx = getcontext()
1606 final_ctx = getcontext()
1607 self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
1608 self.assert_(orig_ctx is not set_ctx, 'did not copy the context')
1609 self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
1610
1611 def test_localcontextarg(self):
1612 # Use a copy of the supplied context in the block
1613 orig_ctx = getcontext()
1614 new_ctx = Context(prec=42)
1615 with localcontext(new_ctx) as enter_ctx:
1616 set_ctx = getcontext()
1617 final_ctx = getcontext()
1618 self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
1619 self.assert_(set_ctx.prec == new_ctx.prec, 'did not set correct context')
1620 self.assert_(new_ctx is not set_ctx, 'did not copy the context')
1621 self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
1622
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001623class ContextFlags(unittest.TestCase):
1624 def test_flags_irrelevant(self):
1625 # check that the result (numeric result + flags raised) of an
1626 # arithmetic operation doesn't depend on the current flags
1627
1628 context = Context(prec=9, Emin = -999999999, Emax = 999999999,
1629 rounding=ROUND_HALF_EVEN, traps=[], flags=[])
1630
1631 # operations that raise various flags, in the form (function, arglist)
1632 operations = [
1633 (context._apply, [Decimal("100E-1000000009")]),
1634 (context.sqrt, [Decimal(2)]),
1635 (context.add, [Decimal("1.23456789"), Decimal("9.87654321")]),
1636 (context.multiply, [Decimal("1.23456789"), Decimal("9.87654321")]),
1637 (context.subtract, [Decimal("1.23456789"), Decimal("9.87654321")]),
1638 ]
1639
1640 # try various flags individually, then a whole lot at once
1641 flagsets = [[Inexact], [Rounded], [Underflow], [Clamped], [Subnormal],
1642 [Inexact, Rounded, Underflow, Clamped, Subnormal]]
1643
1644 for fn, args in operations:
1645 # find answer and flags raised using a clean context
1646 context.clear_flags()
1647 ans = fn(*args)
1648 flags = [k for k, v in context.flags.items() if v]
1649
1650 for extra_flags in flagsets:
1651 # set flags, before calling operation
1652 context.clear_flags()
1653 for flag in extra_flags:
1654 context._raise_error(flag)
1655 new_ans = fn(*args)
1656
1657 # flags that we expect to be set after the operation
1658 expected_flags = list(flags)
1659 for flag in extra_flags:
1660 if flag not in expected_flags:
1661 expected_flags.append(flag)
1662 expected_flags.sort(key=id)
1663
1664 # flags we actually got
1665 new_flags = [k for k,v in context.flags.items() if v]
1666 new_flags.sort(key=id)
1667
1668 self.assertEqual(ans, new_ans,
1669 "operation produces different answers depending on flags set: " +
1670 "expected %s, got %s." % (ans, new_ans))
1671 self.assertEqual(new_flags, expected_flags,
1672 "operation raises different flags depending on flags set: " +
1673 "expected %s, got %s" % (expected_flags, new_flags))
1674
1675def test_main(arith=False, verbose=None, todo_tests=None, debug=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001676 """ Execute the tests.
1677
Raymond Hettingered20ad82004-09-04 20:09:13 +00001678 Runs all arithmetic tests if arith is True or if the "decimal" resource
1679 is enabled in regrtest.py
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001680 """
Raymond Hettingered20ad82004-09-04 20:09:13 +00001681
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001682 init()
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683 global TEST_ALL, DEBUG
Raymond Hettingered20ad82004-09-04 20:09:13 +00001684 TEST_ALL = arith or is_resource_enabled('decimal')
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001685 DEBUG = debug
Raymond Hettingered20ad82004-09-04 20:09:13 +00001686
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001687 if todo_tests is None:
1688 test_classes = [
1689 DecimalExplicitConstructionTest,
1690 DecimalImplicitConstructionTest,
1691 DecimalArithmeticOperatorsTest,
Christian Heimesf16baeb2008-02-29 14:57:44 +00001692 DecimalFormatTest,
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001693 DecimalUseOfContextTest,
1694 DecimalUsabilityTest,
1695 DecimalPythonAPItests,
1696 ContextAPItests,
1697 DecimalTest,
1698 WithStatementTest,
1699 ContextFlags
1700 ]
1701 else:
1702 test_classes = [DecimalTest]
1703
1704 # Dynamically build custom test definition for each file in the test
1705 # directory and add the definitions to the DecimalTest class. This
1706 # procedure insures that new files do not get skipped.
1707 for filename in os.listdir(directory):
1708 if '.decTest' not in filename or filename.startswith("."):
1709 continue
1710 head, tail = filename.split('.')
1711 if todo_tests is not None and head not in todo_tests:
1712 continue
1713 tester = lambda self, f=filename: self.eval_file(directory + f)
1714 setattr(DecimalTest, 'test_' + head, tester)
1715 del filename, head, tail, tester
1716
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001717
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001718 try:
1719 run_unittest(*test_classes)
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720 if todo_tests is None:
1721 import decimal as DecimalModule
1722 run_doctest(DecimalModule, verbose)
Thomas Wouters49fd7fa2006-04-21 10:40:58 +00001723 finally:
1724 setcontext(ORIGINAL_CONTEXT)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001725
1726if __name__ == '__main__':
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727 import optparse
1728 p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]")
1729 p.add_option('--debug', '-d', action='store_true', help='shows the test number and context before each test')
1730 p.add_option('--skip', '-s', action='store_true', help='skip over 90% of the arithmetic tests')
1731 (opt, args) = p.parse_args()
1732
1733 if opt.skip:
1734 test_main(arith=False, verbose=True)
1735 elif args:
1736 test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001737 else:
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001738 test_main(arith=True, verbose=True)