Update version number and release date.
[python/dscho.git] / Lib / test / test_fpformat.py
bloba1b872262a6609b17be909a822b38e3299459b45
1 '''
2 Tests for fpformat module
3 Nick Mathewson
4 '''
5 from test.test_support import run_unittest
6 import unittest
7 from fpformat import fix, sci, NotANumber
9 StringType = type('')
11 # Test the old and obsolescent fpformat module.
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.
18 # Differences only occur for unreasonable n and d. <.2 wink>)
20 class FpformatTest(unittest.TestCase):
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))
28 self.assertEquals(result, expected)
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 if needed
36 num, exp = expected.split("e")
37 if len(exp) < 4:
38 exp = exp[0] + "0" + exp[1:]
39 expected = "%se%s" % (num, exp)
41 self.assertEquals(result, expected)
43 def test_basic_cases(self):
44 self.assertEquals(fix(100.0/3, 3), '33.333')
45 self.assertEquals(sci(100.0/3, 3), '3.333e+001')
47 def test_reasonable_values(self):
48 for d in range(7):
49 for val in (1000.0/3, 1000, 1000.0, .002, 1.0/3, 1e10):
50 for realVal in (val, 1.0/val, -val, -1.0/val):
51 self.checkFix(realVal, d)
52 self.checkSci(realVal, d)
54 def test_failing_values(self):
55 # Now for 'unreasonable n and d'
56 self.assertEquals(fix(1.0, 1000), '1.'+('0'*1000))
57 self.assertEquals(sci("1"+('0'*1000), 0), '1e+1000')
59 # This behavior is inconsistent. sci raises an exception; fix doesn't.
60 yacht = "Throatwobbler Mangrove"
61 self.assertEquals(fix(yacht, 10), yacht)
62 try:
63 sci(yacht, 10)
64 except NotANumber:
65 pass
66 else:
67 self.fail("No exception on non-numeric sci")
70 def test_main():
71 run_unittest(FpformatTest)
74 if __name__ == "__main__":
75 test_main()