jcgregorio@wpgntai-ubiq72.hot.corp.google.com | ed13252 | 2010-04-19 11:12:52 -0700 | [diff] [blame^] | 1 | from decimal import Decimal |
| 2 | from unittest import TestCase |
| 3 | |
| 4 | import simplejson as json |
| 5 | |
| 6 | class TestDecimal(TestCase): |
| 7 | NUMS = "1.0", "10.00", "1.1", "1234567890.1234567890", "500" |
| 8 | def test_decimal_encode(self): |
| 9 | for d in map(Decimal, self.NUMS): |
| 10 | self.assertEquals(json.dumps(d, use_decimal=True), str(d)) |
| 11 | |
| 12 | def test_decimal_decode(self): |
| 13 | for s in self.NUMS: |
| 14 | self.assertEquals(json.loads(s, parse_float=Decimal), Decimal(s)) |
| 15 | |
| 16 | def test_decimal_roundtrip(self): |
| 17 | for d in map(Decimal, self.NUMS): |
| 18 | # The type might not be the same (int and Decimal) but they |
| 19 | # should still compare equal. |
| 20 | self.assertEquals( |
| 21 | json.loads( |
| 22 | json.dumps(d, use_decimal=True), parse_float=Decimal), |
| 23 | d) |
| 24 | self.assertEquals( |
| 25 | json.loads( |
| 26 | json.dumps([d], use_decimal=True), parse_float=Decimal), |
| 27 | [d]) |
| 28 | |
| 29 | def test_decimal_defaults(self): |
| 30 | d = Decimal(1) |
| 31 | # use_decimal=False is the default |
| 32 | self.assertRaises(TypeError, json.dumps, d, use_decimal=False) |
| 33 | self.assertRaises(TypeError, json.dumps, d) |