0001 ''' 0002 Tests for fpformat module 0003 Nick Mathewson 0004 ''' 0005 from test.test_support import run_unittest 0006 import unittest 0007 from fpformat import fix, sci, NotANumber 0008 0009 StringType = type('') 0010 0011 # Test the old and obsolescent fpformat module. 0012 # 0013 # (It's obsolescent because fix(n,d) == "%.*f"%(d,n) and 0014 # sci(n,d) == "%.*e"%(d,n) 0015 # for all reasonable numeric n and d, except that sci gives 3 exponent 0016 # digits instead of 2. 0017 # 0018 # Differences only occur for unreasonable n and d. <.2 wink>) 0019 0020 class FpformatTest(unittest.TestCase): 0021 0022 def checkFix(self, n, digits): 0023 result = fix(n, digits) 0024 if isinstance(n, StringType): 0025 n = repr(n) 0026 expected = "%.*f" % (digits, float(n)) 0027 0028 self.assertEquals(result, expected) 0029 0030 def checkSci(self, n, digits): 0031 result = sci(n, digits) 0032 if isinstance(n, StringType): 0033 n = repr(n) 0034 expected = "%.*e" % (digits, float(n)) 0035 # add the extra 0 if needed 0036 num, exp = expected.split("e") 0037 if len(exp) < 4: 0038 exp = exp[0] + "0" + exp[1:] 0039 expected = "%se%s" % (num, exp) 0040 0041 self.assertEquals(result, expected) 0042 0043 def test_basic_cases(self): 0044 self.assertEquals(fix(100.0/3, 3), '33.333') 0045 self.assertEquals(sci(100.0/3, 3), '3.333e+001') 0046 0047 def test_reasonable_values(self): 0048 for d in range(7): 0049 for val in (1000.0/3, 1000, 1000.0, .002, 1.0/3, 1e10): 0050 for realVal in (val, 1.0/val, -val, -1.0/val): 0051 self.checkFix(realVal, d) 0052 self.checkSci(realVal, d) 0053 0054 def test_failing_values(self): 0055 # Now for 'unreasonable n and d' 0056 self.assertEquals(fix(1.0, 1000), '1.'+('0'*1000)) 0057 self.assertEquals(sci("1"+('0'*1000), 0), '1e+1000') 0058 0059 # This behavior is inconsistent. sci raises an exception; fix doesn't. 0060 yacht = "Throatwobbler Mangrove" 0061 self.assertEquals(fix(yacht, 10), yacht) 0062 try: 0063 sci(yacht, 10) 0064 except NotANumber: 0065 pass 0066 else: 0067 self.fail("No exception on non-numeric sci") 0068 0069 0070 def test_main(): 0071 run_unittest(FpformatTest) 0072 0073 0074 if __name__ == "__main__": 0075 test_main() 0076
Generated by PyXR 0.9.4