def test_format_json(self): t1 = typed.dict({ 'a': typed.datetime.format('%Y-%m-%d %H:%M:%S').optional, 'b': (typed.string | typed.none).optional, 'c': typed.bool.format({True: 1, False: 0}).default(False), }) t2 = typed.dict({ 'd': typed.int, 'e': (typed.none | typed.date.format('%d/%m/%Y')).default(None), 'f': typed.list(typed.int), 'g': typed.json(t1).default(t1.load({})), }).format(typed.json) self.assertEqual(t2.load(json.dumps({'d': 1, 'f': []})), {'d': 1, 'e': None, 'f': [], 'g': {'c': False}}) self.assertEqual(t2.load(json.dumps({'d': 0, 'e': None, 'f': [1, 2], 'g': json.dumps({'b': None, 'c': 1})})), {'d': 0, 'e': None, 'f': [1, 2], 'g': {'b': None, 'c': True}}) self.assertEqual(t2.load(json.dumps({'d': 1, 'e': '15/02/2011', 'f': [], 'g': json.dumps({'a': '2013-11-11 16:16:16', 'b': 'foo', 'c': 0})})), {'d': 1, 'e': datetime.date(2011, 02, 15), 'f': [], 'g': {'a': datetime.datetime(2013, 11, 11, 16, 16, 16), 'b': 'foo', 'c': False}})
}).format(typed.json) self.assertEqual(t2.load(json.dumps({'d': 1, 'f': []})), {'d': 1, 'e': None, 'f': [], 'g': {'c': False}}) self.assertEqual(t2.load(json.dumps({'d': 0, 'e': None, 'f': [1, 2], 'g': json.dumps({'b': None, 'c': 1})})), {'d': 0, 'e': None, 'f': [1, 2], 'g': {'b': None, 'c': True}}) self.assertEqual(t2.load(json.dumps({'d': 1, 'e': '15/02/2011', 'f': [], 'g': json.dumps({'a': '2013-11-11 16:16:16', 'b': 'foo', 'c': 0})})), {'d': 1, 'e': datetime.date(2011, 02, 15), 'f': [], 'g': {'a': datetime.datetime(2013, 11, 11, 16, 16, 16), 'b': 'foo', 'c': False}}) self.assertEqual(t2.save({'d': 1, 'f': [1, 2, 3, 4]}), json.dumps({'d': 1, 'f': [1, 2, 3, 4]})) self.assertEqual(t2.save({'d': 1, 'e': None, 'f': [1, 2, 3, 4], 'g': {'c': False}}), json.dumps({'d': 1, 'f': [1, 2, 3, 4]})) self.assertEqual(t2.save({'d': 1, 'e': datetime.date(2013, 02, 15), 'f': [], 'g': {'a': datetime.datetime(2013, 10, 10, 05, 55, 50), 'b': None, 'c': True}}), json.dumps({'d': 1, 'e': '15/02/2013', 'f': [], 'g': json.dumps({'a': '2013-10-10 05:55:50', 'b': None, 'c': 1})})) if HAS_UJSON: t3 = typed.json(typed.dict({ 'a': typed.int, 'b': typed.float, 'c': typed.list(typed.float), 'd': typed.dict({ 'e': typed.list(typed.float), }), }), double_precision=4) obj = {'a': 1, 'b': 0.0123456789, 'c': [0.00001, 0.00011, 0.00026], 'd': {'e': [10000.098765432, 123456.01001]}} obj_json = '{"a": 1, "b": 0.0123, "c": [0.0, 0.0001, 0.0003], "d": {"e": [10000.0988, 123456.01]}}' self.assertItemsEqual(t3.save(obj)[2:-1].split(',"'), obj_json.replace(' ', '')[2:-1].split(',"')) # elements might come in different order def test_tuple(self): t1 = typed.tuple(typed.int, typed.datetime.format('%Y-%m-%d %H:%M:%S'), typed.string | typed.none) self.assertEqual(t1.load(tuple([4, '2013-10-11 11:02:45', 'foo'])), (4, datetime.datetime(2013, 10, 11, 11, 02, 45), 'foo')) self.assertEqual(t1.load(tuple([4, '2013-10-11 11:02:45', None])), (4, datetime.datetime(2013, 10, 11, 11, 02, 45), None))