1 | #!/bin/python |
---|
2 | # -*- coding: utf-8 -*- |
---|
3 | |
---|
4 | """ |
---|
5 | Unit tests for gluon.serializers |
---|
6 | """ |
---|
7 | |
---|
8 | import unittest |
---|
9 | from .fix_path import fix_sys_path |
---|
10 | import datetime |
---|
11 | import decimal |
---|
12 | |
---|
13 | from gluon.serializers import * |
---|
14 | from gluon.storage import Storage |
---|
15 | # careful with the import path 'cause of isinstance() checks |
---|
16 | from gluon.languages import TranslatorFactory |
---|
17 | from gluon.html import SPAN |
---|
18 | |
---|
19 | |
---|
20 | class TestSerializers(unittest.TestCase): |
---|
21 | |
---|
22 | def testJSON(self): |
---|
23 | # the main and documented "way" is to use the json() function |
---|
24 | # it has a few corner-cases that make json() be somewhat |
---|
25 | # different from the standard buyt being compliant |
---|
26 | # it's just a matter of conventions |
---|
27 | |
---|
28 | # incompatible spacing, newer simplejson already account |
---|
29 | # for this but it's still better to remember |
---|
30 | weird = {'JSON': u"ro" + u'\u2028' + u'ck' + u'\u2029' + u's!'} |
---|
31 | rtn = json(weird) |
---|
32 | self.assertEqual(rtn, u'{"JSON": "ro\\u2028ck\\u2029s!"}') |
---|
33 | # date, datetime, time strictly as strings in isoformat, minus the T |
---|
34 | objs = [ |
---|
35 | datetime.datetime(2014, 1, 1, 12, 15, 35), |
---|
36 | datetime.date(2014, 1, 1), |
---|
37 | datetime.time(12, 15, 35) |
---|
38 | ] |
---|
39 | iso_objs = [obj.isoformat()[:19].replace('T', ' ') for obj in objs] |
---|
40 | json_objs = [json(obj) for obj in objs] |
---|
41 | json_web2pyfied = [json(obj) for obj in iso_objs] |
---|
42 | self.assertEqual(json_objs, json_web2pyfied) |
---|
43 | # int or long int()ified |
---|
44 | # self.assertEqual(json(1), json(1)) |
---|
45 | # decimal stringified |
---|
46 | obj = {'a': decimal.Decimal('4.312312312312')} |
---|
47 | self.assertEqual(json(obj), u'{"a": 4.312312312312}') |
---|
48 | # lazyT translated |
---|
49 | T = TranslatorFactory('', 'en') |
---|
50 | lazy_translation = T('abc') |
---|
51 | self.assertEqual(json(lazy_translation), u'"abc"') |
---|
52 | # html helpers are xml()ed before too |
---|
53 | self.assertEqual(json(SPAN('abc'), cls=None), u'"<span>abc</span>"') |
---|
54 | self.assertEqual(json(SPAN('abc')), u'"\\u003cspan\\u003eabc\\u003c/span\\u003e"') |
---|
55 | # unicode keys make a difference with loads_json |
---|
56 | base = {u'è': 1, 'b': 2} |
---|
57 | base_enc = json(base) |
---|
58 | base_load = loads_json(base_enc) |
---|
59 | self.assertTrue(base == base_load) |
---|
60 | # if unicode_keys is false, the standard behaviour is assumed |
---|
61 | base_load = loads_json(base_enc, unicode_keys=False) |
---|
62 | self.assertFalse(base == base_load) |
---|