| 1 |
''' |
| 2 |
Tests for fpformat module |
| 3 |
Nick Mathewson |
| 4 |
''' |
| 5 |
from test.test_support import run_unittest, import_module |
| 6 |
import unittest |
| 7 |
fpformat = import_module('fpformat', deprecated=True) |
| 8 |
fix, sci, NotANumber = fpformat.fix, fpformat.sci, fpformat.NotANumber |
| 9 |
|
| 10 |
StringType = type('') |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
class FpformatTest(unittest.TestCase): |
| 22 |
|
| 23 |
def checkFix(self, n, digits): |
| 24 |
result = fix(n, digits) |
| 25 |
if isinstance(n, StringType): |
| 26 |
n = repr(n) |
| 27 |
expected = "%.*f" % (digits, float(n)) |
| 28 |
|
| 29 |
self.assertEqual(result, expected) |
| 30 |
|
| 31 |
def checkSci(self, n, digits): |
| 32 |
result = sci(n, digits) |
| 33 |
if isinstance(n, StringType): |
| 34 |
n = repr(n) |
| 35 |
expected = "%.*e" % (digits, float(n)) |
| 36 |
|
| 37 |
num, exp = expected.split("e") |
| 38 |
if len(exp) < 4: |
| 39 |
exp = exp[0] + "0" + exp[1:] |
| 40 |
expected = "%se%s" % (num, exp) |
| 41 |
|
| 42 |
self.assertEqual(result, expected) |
| 43 |
|
| 44 |
def test_basic_cases(self): |
| 45 |
self.assertEqual(fix(100.0/3, 3), '33.333') |
| 46 |
self.assertEqual(sci(100.0/3, 3), '3.333e+001') |
| 47 |
|
| 48 |
def test_reasonable_values(self): |
| 49 |
for d in range(7): |
| 50 |
for val in (1000.0/3, 1000, 1000.0, .002, 1.0/3, 1e10): |
| 51 |
for realVal in (val, 1.0/val, -val, -1.0/val): |
| 52 |
self.checkFix(realVal, d) |
| 53 |
self.checkSci(realVal, d) |
| 54 |
|
| 55 |
def test_failing_values(self): |
| 56 |
|
| 57 |
self.assertEqual(fix(1.0, 1000), '1.'+('0'*1000)) |
| 58 |
self.assertEqual(sci("1"+('0'*1000), 0), '1e+1000') |
| 59 |
|
| 60 |
|
| 61 |
yacht = "Throatwobbler Mangrove" |
| 62 |
self.assertEqual(fix(yacht, 10), yacht) |
| 63 |
try: |
| 64 |
sci(yacht, 10) |
| 65 |
except NotANumber: |
| 66 |
pass |
| 67 |
else: |
| 68 |
self.fail("No exception on non-numeric sci") |
| 69 |
|
| 70 |
def test_REDOS(self): |
| 71 |
|
| 72 |
attack = '+0' + ('0' * 1000000) + '++' |
| 73 |
digs = 5 |
| 74 |
|
| 75 |
|
| 76 |
self.assertEqual(fpformat.fix(attack, digs), attack) |
| 77 |
|
| 78 |
with self.assertRaises(NotANumber): |
| 79 |
fpformat.sci(attack, digs) |
| 80 |
|
| 81 |
def test_main(): |
| 82 |
run_unittest(FpformatTest) |
| 83 |
|
| 84 |
|
| 85 |
if __name__ == "__main__": |
| 86 |
test_main() |