blob: 1314654657b69d11c9c4ea6c0ee82a5b2102d7c6 [file] [log] [blame]
Fred Drake15861362001-07-23 02:46:35 +00001'''
2 Tests for fpformat module
3 Nick Mathewson
4'''
5from test_support import run_unittest
6import unittest
7from fpformat import fix, sci, NotANumber
8
9StringType = type('')
10
11# Test the old and obsolescent fpformat module.
12#
13# (It's obsolescent because fix(n,d) == "%.*f"%(d,n) and
14# sci(n,d) == "%.*e"%(d,n)
15# for all reasonable numeric n and d, except that sci gives 3 exponent
16# digits instead of 2.
17#
18# Differences only occur for unreasonable n and d. <.2 wink>)
19
20class FpformatTest(unittest.TestCase):
21
22 def checkFix(self, n, digits):
23 result = fix(n, digits)
24 if isinstance(n, StringType):
25 n = repr(n)
26 expected = "%.*f" % (digits, float(n))
27
28 self.assertEquals(result, expected)
29
30 def checkSci(self, n, digits):
31 result = sci(n, digits)
32 if isinstance(n, StringType):
33 n = repr(n)
34 expected = "%.*e" % (digits, float(n))
35 # add the extra 0
36 expected = expected[:-2]+'0'+expected[-2:]
37
38 self.assertEquals(result, expected)
39
40 def test_basic_cases(self):
41 self.assertEquals(fix(100.0/3, 3), '33.333')
42 self.assertEquals(sci(100.0/3, 3), '3.333e+001')
43
44 def test_reasonable_values(self):
45 for d in range(7):
46 for val in (1000.0/3, 1000, 1000.0, .002, 1.0/3, 1e10):
47 for realVal in (val, 1.0/val, -val, -1.0/val):
48 self.checkFix(realVal, d)
49 self.checkSci(realVal, d)
50
51 def test_failing_values(self):
52 # Now for 'unreasonable n and d'
53 self.assertEquals(fix(1.0, 1000), '1.'+('0'*1000))
54 self.assertEquals(sci("1"+('0'*1000), 0), '1e+1000')
55
56 # This behavior is inconsistent. sci raises an exception; fix doesn't.
57 yacht = "Throatwobbler Mangrove"
58 self.assertEquals(fix(yacht, 10), yacht)
59 try:
60 sci(yacht, 10)
61 except NotANumber:
62 pass
63 else:
64 self.fail("No exception on non-numeric sci")
65
66run_unittest(FpformatTest)
67