test_decimal.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import decimal
  2. from decimal import Decimal
  3. from unittest import TestCase
  4. from simplejson.compat import StringIO, reload_module
  5. import simplejson as json
  6. class TestDecimal(TestCase):
  7. NUMS = "1.0", "10.00", "1.1", "1234567890.1234567890", "500"
  8. def dumps(self, obj, **kw):
  9. sio = StringIO()
  10. json.dump(obj, sio, **kw)
  11. res = json.dumps(obj, **kw)
  12. self.assertEqual(res, sio.getvalue())
  13. return res
  14. def loads(self, s, **kw):
  15. sio = StringIO(s)
  16. res = json.loads(s, **kw)
  17. self.assertEqual(res, json.load(sio, **kw))
  18. return res
  19. def test_decimal_encode(self):
  20. for d in map(Decimal, self.NUMS):
  21. self.assertEqual(self.dumps(d, use_decimal=True), str(d))
  22. def test_decimal_decode(self):
  23. for s in self.NUMS:
  24. self.assertEqual(self.loads(s, parse_float=Decimal), Decimal(s))
  25. def test_stringify_key(self):
  26. for d in map(Decimal, self.NUMS):
  27. v = {d: d}
  28. self.assertEqual(
  29. self.loads(
  30. self.dumps(v, use_decimal=True), parse_float=Decimal),
  31. {str(d): d})
  32. def test_decimal_roundtrip(self):
  33. for d in map(Decimal, self.NUMS):
  34. # The type might not be the same (int and Decimal) but they
  35. # should still compare equal.
  36. for v in [d, [d], {'': d}]:
  37. self.assertEqual(
  38. self.loads(
  39. self.dumps(v, use_decimal=True), parse_float=Decimal),
  40. v)
  41. def test_decimal_defaults(self):
  42. d = Decimal('1.1')
  43. # use_decimal=True is the default
  44. self.assertRaises(TypeError, json.dumps, d, use_decimal=False)
  45. self.assertEqual('1.1', json.dumps(d))
  46. self.assertEqual('1.1', json.dumps(d, use_decimal=True))
  47. self.assertRaises(TypeError, json.dump, d, StringIO(),
  48. use_decimal=False)
  49. sio = StringIO()
  50. json.dump(d, sio)
  51. self.assertEqual('1.1', sio.getvalue())
  52. sio = StringIO()
  53. json.dump(d, sio, use_decimal=True)
  54. self.assertEqual('1.1', sio.getvalue())
  55. def test_decimal_reload(self):
  56. # Simulate a subinterpreter that reloads the Python modules but not
  57. # the C code https://github.com/simplejson/simplejson/issues/34
  58. global Decimal
  59. Decimal = reload_module(decimal).Decimal
  60. import simplejson.encoder
  61. simplejson.encoder.Decimal = Decimal
  62. self.test_decimal_roundtrip()