blob: 0c8852c4001f6d1bf2b38d891fc4c9c1fa4e45ab [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"""
Nick Coghlan8b6999b2006-08-31 12:00:43 +000026from __future__ import with_statement
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000027
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000028import glob
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +000029import math
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000030import os, sys
31import pickle, copy
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +000032import unittest
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000033from decimal import *
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()
50 DefaultContext.prec = 9
51 DefaultContext.rounding = ROUND_HALF_EVEN
52 DefaultContext.traps = dict.fromkeys(Signals, 0)
53 setcontext(DefaultContext)
Raymond Hettinger6ea48452004-07-03 12:26:21 +000054
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000055TESTDATADIR = 'decimaltestdata'
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +000056if __name__ == '__main__':
57 file = sys.argv[0]
58else:
59 file = __file__
60testdir = os.path.dirname(file) or os.curdir
Raymond Hettinger267b8682005-03-27 10:47:39 +000061directory = testdir + os.sep + TESTDATADIR + os.sep
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000062
Raymond Hettinger267b8682005-03-27 10:47:39 +000063skip_expected = not os.path.isdir(directory)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000064
65# Make sure it actually raises errors when not expected and caught in flags
66# Slower, since it runs some things several times.
67EXTENDEDERRORTEST = False
68
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000069#Map the test cases' error names to the actual errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000070ErrorNames = {'clamped' : Clamped,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000071 'conversion_syntax' : InvalidOperation,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000072 'division_by_zero' : DivisionByZero,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000073 'division_impossible' : InvalidOperation,
74 'division_undefined' : InvalidOperation,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000075 'inexact' : Inexact,
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000076 'invalid_context' : InvalidOperation,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000077 'invalid_operation' : InvalidOperation,
78 'overflow' : Overflow,
79 'rounded' : Rounded,
80 'subnormal' : Subnormal,
81 'underflow' : Underflow}
82
83
84def Nonfunction(*args):
85 """Doesn't do anything."""
86 return None
87
88RoundingDict = {'ceiling' : ROUND_CEILING, #Maps test-case names to roundings.
89 'down' : ROUND_DOWN,
90 'floor' : ROUND_FLOOR,
91 'half_down' : ROUND_HALF_DOWN,
92 'half_even' : ROUND_HALF_EVEN,
93 'half_up' : ROUND_HALF_UP,
Facundo Batista353750c2007-09-13 18:13:15 +000094 'up' : ROUND_UP,
95 '05up' : ROUND_05UP}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000096
97# Name adapter to be able to change the Decimal and Context
98# interface without changing the test files from Cowlishaw
Facundo Batista1a191df2007-10-02 17:01:24 +000099nameAdapter = {'and':'logical_and',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000100 'apply':'_apply',
Facundo Batista353750c2007-09-13 18:13:15 +0000101 'class':'number_class',
102 'comparesig':'compare_signal',
103 'comparetotal':'compare_total',
104 'comparetotmag':'compare_total_mag',
Facundo Batista353750c2007-09-13 18:13:15 +0000105 'copy':'copy_decimal',
Facundo Batista1a191df2007-10-02 17:01:24 +0000106 'copyabs':'copy_abs',
Facundo Batista353750c2007-09-13 18:13:15 +0000107 'copynegate':'copy_negate',
108 'copysign':'copy_sign',
Facundo Batista1a191df2007-10-02 17:01:24 +0000109 'divideint':'divide_int',
Facundo Batista353750c2007-09-13 18:13:15 +0000110 'invert':'logical_invert',
Facundo Batista1a191df2007-10-02 17:01:24 +0000111 'iscanonical':'is_canonical',
112 'isfinite':'is_finite',
113 'isinfinite':'is_infinite',
114 'isnan':'is_nan',
115 'isnormal':'is_normal',
116 'isqnan':'is_qnan',
117 'issigned':'is_signed',
118 'issnan':'is_snan',
119 'issubnormal':'is_subnormal',
120 'iszero':'is_zero',
Facundo Batista353750c2007-09-13 18:13:15 +0000121 'maxmag':'max_mag',
122 'minmag':'min_mag',
123 'nextminus':'next_minus',
124 'nextplus':'next_plus',
125 'nexttoward':'next_toward',
Facundo Batista1a191df2007-10-02 17:01:24 +0000126 'or':'logical_or',
Facundo Batista353750c2007-09-13 18:13:15 +0000127 'reduce':'normalize',
Facundo Batista1a191df2007-10-02 17:01:24 +0000128 'remaindernear':'remainder_near',
129 'samequantum':'same_quantum',
130 'squareroot':'sqrt',
131 'toeng':'to_eng_string',
132 'tointegral':'to_integral_value',
133 'tointegralx':'to_integral_exact',
134 'tosci':'to_sci_string',
135 'xor':'logical_xor',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000136 }
137
Facundo Batista1a191df2007-10-02 17:01:24 +0000138# The following functions return True/False rather than a Decimal instance
139
140LOGICAL_FUNCTIONS = (
141 'is_canonical',
142 'is_finite',
143 'is_infinite',
144 'is_nan',
145 'is_normal',
146 'is_qnan',
147 'is_signed',
148 'is_snan',
149 'is_subnormal',
150 'is_zero',
151 'same_quantum',
152 )
153
Facundo Batista353750c2007-09-13 18:13:15 +0000154# For some operations (currently exp, ln, log10, power), the decNumber
155# reference implementation imposes additional restrictions on the
156# context and operands. These restrictions are not part of the
157# specification; however, the effect of these restrictions does show
158# up in some of the testcases. We skip testcases that violate these
159# restrictions, since Decimal behaves differently from decNumber for
160# these testcases so these testcases would otherwise fail.
161
162decNumberRestricted = ('power', 'ln', 'log10', 'exp')
163DEC_MAX_MATH = 999999
164def outside_decNumber_bounds(v, context):
165 if (context.prec > DEC_MAX_MATH or
166 context.Emax > DEC_MAX_MATH or
167 -context.Emin > DEC_MAX_MATH):
168 return True
169 if not v._is_special and v and (
170 len(v._int) > DEC_MAX_MATH or
171 v.adjusted() > DEC_MAX_MATH or
172 v.adjusted() < 1-2*DEC_MAX_MATH):
173 return True
174 return False
175
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000176class DecimalTest(unittest.TestCase):
177 """Class which tests the Decimal class against the test cases.
178
179 Changed for unittest.
180 """
181 def setUp(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000182 self.context = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +0000183 for key in DefaultContext.traps.keys():
184 DefaultContext.traps[key] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000185 self.ignore_list = ['#']
186 # Basically, a # means return NaN InvalidOperation.
187 # Different from a sNaN in trim
188
189 self.ChangeDict = {'precision' : self.change_precision,
190 'rounding' : self.change_rounding_method,
191 'maxexponent' : self.change_max_exponent,
192 'minexponent' : self.change_min_exponent,
193 'clamp' : self.change_clamp}
194
195 def tearDown(self):
196 """Cleaning up enviroment."""
197 # leaving context in original state
Raymond Hettingerbf440692004-07-10 14:14:37 +0000198 for key in DefaultContext.traps.keys():
199 DefaultContext.traps[key] = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000200 return
201
202 def eval_file(self, file):
203 global skip_expected
204 if skip_expected:
205 raise TestSkipped
206 return
207 for line in open(file).xreadlines():
208 line = line.replace('\r\n', '').replace('\n', '')
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000209 #print line
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000210 try:
211 t = self.eval_line(line)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000212 except DecimalException, exception:
213 #Exception raised where there shoudn't have been one.
214 self.fail('Exception "'+exception.__class__.__name__ + '" raised on line '+line)
215
216 return
217
218 def eval_line(self, s):
219 if s.find(' -> ') >= 0 and s[:2] != '--' and not s.startswith(' --'):
220 s = (s.split('->')[0] + '->' +
221 s.split('->')[1].split('--')[0]).strip()
222 else:
223 s = s.split('--')[0].strip()
224
225 for ignore in self.ignore_list:
226 if s.find(ignore) >= 0:
227 #print s.split()[0], 'NotImplemented--', ignore
228 return
229 if not s:
230 return
231 elif ':' in s:
232 return self.eval_directive(s)
233 else:
234 return self.eval_equation(s)
235
236 def eval_directive(self, s):
237 funct, value = map(lambda x: x.strip().lower(), s.split(':'))
238 if funct == 'rounding':
239 value = RoundingDict[value]
240 else:
241 try:
242 value = int(value)
243 except ValueError:
244 pass
245
246 funct = self.ChangeDict.get(funct, Nonfunction)
247 funct(value)
248
249 def eval_equation(self, s):
250 #global DEFAULT_PRECISION
251 #print DEFAULT_PRECISION
Raymond Hettingered20ad82004-09-04 20:09:13 +0000252
253 if not TEST_ALL and random.random() < 0.90:
254 return
255
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000256 try:
257 Sides = s.split('->')
258 L = Sides[0].strip().split()
259 id = L[0]
Facundo Batista353750c2007-09-13 18:13:15 +0000260 if DEBUG:
261 print "Test ", id,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000262 funct = L[1].lower()
263 valstemp = L[2:]
264 L = Sides[1].strip().split()
265 ans = L[0]
266 exceptions = L[1:]
267 except (TypeError, AttributeError, IndexError):
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +0000268 raise InvalidOperation
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000269 def FixQuotes(val):
270 val = val.replace("''", 'SingleQuote').replace('""', 'DoubleQuote')
271 val = val.replace("'", '').replace('"', '')
272 val = val.replace('SingleQuote', "'").replace('DoubleQuote', '"')
273 return val
274 fname = nameAdapter.get(funct, funct)
275 if fname == 'rescale':
276 return
277 funct = getattr(self.context, fname)
278 vals = []
279 conglomerate = ''
280 quote = 0
281 theirexceptions = [ErrorNames[x.lower()] for x in exceptions]
282
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000283 for exception in Signals:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000284 self.context.traps[exception] = 1 #Catch these bugs...
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000285 for exception in theirexceptions:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000286 self.context.traps[exception] = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000287 for i, val in enumerate(valstemp):
288 if val.count("'") % 2 == 1:
289 quote = 1 - quote
290 if quote:
291 conglomerate = conglomerate + ' ' + val
292 continue
293 else:
294 val = conglomerate + val
295 conglomerate = ''
296 v = FixQuotes(val)
297 if fname in ('to_sci_string', 'to_eng_string'):
298 if EXTENDEDERRORTEST:
299 for error in theirexceptions:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000300 self.context.traps[error] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000301 try:
302 funct(self.context.create_decimal(v))
303 except error:
304 pass
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000305 except Signals, e:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306 self.fail("Raised %s in %s when %s disabled" % \
307 (e, s, error))
308 else:
309 self.fail("Did not raise %s in %s" % (error, s))
Raymond Hettingerbf440692004-07-10 14:14:37 +0000310 self.context.traps[error] = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000311 v = self.context.create_decimal(v)
312 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000313 v = Decimal(v, self.context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000314 vals.append(v)
315
316 ans = FixQuotes(ans)
317
Facundo Batista353750c2007-09-13 18:13:15 +0000318 # skip tests that are related to bounds imposed in the decNumber
319 # reference implementation
320 if fname in decNumberRestricted:
321 if fname == 'power':
322 if not (vals[1]._isinteger() and
323 -1999999997 <= vals[1] <= 999999999):
324 if outside_decNumber_bounds(vals[0], self.context) or \
325 outside_decNumber_bounds(vals[1], self.context):
326 #print "Skipping test %s" % s
327 return
328 else:
329 if outside_decNumber_bounds(vals[0], self.context):
330 #print "Skipping test %s" % s
331 return
332
333
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000334 if EXTENDEDERRORTEST and fname not in ('to_sci_string', 'to_eng_string'):
335 for error in theirexceptions:
Raymond Hettingerbf440692004-07-10 14:14:37 +0000336 self.context.traps[error] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 try:
338 funct(*vals)
339 except error:
340 pass
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000341 except Signals, e:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000342 self.fail("Raised %s in %s when %s disabled" % \
343 (e, s, error))
344 else:
345 self.fail("Did not raise %s in %s" % (error, s))
Raymond Hettingerbf440692004-07-10 14:14:37 +0000346 self.context.traps[error] = 0
Facundo Batista353750c2007-09-13 18:13:15 +0000347 if DEBUG:
348 print "--", self.context
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 try:
350 result = str(funct(*vals))
Facundo Batista1a191df2007-10-02 17:01:24 +0000351 if fname in LOGICAL_FUNCTIONS:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000352 result = str(int(eval(result))) # 'True', 'False' -> '1', '0'
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +0000353 except Signals, error:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000354 self.fail("Raised %s in %s" % (error, s))
355 except: #Catch any error long enough to state the test case.
356 print "ERROR:", s
357 raise
358
359 myexceptions = self.getexceptions()
Raymond Hettingerbf440692004-07-10 14:14:37 +0000360 self.context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000361
362 myexceptions.sort()
363 theirexceptions.sort()
364
365 self.assertEqual(result, ans,
366 'Incorrect answer for ' + s + ' -- got ' + result)
367 self.assertEqual(myexceptions, theirexceptions,
Facundo Batista353750c2007-09-13 18:13:15 +0000368 'Incorrect flags set in ' + s + ' -- got ' + str(myexceptions))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000369 return
370
371 def getexceptions(self):
Raymond Hettingerf63ba432004-08-17 05:42:09 +0000372 return [e for e in Signals if self.context.flags[e]]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000373
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000374 def change_precision(self, prec):
375 self.context.prec = prec
376 def change_rounding_method(self, rounding):
377 self.context.rounding = rounding
378 def change_min_exponent(self, exp):
379 self.context.Emin = exp
380 def change_max_exponent(self, exp):
381 self.context.Emax = exp
382 def change_clamp(self, clamp):
383 self.context._clamp = clamp
384
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000385
386
387# The following classes test the behaviour of Decimal according to PEP 327
388
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000389class DecimalExplicitConstructionTest(unittest.TestCase):
390 '''Unit tests for Explicit Construction cases of Decimal.'''
391
392 def test_explicit_empty(self):
393 self.assertEqual(Decimal(), Decimal("0"))
394
395 def test_explicit_from_None(self):
396 self.assertRaises(TypeError, Decimal, None)
397
398 def test_explicit_from_int(self):
399
400 #positive
401 d = Decimal(45)
402 self.assertEqual(str(d), '45')
403
404 #very large positive
405 d = Decimal(500000123)
406 self.assertEqual(str(d), '500000123')
407
408 #negative
409 d = Decimal(-45)
410 self.assertEqual(str(d), '-45')
411
412 #zero
413 d = Decimal(0)
414 self.assertEqual(str(d), '0')
415
416 def test_explicit_from_string(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000417
418 #empty
419 self.assertEqual(str(Decimal('')), 'NaN')
420
421 #int
422 self.assertEqual(str(Decimal('45')), '45')
423
424 #float
425 self.assertEqual(str(Decimal('45.34')), '45.34')
426
427 #engineer notation
428 self.assertEqual(str(Decimal('45e2')), '4.5E+3')
429
430 #just not a number
431 self.assertEqual(str(Decimal('ugly')), 'NaN')
432
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000433 #leading and trailing whitespace permitted
434 self.assertEqual(str(Decimal('1.3E4 \n')), '1.3E+4')
435 self.assertEqual(str(Decimal(' -7.89')), '-7.89')
436
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000437 def test_explicit_from_tuples(self):
438
439 #zero
440 d = Decimal( (0, (0,), 0) )
441 self.assertEqual(str(d), '0')
442
443 #int
444 d = Decimal( (1, (4, 5), 0) )
445 self.assertEqual(str(d), '-45')
446
447 #float
448 d = Decimal( (0, (4, 5, 3, 4), -2) )
449 self.assertEqual(str(d), '45.34')
450
451 #weird
452 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
453 self.assertEqual(str(d), '-4.34913534E-17')
454
455 #wrong number of items
456 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1)) )
457
458 #bad sign
459 self.assertRaises(ValueError, Decimal, (8, (4, 3, 4, 9, 1), 2) )
Facundo Batista9b5e2312007-10-19 19:25:57 +0000460 self.assertRaises(ValueError, Decimal, (0., (4, 3, 4, 9, 1), 2) )
461 self.assertRaises(ValueError, Decimal, (Decimal(1), (4, 3, 4, 9, 1), 2))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000462
463 #bad exp
464 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 'wrong!') )
Facundo Batista9b5e2312007-10-19 19:25:57 +0000465 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), 0.) )
466 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 9, 1), '1') )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000467
468 #bad coefficients
469 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, None, 1), 2) )
470 self.assertRaises(ValueError, Decimal, (1, (4, -3, 4, 9, 1), 2) )
Facundo Batista9b5e2312007-10-19 19:25:57 +0000471 self.assertRaises(ValueError, Decimal, (1, (4, 10, 4, 9, 1), 2) )
Facundo Batista72bc54f2007-11-23 17:59:00 +0000472 self.assertRaises(ValueError, Decimal, (1, (4, 3, 4, 'a', 1), 2) )
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000473
474 def test_explicit_from_Decimal(self):
475
476 #positive
477 d = Decimal(45)
478 e = Decimal(d)
479 self.assertEqual(str(e), '45')
480 self.assertNotEqual(id(d), id(e))
481
482 #very large positive
483 d = Decimal(500000123)
484 e = Decimal(d)
485 self.assertEqual(str(e), '500000123')
486 self.assertNotEqual(id(d), id(e))
487
488 #negative
489 d = Decimal(-45)
490 e = Decimal(d)
491 self.assertEqual(str(e), '-45')
492 self.assertNotEqual(id(d), id(e))
493
494 #zero
495 d = Decimal(0)
496 e = Decimal(d)
497 self.assertEqual(str(e), '0')
498 self.assertNotEqual(id(d), id(e))
499
500 def test_explicit_context_create_decimal(self):
501
502 nc = copy.copy(getcontext())
503 nc.prec = 3
504
505 # empty
Raymond Hettingerfed52962004-07-14 15:41:57 +0000506 d = Decimal()
507 self.assertEqual(str(d), '0')
508 d = nc.create_decimal()
509 self.assertEqual(str(d), '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000510
511 # from None
512 self.assertRaises(TypeError, nc.create_decimal, None)
513
514 # from int
515 d = nc.create_decimal(456)
516 self.failUnless(isinstance(d, Decimal))
517 self.assertEqual(nc.create_decimal(45678),
518 nc.create_decimal('457E+2'))
519
520 # from string
521 d = Decimal('456789')
522 self.assertEqual(str(d), '456789')
523 d = nc.create_decimal('456789')
524 self.assertEqual(str(d), '4.57E+5')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000525 # leading and trailing whitespace should result in a NaN;
526 # spaces are already checked in Cowlishaw's test-suite, so
527 # here we just check that a trailing newline results in a NaN
528 self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
530 # from tuples
531 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
532 self.assertEqual(str(d), '-4.34913534E-17')
533 d = nc.create_decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
534 self.assertEqual(str(d), '-4.35E-17')
535
536 # from Decimal
537 prevdec = Decimal(500000123)
538 d = Decimal(prevdec)
539 self.assertEqual(str(d), '500000123')
540 d = nc.create_decimal(prevdec)
541 self.assertEqual(str(d), '5.00E+8')
542
543
544class DecimalImplicitConstructionTest(unittest.TestCase):
545 '''Unit tests for Implicit Construction cases of Decimal.'''
546
547 def test_implicit_from_None(self):
548 self.assertRaises(TypeError, eval, 'Decimal(5) + None', globals())
549
550 def test_implicit_from_int(self):
551 #normal
552 self.assertEqual(str(Decimal(5) + 45), '50')
553 #exceeding precision
554 self.assertEqual(Decimal(5) + 123456789000, Decimal(123456789000))
555
556 def test_implicit_from_string(self):
557 self.assertRaises(TypeError, eval, 'Decimal(5) + "3"', globals())
558
559 def test_implicit_from_float(self):
560 self.assertRaises(TypeError, eval, 'Decimal(5) + 2.2', globals())
561
562 def test_implicit_from_Decimal(self):
563 self.assertEqual(Decimal(5) + Decimal(45), Decimal(50))
564
Raymond Hettinger267b8682005-03-27 10:47:39 +0000565 def test_rop(self):
566 # Allow other classes to be trained to interact with Decimals
567 class E:
568 def __divmod__(self, other):
569 return 'divmod ' + str(other)
570 def __rdivmod__(self, other):
571 return str(other) + ' rdivmod'
572 def __lt__(self, other):
573 return 'lt ' + str(other)
574 def __gt__(self, other):
575 return 'gt ' + str(other)
576 def __le__(self, other):
577 return 'le ' + str(other)
578 def __ge__(self, other):
579 return 'ge ' + str(other)
580 def __eq__(self, other):
581 return 'eq ' + str(other)
582 def __ne__(self, other):
583 return 'ne ' + str(other)
584
585 self.assertEqual(divmod(E(), Decimal(10)), 'divmod 10')
586 self.assertEqual(divmod(Decimal(10), E()), '10 rdivmod')
587 self.assertEqual(eval('Decimal(10) < E()'), 'gt 10')
588 self.assertEqual(eval('Decimal(10) > E()'), 'lt 10')
589 self.assertEqual(eval('Decimal(10) <= E()'), 'ge 10')
590 self.assertEqual(eval('Decimal(10) >= E()'), 'le 10')
591 self.assertEqual(eval('Decimal(10) == E()'), 'eq 10')
592 self.assertEqual(eval('Decimal(10) != E()'), 'ne 10')
593
594 # insert operator methods and then exercise them
Georg Brandl96c3f7f2006-03-28 08:06:35 +0000595 oplist = [
596 ('+', '__add__', '__radd__'),
597 ('-', '__sub__', '__rsub__'),
598 ('*', '__mul__', '__rmul__'),
599 ('%', '__mod__', '__rmod__'),
600 ('//', '__floordiv__', '__rfloordiv__'),
601 ('**', '__pow__', '__rpow__')
602 ]
603 if 1/2 == 0:
604 # testing with classic division, so add __div__
605 oplist.append(('/', '__div__', '__rdiv__'))
606 else:
607 # testing with -Qnew, so add __truediv__
608 oplist.append(('/', '__truediv__', '__rtruediv__'))
Anthony Baxter4ef3a232006-03-30 12:59:11 +0000609
Georg Brandl96c3f7f2006-03-28 08:06:35 +0000610 for sym, lop, rop in oplist:
Raymond Hettinger267b8682005-03-27 10:47:39 +0000611 setattr(E, lop, lambda self, other: 'str' + lop + str(other))
612 setattr(E, rop, lambda self, other: str(other) + rop + 'str')
613 self.assertEqual(eval('E()' + sym + 'Decimal(10)'),
614 'str' + lop + '10')
615 self.assertEqual(eval('Decimal(10)' + sym + 'E()'),
616 '10' + rop + 'str')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000617
618class DecimalArithmeticOperatorsTest(unittest.TestCase):
619 '''Unit tests for all arithmetic operators, binary and unary.'''
620
621 def test_addition(self):
622
623 d1 = Decimal('-11.1')
624 d2 = Decimal('22.2')
625
626 #two Decimals
627 self.assertEqual(d1+d2, Decimal('11.1'))
628 self.assertEqual(d2+d1, Decimal('11.1'))
629
630 #with other type, left
631 c = d1 + 5
632 self.assertEqual(c, Decimal('-6.1'))
633 self.assertEqual(type(c), type(d1))
634
635 #with other type, right
636 c = 5 + d1
637 self.assertEqual(c, Decimal('-6.1'))
638 self.assertEqual(type(c), type(d1))
639
640 #inline with decimal
641 d1 += d2
642 self.assertEqual(d1, Decimal('11.1'))
643
644 #inline with other type
645 d1 += 5
646 self.assertEqual(d1, Decimal('16.1'))
647
648 def test_subtraction(self):
649
650 d1 = Decimal('-11.1')
651 d2 = Decimal('22.2')
652
653 #two Decimals
654 self.assertEqual(d1-d2, Decimal('-33.3'))
655 self.assertEqual(d2-d1, Decimal('33.3'))
656
657 #with other type, left
658 c = d1 - 5
659 self.assertEqual(c, Decimal('-16.1'))
660 self.assertEqual(type(c), type(d1))
661
662 #with other type, right
663 c = 5 - d1
664 self.assertEqual(c, Decimal('16.1'))
665 self.assertEqual(type(c), type(d1))
666
667 #inline with decimal
668 d1 -= d2
669 self.assertEqual(d1, Decimal('-33.3'))
670
671 #inline with other type
672 d1 -= 5
673 self.assertEqual(d1, Decimal('-38.3'))
674
675 def test_multiplication(self):
676
677 d1 = Decimal('-5')
678 d2 = Decimal('3')
679
680 #two Decimals
681 self.assertEqual(d1*d2, Decimal('-15'))
682 self.assertEqual(d2*d1, Decimal('-15'))
683
684 #with other type, left
685 c = d1 * 5
686 self.assertEqual(c, Decimal('-25'))
687 self.assertEqual(type(c), type(d1))
688
689 #with other type, right
690 c = 5 * d1
691 self.assertEqual(c, Decimal('-25'))
692 self.assertEqual(type(c), type(d1))
693
694 #inline with decimal
695 d1 *= d2
696 self.assertEqual(d1, Decimal('-15'))
697
698 #inline with other type
699 d1 *= 5
700 self.assertEqual(d1, Decimal('-75'))
701
702 def test_division(self):
703
704 d1 = Decimal('-5')
705 d2 = Decimal('2')
706
707 #two Decimals
708 self.assertEqual(d1/d2, Decimal('-2.5'))
709 self.assertEqual(d2/d1, Decimal('-0.4'))
710
711 #with other type, left
712 c = d1 / 4
713 self.assertEqual(c, Decimal('-1.25'))
714 self.assertEqual(type(c), type(d1))
715
716 #with other type, right
717 c = 4 / d1
718 self.assertEqual(c, Decimal('-0.8'))
719 self.assertEqual(type(c), type(d1))
720
721 #inline with decimal
722 d1 /= d2
723 self.assertEqual(d1, Decimal('-2.5'))
724
725 #inline with other type
726 d1 /= 4
727 self.assertEqual(d1, Decimal('-0.625'))
728
729 def test_floor_division(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000730
731 d1 = Decimal('5')
732 d2 = Decimal('2')
733
734 #two Decimals
735 self.assertEqual(d1//d2, Decimal('2'))
736 self.assertEqual(d2//d1, Decimal('0'))
737
738 #with other type, left
739 c = d1 // 4
740 self.assertEqual(c, Decimal('1'))
741 self.assertEqual(type(c), type(d1))
742
743 #with other type, right
744 c = 7 // d1
745 self.assertEqual(c, Decimal('1'))
746 self.assertEqual(type(c), type(d1))
747
748 #inline with decimal
749 d1 //= d2
750 self.assertEqual(d1, Decimal('2'))
751
752 #inline with other type
753 d1 //= 2
754 self.assertEqual(d1, Decimal('1'))
755
756 def test_powering(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757
758 d1 = Decimal('5')
759 d2 = Decimal('2')
760
761 #two Decimals
762 self.assertEqual(d1**d2, Decimal('25'))
763 self.assertEqual(d2**d1, Decimal('32'))
764
765 #with other type, left
766 c = d1 ** 4
767 self.assertEqual(c, Decimal('625'))
768 self.assertEqual(type(c), type(d1))
769
770 #with other type, right
771 c = 7 ** d1
772 self.assertEqual(c, Decimal('16807'))
773 self.assertEqual(type(c), type(d1))
774
775 #inline with decimal
776 d1 **= d2
777 self.assertEqual(d1, Decimal('25'))
778
779 #inline with other type
780 d1 **= 4
781 self.assertEqual(d1, Decimal('390625'))
782
783 def test_module(self):
784
785 d1 = Decimal('5')
786 d2 = Decimal('2')
787
788 #two Decimals
789 self.assertEqual(d1%d2, Decimal('1'))
790 self.assertEqual(d2%d1, Decimal('2'))
791
792 #with other type, left
793 c = d1 % 4
794 self.assertEqual(c, Decimal('1'))
795 self.assertEqual(type(c), type(d1))
796
797 #with other type, right
798 c = 7 % d1
799 self.assertEqual(c, Decimal('2'))
800 self.assertEqual(type(c), type(d1))
801
802 #inline with decimal
803 d1 %= d2
804 self.assertEqual(d1, Decimal('1'))
805
806 #inline with other type
807 d1 %= 4
808 self.assertEqual(d1, Decimal('1'))
809
810 def test_floor_div_module(self):
811
812 d1 = Decimal('5')
813 d2 = Decimal('2')
814
815 #two Decimals
816 (p, q) = divmod(d1, d2)
817 self.assertEqual(p, Decimal('2'))
818 self.assertEqual(q, Decimal('1'))
819 self.assertEqual(type(p), type(d1))
820 self.assertEqual(type(q), type(d1))
821
822 #with other type, left
823 (p, q) = divmod(d1, 4)
824 self.assertEqual(p, Decimal('1'))
825 self.assertEqual(q, Decimal('1'))
826 self.assertEqual(type(p), type(d1))
827 self.assertEqual(type(q), type(d1))
828
829 #with other type, right
830 (p, q) = divmod(7, d1)
831 self.assertEqual(p, Decimal('1'))
832 self.assertEqual(q, Decimal('2'))
833 self.assertEqual(type(p), type(d1))
834 self.assertEqual(type(q), type(d1))
835
836 def test_unary_operators(self):
837 self.assertEqual(+Decimal(45), Decimal(+45)) # +
838 self.assertEqual(-Decimal(45), Decimal(-45)) # -
839 self.assertEqual(abs(Decimal(45)), abs(Decimal(-45))) # abs
840
841
842# The following are two functions used to test threading in the next class
843
844def thfunc1(cls):
845 d1 = Decimal(1)
846 d3 = Decimal(3)
847 cls.assertEqual(d1/d3, Decimal('0.333333333'))
848 cls.synchro.wait()
849 cls.assertEqual(d1/d3, Decimal('0.333333333'))
850 cls.finish1.set()
851 return
852
853def thfunc2(cls):
854 d1 = Decimal(1)
855 d3 = Decimal(3)
856 cls.assertEqual(d1/d3, Decimal('0.333333333'))
857 thiscontext = getcontext()
858 thiscontext.prec = 18
859 cls.assertEqual(d1/d3, Decimal('0.333333333333333333'))
860 cls.synchro.set()
861 cls.finish2.set()
862 return
863
864
865class DecimalUseOfContextTest(unittest.TestCase):
866 '''Unit tests for Use of Context cases in Decimal.'''
867
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000868 try:
869 import threading
870 except ImportError:
871 threading = None
872
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873 # Take care executing this test from IDLE, there's an issue in threading
874 # that hangs IDLE and I couldn't find it
875
876 def test_threading(self):
877 #Test the "threading isolation" of a Context.
878
879 self.synchro = threading.Event()
880 self.finish1 = threading.Event()
881 self.finish2 = threading.Event()
882
883 th1 = threading.Thread(target=thfunc1, args=(self,))
884 th2 = threading.Thread(target=thfunc2, args=(self,))
885
886 th1.start()
887 th2.start()
888
889 self.finish1.wait()
Thomas Woutersb3e6e8c2007-09-19 17:27:29 +0000890 self.finish2.wait()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000891 return
892
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000893 if threading is None:
894 del test_threading
895
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000896
897class DecimalUsabilityTest(unittest.TestCase):
898 '''Unit tests for Usability cases of Decimal.'''
899
900 def test_comparison_operators(self):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000901
902 da = Decimal('23.42')
903 db = Decimal('23.42')
904 dc = Decimal('45')
905
906 #two Decimals
907 self.failUnless(dc > da)
908 self.failUnless(dc >= da)
909 self.failUnless(da < dc)
910 self.failUnless(da <= dc)
911 self.failUnless(da == db)
912 self.failUnless(da != dc)
913 self.failUnless(da <= db)
914 self.failUnless(da >= db)
915 self.assertEqual(cmp(dc,da), 1)
916 self.assertEqual(cmp(da,dc), -1)
917 self.assertEqual(cmp(da,db), 0)
918
919 #a Decimal and an int
920 self.failUnless(dc > 23)
921 self.failUnless(23 < dc)
922 self.failUnless(dc == 45)
923 self.assertEqual(cmp(dc,23), 1)
924 self.assertEqual(cmp(23,dc), -1)
925 self.assertEqual(cmp(dc,45), 0)
926
927 #a Decimal and uncomparable
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000928 self.assertNotEqual(da, 'ugly')
929 self.assertNotEqual(da, 32.7)
930 self.assertNotEqual(da, object())
931 self.assertNotEqual(da, object)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000933 # sortable
934 a = map(Decimal, xrange(100))
935 b = a[:]
936 random.shuffle(a)
937 a.sort()
938 self.assertEqual(a, b)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939
Facundo Batista353750c2007-09-13 18:13:15 +0000940 # with None
941 self.assertFalse(Decimal(1) < None)
942 self.assertTrue(Decimal(1) > None)
943
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944 def test_copy_and_deepcopy_methods(self):
945 d = Decimal('43.24')
946 c = copy.copy(d)
947 self.assertEqual(id(c), id(d))
948 dc = copy.deepcopy(d)
949 self.assertEqual(id(dc), id(d))
950
951 def test_hash_method(self):
952 #just that it's hashable
953 hash(Decimal(23))
Facundo Batista8c202442007-09-19 17:53:25 +0000954
955 test_values = [Decimal(sign*(2**m + n))
956 for m in [0, 14, 15, 16, 17, 30, 31,
957 32, 33, 62, 63, 64, 65, 66]
958 for n in range(-10, 10)
959 for sign in [-1, 1]]
960 test_values.extend([
961 Decimal("-0"), # zeros
962 Decimal("0.00"),
963 Decimal("-0.000"),
964 Decimal("0E10"),
965 Decimal("-0E12"),
966 Decimal("10.0"), # negative exponent
967 Decimal("-23.00000"),
968 Decimal("1230E100"), # positive exponent
969 Decimal("-4.5678E50"),
970 # a value for which hash(n) != hash(n % (2**64-1))
971 # in Python pre-2.6
972 Decimal(2**64 + 2**32 - 1),
973 # selection of values which fail with the old (before
974 # version 2.6) long.__hash__
975 Decimal("1.634E100"),
976 Decimal("90.697E100"),
977 Decimal("188.83E100"),
978 Decimal("1652.9E100"),
979 Decimal("56531E100"),
980 ])
981
982 # check that hash(d) == hash(int(d)) for integral values
983 for value in test_values:
984 self.assertEqual(hash(value), hash(int(value)))
985
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000986 #the same hash that to an int
987 self.assertEqual(hash(Decimal(23)), hash(23))
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000988 self.assertRaises(TypeError, hash, Decimal('NaN'))
989 self.assert_(hash(Decimal('Inf')))
990 self.assert_(hash(Decimal('-Inf')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
Facundo Batista52b25792008-01-08 12:25:20 +0000992 # check that the value of the hash doesn't depend on the
993 # current context (issue #1757)
994 c = getcontext()
995 old_precision = c.prec
996 x = Decimal("123456789.1")
997
998 c.prec = 6
999 h1 = hash(x)
1000 c.prec = 10
1001 h2 = hash(x)
1002 c.prec = 16
1003 h3 = hash(x)
1004
1005 self.assertEqual(h1, h2)
1006 self.assertEqual(h1, h3)
1007 c.prec = old_precision
1008
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009 def test_min_and_max_methods(self):
1010
1011 d1 = Decimal('15.32')
1012 d2 = Decimal('28.5')
1013 l1 = 15
1014 l2 = 28
1015
1016 #between Decimals
1017 self.failUnless(min(d1,d2) is d1)
1018 self.failUnless(min(d2,d1) is d1)
1019 self.failUnless(max(d1,d2) is d2)
1020 self.failUnless(max(d2,d1) is d2)
1021
1022 #between Decimal and long
1023 self.failUnless(min(d1,l2) is d1)
1024 self.failUnless(min(l2,d1) is d1)
1025 self.failUnless(max(l1,d2) is d2)
1026 self.failUnless(max(d2,l1) is d2)
1027
1028 def test_as_nonzero(self):
1029 #as false
1030 self.failIf(Decimal(0))
1031 #as true
1032 self.failUnless(Decimal('0.372'))
1033
1034 def test_tostring_methods(self):
1035 #Test str and repr methods.
1036
1037 d = Decimal('15.32')
1038 self.assertEqual(str(d), '15.32') # str
1039 self.assertEqual(repr(d), 'Decimal("15.32")') # repr
1040
1041 def test_tonum_methods(self):
1042 #Test float, int and long methods.
1043
1044 d1 = Decimal('66')
1045 d2 = Decimal('15.32')
1046
1047 #int
1048 self.assertEqual(int(d1), 66)
1049 self.assertEqual(int(d2), 15)
1050
1051 #long
1052 self.assertEqual(long(d1), 66)
1053 self.assertEqual(long(d2), 15)
1054
1055 #float
1056 self.assertEqual(float(d1), 66)
1057 self.assertEqual(float(d2), 15.32)
1058
1059 def test_eval_round_trip(self):
1060
1061 #with zero
1062 d = Decimal( (0, (0,), 0) )
1063 self.assertEqual(d, eval(repr(d)))
1064
1065 #int
1066 d = Decimal( (1, (4, 5), 0) )
1067 self.assertEqual(d, eval(repr(d)))
1068
1069 #float
1070 d = Decimal( (0, (4, 5, 3, 4), -2) )
1071 self.assertEqual(d, eval(repr(d)))
1072
1073 #weird
1074 d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
1075 self.assertEqual(d, eval(repr(d)))
1076
1077 def test_as_tuple(self):
1078
1079 #with zero
1080 d = Decimal(0)
1081 self.assertEqual(d.as_tuple(), (0, (0,), 0) )
1082
1083 #int
1084 d = Decimal(-45)
1085 self.assertEqual(d.as_tuple(), (1, (4, 5), 0) )
1086
1087 #complicated string
1088 d = Decimal("-4.34913534E-17")
1089 self.assertEqual(d.as_tuple(), (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
1090
1091 #inf
1092 d = Decimal("Infinity")
1093 self.assertEqual(d.as_tuple(), (0, (0,), 'F') )
1094
Facundo Batista9b5e2312007-10-19 19:25:57 +00001095 #leading zeros in coefficient should be stripped
1096 d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), -2) )
1097 self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), -2) )
1098 d = Decimal( (1, (0, 0, 0), 37) )
1099 self.assertEqual(d.as_tuple(), (1, (0,), 37))
1100 d = Decimal( (1, (), 37) )
1101 self.assertEqual(d.as_tuple(), (1, (0,), 37))
1102
1103 #leading zeros in NaN diagnostic info should be stripped
1104 d = Decimal( (0, (0, 0, 4, 0, 5, 3, 4), 'n') )
1105 self.assertEqual(d.as_tuple(), (0, (4, 0, 5, 3, 4), 'n') )
1106 d = Decimal( (1, (0, 0, 0), 'N') )
1107 self.assertEqual(d.as_tuple(), (1, (), 'N') )
1108 d = Decimal( (1, (), 'n') )
1109 self.assertEqual(d.as_tuple(), (1, (), 'n') )
1110
1111 #coefficient in infinity should be ignored
1112 d = Decimal( (0, (4, 5, 3, 4), 'F') )
1113 self.assertEqual(d.as_tuple(), (0, (0,), 'F'))
1114 d = Decimal( (1, (0, 2, 7, 1), 'F') )
1115 self.assertEqual(d.as_tuple(), (1, (0,), 'F'))
1116
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117 def test_immutability_operations(self):
1118 # Do operations and check that it didn't change change internal objects.
1119
1120 d1 = Decimal('-25e55')
1121 b1 = Decimal('-25e55')
Facundo Batista353750c2007-09-13 18:13:15 +00001122 d2 = Decimal('33e+33')
1123 b2 = Decimal('33e+33')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124
1125 def checkSameDec(operation, useOther=False):
1126 if useOther:
1127 eval("d1." + operation + "(d2)")
1128 self.assertEqual(d1._sign, b1._sign)
1129 self.assertEqual(d1._int, b1._int)
1130 self.assertEqual(d1._exp, b1._exp)
1131 self.assertEqual(d2._sign, b2._sign)
1132 self.assertEqual(d2._int, b2._int)
1133 self.assertEqual(d2._exp, b2._exp)
1134 else:
1135 eval("d1." + operation + "()")
1136 self.assertEqual(d1._sign, b1._sign)
1137 self.assertEqual(d1._int, b1._int)
1138 self.assertEqual(d1._exp, b1._exp)
1139 return
1140
1141 Decimal(d1)
1142 self.assertEqual(d1._sign, b1._sign)
1143 self.assertEqual(d1._int, b1._int)
1144 self.assertEqual(d1._exp, b1._exp)
1145
1146 checkSameDec("__abs__")
1147 checkSameDec("__add__", True)
1148 checkSameDec("__div__", True)
1149 checkSameDec("__divmod__", True)
1150 checkSameDec("__cmp__", True)
1151 checkSameDec("__float__")
1152 checkSameDec("__floordiv__", True)
1153 checkSameDec("__hash__")
1154 checkSameDec("__int__")
Raymond Hettinger5a053642008-01-24 19:05:29 +00001155 checkSameDec("__trunc__")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 checkSameDec("__long__")
1157 checkSameDec("__mod__", True)
1158 checkSameDec("__mul__", True)
1159 checkSameDec("__neg__")
1160 checkSameDec("__nonzero__")
1161 checkSameDec("__pos__")
1162 checkSameDec("__pow__", True)
1163 checkSameDec("__radd__", True)
1164 checkSameDec("__rdiv__", True)
1165 checkSameDec("__rdivmod__", True)
1166 checkSameDec("__repr__")
1167 checkSameDec("__rfloordiv__", True)
1168 checkSameDec("__rmod__", True)
1169 checkSameDec("__rmul__", True)
1170 checkSameDec("__rpow__", True)
1171 checkSameDec("__rsub__", True)
1172 checkSameDec("__str__")
1173 checkSameDec("__sub__", True)
1174 checkSameDec("__truediv__", True)
1175 checkSameDec("adjusted")
1176 checkSameDec("as_tuple")
1177 checkSameDec("compare", True)
1178 checkSameDec("max", True)
1179 checkSameDec("min", True)
1180 checkSameDec("normalize")
1181 checkSameDec("quantize", True)
1182 checkSameDec("remainder_near", True)
1183 checkSameDec("same_quantum", True)
1184 checkSameDec("sqrt")
1185 checkSameDec("to_eng_string")
1186 checkSameDec("to_integral")
1187
Facundo Batista6c398da2007-09-17 17:30:13 +00001188 def test_subclassing(self):
1189 # Different behaviours when subclassing Decimal
1190
1191 class MyDecimal(Decimal):
1192 pass
1193
1194 d1 = MyDecimal(1)
1195 d2 = MyDecimal(2)
1196 d = d1 + d2
1197 self.assertTrue(type(d) is Decimal)
1198
1199 d = d1.max(d2)
1200 self.assertTrue(type(d) is Decimal)
1201
1202
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001203class DecimalPythonAPItests(unittest.TestCase):
1204
1205 def test_pickle(self):
1206 d = Decimal('-3.141590000')
1207 p = pickle.dumps(d)
1208 e = pickle.loads(p)
1209 self.assertEqual(d, e)
1210
Raymond Hettinger5548be22004-07-05 18:49:38 +00001211 def test_int(self):
Raymond Hettinger605ed022004-11-24 07:28:48 +00001212 for x in range(-250, 250):
1213 s = '%0.2f' % (x / 100.0)
Raymond Hettinger5548be22004-07-05 18:49:38 +00001214 # should work the same as for floats
1215 self.assertEqual(int(Decimal(s)), int(float(s)))
Raymond Hettinger605ed022004-11-24 07:28:48 +00001216 # should work the same as to_integral in the ROUND_DOWN mode
Raymond Hettinger5548be22004-07-05 18:49:38 +00001217 d = Decimal(s)
Raymond Hettinger605ed022004-11-24 07:28:48 +00001218 r = d.to_integral(ROUND_DOWN)
Raymond Hettinger5548be22004-07-05 18:49:38 +00001219 self.assertEqual(Decimal(int(d)), r)
1220
Raymond Hettinger5a053642008-01-24 19:05:29 +00001221 def test_trunc(self):
1222 for x in range(-250, 250):
1223 s = '%0.2f' % (x / 100.0)
1224 # should work the same as for floats
1225 self.assertEqual(int(Decimal(s)), int(float(s)))
1226 # should work the same as to_integral in the ROUND_DOWN mode
1227 d = Decimal(s)
1228 r = d.to_integral(ROUND_DOWN)
Jeffrey Yasskinca2b69f2008-02-01 06:22:46 +00001229 self.assertEqual(Decimal(math.trunc(d)), r)
Raymond Hettinger5a053642008-01-24 19:05:29 +00001230
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00001231class ContextAPItests(unittest.TestCase):
1232
1233 def test_pickle(self):
1234 c = Context()
1235 e = pickle.loads(pickle.dumps(c))
1236 for k in vars(c):
1237 v1 = vars(c)[k]
1238 v2 = vars(e)[k]
1239 self.assertEqual(v1, v2)
1240
Raymond Hettinger0aeac102004-07-05 22:53:03 +00001241 def test_equality_with_other_types(self):
1242 self.assert_(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}])
1243 self.assert_(Decimal(10) not in ['a', 1.0, (1,2), {}])
1244
Raymond Hettinger955d2b22004-08-08 20:17:45 +00001245 def test_copy(self):
1246 # All copies should be deep
1247 c = Context()
1248 d = c.copy()
1249 self.assertNotEqual(id(c), id(d))
1250 self.assertNotEqual(id(c.flags), id(d.flags))
1251 self.assertNotEqual(id(c.traps), id(d.traps))
1252
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001253class WithStatementTest(unittest.TestCase):
1254 # Can't do these as docstrings until Python 2.6
1255 # as doctest can't handle __future__ statements
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001256
1257 def test_localcontext(self):
Nick Coghlanced12182006-09-02 03:54:17 +00001258 # Use a copy of the current context in the block
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001259 orig_ctx = getcontext()
1260 with localcontext() as enter_ctx:
1261 set_ctx = getcontext()
1262 final_ctx = getcontext()
1263 self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
1264 self.assert_(orig_ctx is not set_ctx, 'did not copy the context')
1265 self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
1266
1267 def test_localcontextarg(self):
Nick Coghlanced12182006-09-02 03:54:17 +00001268 # Use a copy of the supplied context in the block
Nick Coghlan8b6999b2006-08-31 12:00:43 +00001269 orig_ctx = getcontext()
1270 new_ctx = Context(prec=42)
1271 with localcontext(new_ctx) as enter_ctx:
1272 set_ctx = getcontext()
1273 final_ctx = getcontext()
1274 self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
1275 self.assert_(set_ctx.prec == new_ctx.prec, 'did not set correct context')
1276 self.assert_(new_ctx is not set_ctx, 'did not copy the context')
1277 self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
1278
Facundo Batista353750c2007-09-13 18:13:15 +00001279class ContextFlags(unittest.TestCase):
1280 def test_flags_irrelevant(self):
1281 # check that the result (numeric result + flags raised) of an
1282 # arithmetic operation doesn't depend on the current flags
1283
1284 context = Context(prec=9, Emin = -999999999, Emax = 999999999,
1285 rounding=ROUND_HALF_EVEN, traps=[], flags=[])
1286
1287 # operations that raise various flags, in the form (function, arglist)
1288 operations = [
1289 (context._apply, [Decimal("100E-1000000009")]),
1290 (context.sqrt, [Decimal(2)]),
1291 (context.add, [Decimal("1.23456789"), Decimal("9.87654321")]),
1292 (context.multiply, [Decimal("1.23456789"), Decimal("9.87654321")]),
1293 (context.subtract, [Decimal("1.23456789"), Decimal("9.87654321")]),
1294 ]
1295
1296 # try various flags individually, then a whole lot at once
1297 flagsets = [[Inexact], [Rounded], [Underflow], [Clamped], [Subnormal],
1298 [Inexact, Rounded, Underflow, Clamped, Subnormal]]
1299
1300 for fn, args in operations:
1301 # find answer and flags raised using a clean context
1302 context.clear_flags()
1303 ans = fn(*args)
1304 flags = [k for k, v in context.flags.items() if v]
1305
1306 for extra_flags in flagsets:
1307 # set flags, before calling operation
1308 context.clear_flags()
1309 for flag in extra_flags:
1310 context._raise_error(flag)
1311 new_ans = fn(*args)
1312
1313 # flags that we expect to be set after the operation
1314 expected_flags = list(flags)
1315 for flag in extra_flags:
1316 if flag not in expected_flags:
1317 expected_flags.append(flag)
1318 expected_flags.sort()
1319
1320 # flags we actually got
1321 new_flags = [k for k,v in context.flags.items() if v]
1322 new_flags.sort()
1323
1324 self.assertEqual(ans, new_ans,
1325 "operation produces different answers depending on flags set: " +
1326 "expected %s, got %s." % (ans, new_ans))
1327 self.assertEqual(new_flags, expected_flags,
1328 "operation raises different flags depending on flags set: " +
1329 "expected %s, got %s" % (expected_flags, new_flags))
1330
1331def test_main(arith=False, verbose=None, todo_tests=None, debug=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001332 """ Execute the tests.
1333
Raymond Hettingered20ad82004-09-04 20:09:13 +00001334 Runs all arithmetic tests if arith is True or if the "decimal" resource
1335 is enabled in regrtest.py
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001336 """
Raymond Hettingered20ad82004-09-04 20:09:13 +00001337
Neal Norwitzce4a9c92006-04-09 08:36:46 +00001338 init()
Facundo Batista353750c2007-09-13 18:13:15 +00001339 global TEST_ALL, DEBUG
Raymond Hettingered20ad82004-09-04 20:09:13 +00001340 TEST_ALL = arith or is_resource_enabled('decimal')
Facundo Batista353750c2007-09-13 18:13:15 +00001341 DEBUG = debug
Raymond Hettingered20ad82004-09-04 20:09:13 +00001342
Facundo Batista353750c2007-09-13 18:13:15 +00001343 if todo_tests is None:
1344 test_classes = [
1345 DecimalExplicitConstructionTest,
1346 DecimalImplicitConstructionTest,
1347 DecimalArithmeticOperatorsTest,
1348 DecimalUseOfContextTest,
1349 DecimalUsabilityTest,
1350 DecimalPythonAPItests,
1351 ContextAPItests,
1352 DecimalTest,
1353 WithStatementTest,
1354 ContextFlags
1355 ]
1356 else:
1357 test_classes = [DecimalTest]
1358
1359 # Dynamically build custom test definition for each file in the test
1360 # directory and add the definitions to the DecimalTest class. This
1361 # procedure insures that new files do not get skipped.
1362 for filename in os.listdir(directory):
1363 if '.decTest' not in filename or filename.startswith("."):
1364 continue
1365 head, tail = filename.split('.')
1366 if todo_tests is not None and head not in todo_tests:
1367 continue
1368 tester = lambda self, f=filename: self.eval_file(directory + f)
1369 setattr(DecimalTest, 'test_' + head, tester)
1370 del filename, head, tail, tester
1371
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Tim Peters46cc7022006-03-31 04:11:16 +00001373 try:
1374 run_unittest(*test_classes)
Facundo Batista353750c2007-09-13 18:13:15 +00001375 if todo_tests is None:
1376 import decimal as DecimalModule
1377 run_doctest(DecimalModule, verbose)
Tim Peters46cc7022006-03-31 04:11:16 +00001378 finally:
1379 setcontext(ORIGINAL_CONTEXT)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001380
1381if __name__ == '__main__':
Facundo Batista353750c2007-09-13 18:13:15 +00001382 import optparse
1383 p = optparse.OptionParser("test_decimal.py [--debug] [{--skip | test1 [test2 [...]]}]")
1384 p.add_option('--debug', '-d', action='store_true', help='shows the test number and context before each test')
1385 p.add_option('--skip', '-s', action='store_true', help='skip over 90% of the arithmetic tests')
1386 (opt, args) = p.parse_args()
1387
1388 if opt.skip:
1389 test_main(arith=False, verbose=True)
1390 elif args:
1391 test_main(arith=True, verbose=True, todo_tests=args, debug=opt.debug)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001392 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001393 test_main(arith=True, verbose=True)