Fred Drake | 1586136 | 2001-07-23 02:46:35 +0000 | [diff] [blame] | 1 | ''' |
| 2 | Tests for fpformat module |
| 3 | Nick Mathewson |
| 4 | ''' |
| 5 | from test_support import run_unittest |
| 6 | import unittest |
| 7 | from fpformat import fix, sci, NotANumber |
| 8 | |
| 9 | StringType = type('') |
| 10 | |
| 11 | # Test the old and obsolescent fpformat module. |
| 12 | # |
Tim Peters | fa712ca | 2001-07-23 09:44:21 +0000 | [diff] [blame] | 13 | # (It's obsolescent because fix(n,d) == "%.*f"%(d,n) and |
Fred Drake | 1586136 | 2001-07-23 02:46:35 +0000 | [diff] [blame] | 14 | # sci(n,d) == "%.*e"%(d,n) |
Tim Peters | fa712ca | 2001-07-23 09:44:21 +0000 | [diff] [blame] | 15 | # for all reasonable numeric n and d, except that sci gives 3 exponent |
| 16 | # digits instead of 2. |
Fred Drake | 1586136 | 2001-07-23 02:46:35 +0000 | [diff] [blame] | 17 | # |
| 18 | # Differences only occur for unreasonable n and d. <.2 wink>) |
| 19 | |
| 20 | class 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)) |
Fred Drake | f973c6d | 2001-07-23 16:30:21 +0000 | [diff] [blame] | 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) |
Fred Drake | 1586136 | 2001-07-23 02:46:35 +0000 | [diff] [blame] | 40 | |
| 41 | self.assertEquals(result, expected) |
| 42 | |
| 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') |
| 46 | |
| 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) |
| 53 | |
| 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') |
| 58 | |
| 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") |
| 68 | |
Fred Drake | 2e2be37 | 2001-09-20 21:33:42 +0000 | [diff] [blame] | 69 | |
| 70 | def test_main(): |
| 71 | run_unittest(FpformatTest) |
| 72 | |
| 73 | |
| 74 | if __name__ == "__main__": |
| 75 | test_main() |