source: monitoring/plugins/mpi/simplejson/tests/test_decimal.py @ 2028

Last change on this file since 2028 was 2028, checked in by sanmai, 12 years ago
  • Add CLARIN Discojuice JSON monitoring plugin.
  • Add CLARIN Discojuice HTML monitoring plugin.
  • Add CLARIN SAML monitoring plugin.
  • LAT OAI-PMH endpoint monitoring plugin.
  • Add one dependency (SimpleJSON), for the time being, needed for Python 2.5.
File size: 2.3 KB
Line 
1import decimal
2from decimal import Decimal
3from unittest import TestCase
4from StringIO import StringIO
5
6import simplejson as json
7
8class TestDecimal(TestCase):
9    NUMS = "1.0", "10.00", "1.1", "1234567890.1234567890", "500"
10    def dumps(self, obj, **kw):
11        sio = StringIO()
12        json.dump(obj, sio, **kw)
13        res = json.dumps(obj, **kw)
14        self.assertEquals(res, sio.getvalue())
15        return res
16
17    def loads(self, s, **kw):
18        sio = StringIO(s)
19        res = json.loads(s, **kw)
20        self.assertEquals(res, json.load(sio, **kw))
21        return res
22
23    def test_decimal_encode(self):
24        for d in map(Decimal, self.NUMS):
25            self.assertEquals(self.dumps(d, use_decimal=True), str(d))
26
27    def test_decimal_decode(self):
28        for s in self.NUMS:
29            self.assertEquals(self.loads(s, parse_float=Decimal), Decimal(s))
30
31    def test_decimal_roundtrip(self):
32        for d in map(Decimal, self.NUMS):
33            # The type might not be the same (int and Decimal) but they
34            # should still compare equal.
35            self.assertEquals(
36                self.loads(
37                    self.dumps(d, use_decimal=True), parse_float=Decimal),
38                d)
39            self.assertEquals(
40                self.loads(
41                    self.dumps([d], use_decimal=True), parse_float=Decimal),
42                [d])
43
44    def test_decimal_defaults(self):
45        d = Decimal('1.1')
46        # use_decimal=True is the default
47        self.assertRaises(TypeError, json.dumps, d, use_decimal=False)
48        self.assertEqual('1.1', json.dumps(d))
49        self.assertEqual('1.1', json.dumps(d, use_decimal=True))
50        self.assertRaises(TypeError, json.dump, d, StringIO(),
51                          use_decimal=False)
52        sio = StringIO()
53        json.dump(d, sio)
54        self.assertEqual('1.1', sio.getvalue())
55        sio = StringIO()
56        json.dump(d, sio, use_decimal=True)
57        self.assertEqual('1.1', sio.getvalue())
58
59    def test_decimal_reload(self):
60        # Simulate a subinterpreter that reloads the Python modules but not
61        # the C code https://github.com/simplejson/simplejson/issues/34
62        global Decimal
63        Decimal = reload(decimal).Decimal
64        import simplejson.encoder
65        simplejson.encoder.Decimal = Decimal
66        self.test_decimal_roundtrip()
Note: See TracBrowser for help on using the repository browser.