Changeset 391 for python/trunk/Lib/json/tests
- Timestamp:
- Mar 19, 2014, 11:31:01 PM (11 years ago)
- Location:
- python/trunk
- Files:
-
- 17 edited
- 2 copied
Legend:
- Unmodified
- Added
- Removed
-
python/trunk
-
Property svn:mergeinfo
set to
/python/vendor/Python-2.7.6 merged eligible /python/vendor/current merged eligible
-
Property svn:mergeinfo
set to
-
python/trunk/Lib/json/tests/__init__.py
r2 r391 1 1 import os 2 2 import sys 3 import json 4 import doctest 3 5 import unittest 4 import doctest 6 7 from test import test_support 8 9 # import json with and without accelerations 10 cjson = test_support.import_fresh_module('json', fresh=['_json']) 11 pyjson = test_support.import_fresh_module('json', blocked=['_json']) 12 13 # create two base classes that will be used by the other tests 14 class PyTest(unittest.TestCase): 15 json = pyjson 16 loads = staticmethod(pyjson.loads) 17 dumps = staticmethod(pyjson.dumps) 18 19 @unittest.skipUnless(cjson, 'requires _json') 20 class CTest(unittest.TestCase): 21 if cjson is not None: 22 json = cjson 23 loads = staticmethod(cjson.loads) 24 dumps = staticmethod(cjson.dumps) 25 26 # test PyTest and CTest checking if the functions come from the right module 27 class TestPyTest(PyTest): 28 def test_pyjson(self): 29 self.assertEqual(self.json.scanner.make_scanner.__module__, 30 'json.scanner') 31 self.assertEqual(self.json.decoder.scanstring.__module__, 32 'json.decoder') 33 self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__, 34 'json.encoder') 35 36 class TestCTest(CTest): 37 def test_cjson(self): 38 self.assertEqual(self.json.scanner.make_scanner.__module__, '_json') 39 self.assertEqual(self.json.decoder.scanstring.__module__, '_json') 40 self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json') 41 self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__, 42 '_json') 43 5 44 6 45 here = os.path.dirname(__file__) … … 18 57 19 58 def additional_tests(): 20 import json21 import json.encoder22 import json.decoder23 59 suite = unittest.TestSuite() 24 60 for mod in (json, json.encoder, json.decoder): 25 61 suite.addTest(doctest.DocTestSuite(mod)) 62 suite.addTest(TestPyTest('test_pyjson')) 63 suite.addTest(TestCTest('test_cjson')) 26 64 return suite 27 65 -
python/trunk/Lib/json/tests/test_decode.py
r2 r391 1 1 import decimal 2 from unittest import TestCase 2 from StringIO import StringIO 3 from collections import OrderedDict 4 from json.tests import PyTest, CTest 3 5 4 import json5 6 6 class TestDecode( TestCase):7 class TestDecode(object): 7 8 def test_decimal(self): 8 rval = json.loads('1.1', parse_float=decimal.Decimal)9 self.assert _(isinstance(rval, decimal.Decimal))10 self.assertEqual s(rval, decimal.Decimal('1.1'))9 rval = self.loads('1.1', parse_float=decimal.Decimal) 10 self.assertTrue(isinstance(rval, decimal.Decimal)) 11 self.assertEqual(rval, decimal.Decimal('1.1')) 11 12 12 13 def test_float(self): 13 rval = json.loads('1', parse_int=float) 14 self.assert_(isinstance(rval, float)) 15 self.assertEquals(rval, 1.0) 14 rval = self.loads('1', parse_int=float) 15 self.assertTrue(isinstance(rval, float)) 16 self.assertEqual(rval, 1.0) 17 18 def test_decoder_optimizations(self): 19 # Several optimizations were made that skip over calls to 20 # the whitespace regex, so this test is designed to try and 21 # exercise the uncommon cases. The array cases are already covered. 22 rval = self.loads('{ "key" : "value" , "k":"v" }') 23 self.assertEqual(rval, {"key":"value", "k":"v"}) 24 25 def test_empty_objects(self): 26 self.assertEqual(self.loads('{}'), {}) 27 self.assertEqual(self.loads('[]'), []) 28 self.assertEqual(self.loads('""'), u"") 29 self.assertIsInstance(self.loads('""'), unicode) 30 31 def test_object_pairs_hook(self): 32 s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' 33 p = [("xkd", 1), ("kcw", 2), ("art", 3), ("hxm", 4), 34 ("qrt", 5), ("pad", 6), ("hoy", 7)] 35 self.assertEqual(self.loads(s), eval(s)) 36 self.assertEqual(self.loads(s, object_pairs_hook=lambda x: x), p) 37 self.assertEqual(self.json.load(StringIO(s), 38 object_pairs_hook=lambda x: x), p) 39 od = self.loads(s, object_pairs_hook=OrderedDict) 40 self.assertEqual(od, OrderedDict(p)) 41 self.assertEqual(type(od), OrderedDict) 42 # the object_pairs_hook takes priority over the object_hook 43 self.assertEqual(self.loads(s, object_pairs_hook=OrderedDict, 44 object_hook=lambda x: None), 45 OrderedDict(p)) 46 # check that empty objects literals work (see #17368) 47 self.assertEqual(self.loads('{}', object_pairs_hook=OrderedDict), 48 OrderedDict()) 49 self.assertEqual(self.loads('{"empty": {}}', 50 object_pairs_hook=OrderedDict), 51 OrderedDict([('empty', OrderedDict())])) 52 53 def test_extra_data(self): 54 s = '[1, 2, 3]5' 55 msg = 'Extra data' 56 self.assertRaisesRegexp(ValueError, msg, self.loads, s) 57 58 def test_invalid_escape(self): 59 s = '["abc\\y"]' 60 msg = 'escape' 61 self.assertRaisesRegexp(ValueError, msg, self.loads, s) 62 63 class TestPyDecode(TestDecode, PyTest): pass 64 class TestCDecode(TestDecode, CTest): pass -
python/trunk/Lib/json/tests/test_default.py
r2 r391 1 from unittest import TestCase1 from json.tests import PyTest, CTest 2 2 3 import json4 3 5 class TestDefault( TestCase):4 class TestDefault(object): 6 5 def test_default(self): 7 self.assertEquals( 8 json.dumps(type, default=repr), 9 json.dumps(repr(type))) 6 self.assertEqual( 7 self.dumps(type, default=repr), 8 self.dumps(repr(type))) 9 10 11 class TestPyDefault(TestDefault, PyTest): pass 12 class TestCDefault(TestDefault, CTest): pass -
python/trunk/Lib/json/tests/test_dump.py
r2 r391 1 from unittest import TestCase2 1 from cStringIO import StringIO 2 from json.tests import PyTest, CTest 3 3 4 import json5 4 6 class TestDump( TestCase):5 class TestDump(object): 7 6 def test_dump(self): 8 7 sio = StringIO() 9 json.dump({}, sio)10 self.assertEqual s(sio.getvalue(), '{}')8 self.json.dump({}, sio) 9 self.assertEqual(sio.getvalue(), '{}') 11 10 12 11 def test_dumps(self): 13 self.assertEquals(json.dumps({}), '{}') 12 self.assertEqual(self.dumps({}), '{}') 13 14 def test_encode_truefalse(self): 15 self.assertEqual(self.dumps( 16 {True: False, False: True}, sort_keys=True), 17 '{"false": true, "true": false}') 18 self.assertEqual(self.dumps( 19 {2: 3.0, 4.0: 5L, False: 1, 6L: True}, sort_keys=True), 20 '{"false": 1, "2": 3.0, "4.0": 5, "6": true}') 21 22 # Issue 16228: Crash on encoding resized list 23 def test_encode_mutated(self): 24 a = [object()] * 10 25 def crasher(obj): 26 del a[-1] 27 self.assertEqual(self.dumps(a, default=crasher), 28 '[null, null, null, null, null]') 29 30 31 class TestPyDump(TestDump, PyTest): pass 32 class TestCDump(TestDump, CTest): pass -
python/trunk/Lib/json/tests/test_encode_basestring_ascii.py
r2 r391 1 from unittest import TestCase 1 from collections import OrderedDict 2 from json.tests import PyTest, CTest 2 3 3 import json.encoder4 4 5 5 CASES = [ … … 22 22 ] 23 23 24 class TestEncodeBaseStringAscii(TestCase): 25 def test_py_encode_basestring_ascii(self): 26 self._test_encode_basestring_ascii(json.encoder.py_encode_basestring_ascii) 24 class TestEncodeBasestringAscii(object): 25 def test_encode_basestring_ascii(self): 26 fname = self.json.encoder.encode_basestring_ascii.__name__ 27 for input_string, expect in CASES: 28 result = self.json.encoder.encode_basestring_ascii(input_string) 29 self.assertEqual(result, expect, 30 '{0!r} != {1!r} for {2}({3!r})'.format( 31 result, expect, fname, input_string)) 27 32 28 def test_c_encode_basestring_ascii(self): 29 self._test_encode_basestring_ascii(json.encoder.c_encode_basestring_ascii) 33 def test_ordered_dict(self): 34 # See issue 6105 35 items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)] 36 s = self.dumps(OrderedDict(items)) 37 self.assertEqual(s, '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}') 30 38 31 def _test_encode_basestring_ascii(self, encode_basestring_ascii): 32 fname = encode_basestring_ascii.__name__ 33 for input_string, expect in CASES: 34 result = encode_basestring_ascii(input_string) 35 self.assertEquals(result, expect) 39 40 class TestPyEncodeBasestringAscii(TestEncodeBasestringAscii, PyTest): pass 41 class TestCEncodeBasestringAscii(TestEncodeBasestringAscii, CTest): pass -
python/trunk/Lib/json/tests/test_fail.py
r2 r391 1 from unittest import TestCase1 from json.tests import PyTest, CTest 2 2 3 import json 4 5 # Fri Dec 30 18:57:26 2005 3 # 2007-10-05 6 4 JSONDOCS = [ 7 5 # http://json.org/JSON_checker/test/fail1.json … … 10 8 '["Unclosed array"', 11 9 # http://json.org/JSON_checker/test/fail3.json 12 '{unquoted_key: "keys must be quoted }',10 '{unquoted_key: "keys must be quoted"}', 13 11 # http://json.org/JSON_checker/test/fail4.json 14 12 '["extra comma",]', … … 36 34 '["Illegal backslash escape: \\x15"]', 37 35 # http://json.org/JSON_checker/test/fail16.json 38 '[ "Illegal backslash escape: \\\'"]',36 '[\\naked]', 39 37 # http://json.org/JSON_checker/test/fail17.json 40 38 '["Illegal backslash escape: \\017"]', … … 53 51 # http://json.org/JSON_checker/test/fail24.json 54 52 "['single quote']", 53 # http://json.org/JSON_checker/test/fail25.json 54 '["\ttab\tcharacter\tin\tstring\t"]', 55 # http://json.org/JSON_checker/test/fail26.json 56 '["tab\\ character\\ in\\ string\\ "]', 57 # http://json.org/JSON_checker/test/fail27.json 58 '["line\nbreak"]', 59 # http://json.org/JSON_checker/test/fail28.json 60 '["line\\\nbreak"]', 61 # http://json.org/JSON_checker/test/fail29.json 62 '[0e]', 63 # http://json.org/JSON_checker/test/fail30.json 64 '[0e+]', 65 # http://json.org/JSON_checker/test/fail31.json 66 '[0e+-1]', 67 # http://json.org/JSON_checker/test/fail32.json 68 '{"Comma instead if closing brace": true,', 69 # http://json.org/JSON_checker/test/fail33.json 70 '["mismatch"}', 55 71 # http://code.google.com/p/simplejson/issues/detail?id=3 56 72 u'["A\u001FZ control characters in string"]', … … 62 78 } 63 79 64 class TestFail( TestCase):80 class TestFail(object): 65 81 def test_failures(self): 66 82 for idx, doc in enumerate(JSONDOCS): 67 83 idx = idx + 1 68 84 if idx in SKIPS: 69 json.loads(doc)85 self.loads(doc) 70 86 continue 71 87 try: 72 json.loads(doc)88 self.loads(doc) 73 89 except ValueError: 74 90 pass 75 91 else: 76 self.fail("Expected failure for fail%d.json: %r" % (idx, doc)) 92 self.fail("Expected failure for fail{0}.json: {1!r}".format(idx, doc)) 93 94 def test_non_string_keys_dict(self): 95 data = {'a' : 1, (1, 2) : 2} 96 97 #This is for c encoder 98 self.assertRaises(TypeError, self.dumps, data) 99 100 #This is for python encoder 101 self.assertRaises(TypeError, self.dumps, data, indent=True) 102 103 104 class TestPyFail(TestFail, PyTest): pass 105 class TestCFail(TestFail, CTest): pass -
python/trunk/Lib/json/tests/test_float.py
r2 r391 1 1 import math 2 from unittest import TestCase2 from json.tests import PyTest, CTest 3 3 4 import json5 4 6 class TestFloat( TestCase):5 class TestFloat(object): 7 6 def test_floats(self): 8 for num in [1617161771.7650001, math.pi, math.pi**100, math.pi**-100]: 9 self.assertEquals(float(json.dumps(num)), num) 7 for num in [1617161771.7650001, math.pi, math.pi**100, 8 math.pi**-100, 3.1]: 9 self.assertEqual(float(self.dumps(num)), num) 10 self.assertEqual(self.loads(self.dumps(num)), num) 11 self.assertEqual(self.loads(unicode(self.dumps(num))), num) 12 13 def test_ints(self): 14 for num in [1, 1L, 1<<32, 1<<64]: 15 self.assertEqual(self.dumps(num), str(num)) 16 self.assertEqual(int(self.dumps(num)), num) 17 self.assertEqual(self.loads(self.dumps(num)), num) 18 self.assertEqual(self.loads(unicode(self.dumps(num))), num) 19 20 def test_out_of_range(self): 21 self.assertEqual(self.loads('[23456789012E666]'), [float('inf')]) 22 self.assertEqual(self.loads('[-23456789012E666]'), [float('-inf')]) 23 24 def test_allow_nan(self): 25 for val in (float('inf'), float('-inf'), float('nan')): 26 out = self.dumps([val]) 27 if val == val: # inf 28 self.assertEqual(self.loads(out), [val]) 29 else: # nan 30 res = self.loads(out) 31 self.assertEqual(len(res), 1) 32 self.assertNotEqual(res[0], res[0]) 33 self.assertRaises(ValueError, self.dumps, [val], allow_nan=False) 34 35 36 class TestPyFloat(TestFloat, PyTest): pass 37 class TestCFloat(TestFloat, CTest): pass -
python/trunk/Lib/json/tests/test_indent.py
r2 r391 1 from unittest import TestCase 1 import textwrap 2 from StringIO import StringIO 3 from json.tests import PyTest, CTest 2 4 3 import json4 import textwrap5 5 6 class TestIndent( TestCase):6 class TestIndent(object): 7 7 def test_indent(self): 8 8 h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', … … 31 31 32 32 33 d1 = json.dumps(h)34 d2 = json.dumps(h, indent=2, sort_keys=True, separators=(',', ': '))33 d1 = self.dumps(h) 34 d2 = self.dumps(h, indent=2, sort_keys=True, separators=(',', ': ')) 35 35 36 h1 = json.loads(d1)37 h2 = json.loads(d2)36 h1 = self.loads(d1) 37 h2 = self.loads(d2) 38 38 39 self.assertEquals(h1, h) 40 self.assertEquals(h2, h) 41 self.assertEquals(d2, expect) 39 self.assertEqual(h1, h) 40 self.assertEqual(h2, h) 41 self.assertEqual(d2, expect) 42 43 def test_indent0(self): 44 h = {3: 1} 45 def check(indent, expected): 46 d1 = self.dumps(h, indent=indent) 47 self.assertEqual(d1, expected) 48 49 sio = StringIO() 50 self.json.dump(h, sio, indent=indent) 51 self.assertEqual(sio.getvalue(), expected) 52 53 # indent=0 should emit newlines 54 check(0, '{\n"3": 1\n}') 55 # indent=None is more compact 56 check(None, '{"3": 1}') 57 58 59 class TestPyIndent(TestIndent, PyTest): pass 60 class TestCIndent(TestIndent, CTest): pass -
python/trunk/Lib/json/tests/test_pass1.py
r2 r391 1 from unittest import TestCase1 from json.tests import PyTest, CTest 2 2 3 import json4 3 5 4 # from http://json.org/JSON_checker/test/pass1.json … … 19 18 "e": 0.123456789e-12, 20 19 "E": 1.234567890E+34, 21 "": 23456789012E66 6,20 "": 23456789012E66, 22 21 "zero": 0, 23 22 "one": 1, … … 30 29 "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ", 31 30 "digit": "0123456789", 31 "0123456789": "digit", 32 32 "special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?", 33 33 "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A", … … 45 45 , 46 46 47 4 , 5 , 6 ,7 ], 48 "compact": [1,2,3,4,5,6,7], 47 4 , 5 , 6 ,7 ],"compact":[1,2,3,4,5,6,7], 49 48 "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}", 50 49 "quotes": "" \u0022 %22 0x22 034 "", … … 57 56 , 58 57 59 1066 60 61 58 1066, 59 1e1, 60 0.1e1, 61 1e-1, 62 1e00,2e+00,2e-00 62 63 ,"rosebud"] 63 64 ''' 64 65 65 class TestPass1( TestCase):66 class TestPass1(object): 66 67 def test_parse(self): 67 68 # test in/out equivalence and parsing 68 res = json.loads(JSON) 69 out = json.dumps(res) 70 self.assertEquals(res, json.loads(out)) 71 try: 72 json.dumps(res, allow_nan=False) 73 except ValueError: 74 pass 75 else: 76 self.fail("23456789012E666 should be out of range") 69 res = self.loads(JSON) 70 out = self.dumps(res) 71 self.assertEqual(res, self.loads(out)) 72 73 74 class TestPyPass1(TestPass1, PyTest): pass 75 class TestCPass1(TestPass1, CTest): pass -
python/trunk/Lib/json/tests/test_pass2.py
r2 r391 1 from unittest import TestCase2 import json 1 from json.tests import PyTest, CTest 2 3 3 4 4 # from http://json.org/JSON_checker/test/pass2.json … … 7 7 ''' 8 8 9 class TestPass2( TestCase):9 class TestPass2(object): 10 10 def test_parse(self): 11 11 # test in/out equivalence and parsing 12 res = json.loads(JSON) 13 out = json.dumps(res) 14 self.assertEquals(res, json.loads(out)) 12 res = self.loads(JSON) 13 out = self.dumps(res) 14 self.assertEqual(res, self.loads(out)) 15 16 17 class TestPyPass2(TestPass2, PyTest): pass 18 class TestCPass2(TestPass2, CTest): pass -
python/trunk/Lib/json/tests/test_pass3.py
r2 r391 1 from unittest import TestCase1 from json.tests import PyTest, CTest 2 2 3 import json4 3 5 4 # from http://json.org/JSON_checker/test/pass3.json … … 13 12 ''' 14 13 15 class TestPass3(TestCase): 14 15 class TestPass3(object): 16 16 def test_parse(self): 17 17 # test in/out equivalence and parsing 18 res = json.loads(JSON) 19 out = json.dumps(res) 20 self.assertEquals(res, json.loads(out)) 18 res = self.loads(JSON) 19 out = self.dumps(res) 20 self.assertEqual(res, self.loads(out)) 21 22 23 class TestPyPass3(TestPass3, PyTest): pass 24 class TestCPass3(TestPass3, CTest): pass -
python/trunk/Lib/json/tests/test_recursion.py
r2 r391 1 from unittest import TestCase1 from json.tests import PyTest, CTest 2 2 3 import json4 3 5 4 class JSONTestObject: … … 7 6 8 7 9 class RecursiveJSONEncoder(json.JSONEncoder): 10 recurse = False 11 def default(self, o): 12 if o is JSONTestObject: 13 if self.recurse: 14 return [JSONTestObject] 15 else: 16 return 'JSONTestObject' 17 return json.JSONEncoder.default(o) 18 19 20 class TestRecursion(TestCase): 8 class TestRecursion(object): 21 9 def test_listrecursion(self): 22 10 x = [] 23 11 x.append(x) 24 12 try: 25 json.dumps(x)13 self.dumps(x) 26 14 except ValueError: 27 15 pass … … 32 20 x.append(y) 33 21 try: 34 json.dumps(x)22 self.dumps(x) 35 23 except ValueError: 36 24 pass … … 40 28 x = [y, y] 41 29 # ensure that the marker is cleared 42 json.dumps(x)30 self.dumps(x) 43 31 44 32 def test_dictrecursion(self): … … 46 34 x["test"] = x 47 35 try: 48 json.dumps(x)36 self.dumps(x) 49 37 except ValueError: 50 38 pass … … 54 42 y = {"a": x, "b": x} 55 43 # ensure that the marker is cleared 56 json.dumps(x)44 self.dumps(x) 57 45 58 46 def test_defaultrecursion(self): 47 class RecursiveJSONEncoder(self.json.JSONEncoder): 48 recurse = False 49 def default(self, o): 50 if o is JSONTestObject: 51 if self.recurse: 52 return [JSONTestObject] 53 else: 54 return 'JSONTestObject' 55 return pyjson.JSONEncoder.default(o) 56 59 57 enc = RecursiveJSONEncoder() 60 self.assertEqual s(enc.encode(JSONTestObject), '"JSONTestObject"')58 self.assertEqual(enc.encode(JSONTestObject), '"JSONTestObject"') 61 59 enc.recurse = True 62 60 try: … … 66 64 else: 67 65 self.fail("didn't raise ValueError on default recursion") 66 67 68 def test_highly_nested_objects_decoding(self): 69 # test that loading highly-nested objects doesn't segfault when C 70 # accelerations are used. See #12017 71 # str 72 with self.assertRaises(RuntimeError): 73 self.loads('{"a":' * 100000 + '1' + '}' * 100000) 74 with self.assertRaises(RuntimeError): 75 self.loads('{"a":' * 100000 + '[1]' + '}' * 100000) 76 with self.assertRaises(RuntimeError): 77 self.loads('[' * 100000 + '1' + ']' * 100000) 78 # unicode 79 with self.assertRaises(RuntimeError): 80 self.loads(u'{"a":' * 100000 + u'1' + u'}' * 100000) 81 with self.assertRaises(RuntimeError): 82 self.loads(u'{"a":' * 100000 + u'[1]' + u'}' * 100000) 83 with self.assertRaises(RuntimeError): 84 self.loads(u'[' * 100000 + u'1' + u']' * 100000) 85 86 def test_highly_nested_objects_encoding(self): 87 # See #12051 88 l, d = [], {} 89 for x in xrange(100000): 90 l, d = [l], {'k':d} 91 with self.assertRaises(RuntimeError): 92 self.dumps(l) 93 with self.assertRaises(RuntimeError): 94 self.dumps(d) 95 96 def test_endless_recursion(self): 97 # See #12051 98 class EndlessJSONEncoder(self.json.JSONEncoder): 99 def default(self, o): 100 """If check_circular is False, this will keep adding another list.""" 101 return [o] 102 103 with self.assertRaises(RuntimeError): 104 EndlessJSONEncoder(check_circular=False).encode(5j) 105 106 107 class TestPyRecursion(TestRecursion, PyTest): pass 108 class TestCRecursion(TestRecursion, CTest): pass -
python/trunk/Lib/json/tests/test_scanstring.py
r2 r391 1 1 import sys 2 import decimal 3 from unittest import TestCase 2 from json.tests import PyTest, CTest 4 3 5 import json6 import json.decoder7 4 8 class TestScanString(TestCase): 9 def test_py_scanstring(self): 10 self._test_scanstring(json.decoder.py_scanstring) 11 12 def test_c_scanstring(self): 13 self._test_scanstring(json.decoder.c_scanstring) 14 15 def _test_scanstring(self, scanstring): 16 self.assertEquals( 5 class TestScanstring(object): 6 def test_scanstring(self): 7 scanstring = self.json.decoder.scanstring 8 self.assertEqual( 17 9 scanstring('"z\\ud834\\udd20x"', 1, None, True), 18 10 (u'z\U0001d120x', 16)) 19 11 20 12 if sys.maxunicode == 65535: 21 self.assertEqual s(13 self.assertEqual( 22 14 scanstring(u'"z\U0001d120x"', 1, None, True), 23 15 (u'z\U0001d120x', 6)) 24 16 else: 25 self.assertEqual s(17 self.assertEqual( 26 18 scanstring(u'"z\U0001d120x"', 1, None, True), 27 19 (u'z\U0001d120x', 5)) 28 20 29 self.assertEqual s(21 self.assertEqual( 30 22 scanstring('"\\u007b"', 1, None, True), 31 23 (u'{', 8)) 32 24 33 self.assertEqual s(25 self.assertEqual( 34 26 scanstring('"A JSON payload should be an object or array, not a string."', 1, None, True), 35 27 (u'A JSON payload should be an object or array, not a string.', 60)) 36 28 37 self.assertEqual s(29 self.assertEqual( 38 30 scanstring('["Unclosed array"', 2, None, True), 39 31 (u'Unclosed array', 17)) 40 32 41 self.assertEqual s(33 self.assertEqual( 42 34 scanstring('["extra comma",]', 2, None, True), 43 35 (u'extra comma', 14)) 44 36 45 self.assertEqual s(37 self.assertEqual( 46 38 scanstring('["double extra comma",,]', 2, None, True), 47 39 (u'double extra comma', 21)) 48 40 49 self.assertEqual s(41 self.assertEqual( 50 42 scanstring('["Comma after the close"],', 2, None, True), 51 43 (u'Comma after the close', 24)) 52 44 53 self.assertEqual s(45 self.assertEqual( 54 46 scanstring('["Extra close"]]', 2, None, True), 55 47 (u'Extra close', 14)) 56 48 57 self.assertEqual s(49 self.assertEqual( 58 50 scanstring('{"Extra comma": true,}', 2, None, True), 59 51 (u'Extra comma', 14)) 60 52 61 self.assertEqual s(53 self.assertEqual( 62 54 scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, None, True), 63 55 (u'Extra value after close', 26)) 64 56 65 self.assertEqual s(57 self.assertEqual( 66 58 scanstring('{"Illegal expression": 1 + 2}', 2, None, True), 67 59 (u'Illegal expression', 21)) 68 60 69 self.assertEqual s(61 self.assertEqual( 70 62 scanstring('{"Illegal invocation": alert()}', 2, None, True), 71 63 (u'Illegal invocation', 21)) 72 64 73 self.assertEqual s(65 self.assertEqual( 74 66 scanstring('{"Numbers cannot have leading zeroes": 013}', 2, None, True), 75 67 (u'Numbers cannot have leading zeroes', 37)) 76 68 77 self.assertEqual s(69 self.assertEqual( 78 70 scanstring('{"Numbers cannot be hex": 0x14}', 2, None, True), 79 71 (u'Numbers cannot be hex', 24)) 80 72 81 self.assertEqual s(73 self.assertEqual( 82 74 scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, None, True), 83 75 (u'Too deep', 30)) 84 76 85 self.assertEqual s(77 self.assertEqual( 86 78 scanstring('{"Missing colon" null}', 2, None, True), 87 79 (u'Missing colon', 16)) 88 80 89 self.assertEqual s(81 self.assertEqual( 90 82 scanstring('{"Double colon":: null}', 2, None, True), 91 83 (u'Double colon', 15)) 92 84 93 self.assertEqual s(85 self.assertEqual( 94 86 scanstring('{"Comma instead of colon", null}', 2, None, True), 95 87 (u'Comma instead of colon', 25)) 96 88 97 self.assertEqual s(89 self.assertEqual( 98 90 scanstring('["Colon instead of comma": false]', 2, None, True), 99 91 (u'Colon instead of comma', 25)) 100 92 101 self.assertEqual s(93 self.assertEqual( 102 94 scanstring('["Bad value", truth]', 2, None, True), 103 95 (u'Bad value', 12)) 104 96 105 97 def test_issue3623(self): 106 self.assertRaises(ValueError, json.decoder.scanstring, b"xxx", 1,98 self.assertRaises(ValueError, self.json.decoder.scanstring, b"xxx", 1, 107 99 "xxx") 108 100 self.assertRaises(UnicodeDecodeError, 109 json.encoder.encode_basestring_ascii, b"xx\xff") 101 self.json.encoder.encode_basestring_ascii, b"xx\xff") 102 103 def test_overflow(self): 104 with self.assertRaises(OverflowError): 105 self.json.decoder.scanstring(b"xxx", sys.maxsize+1) 106 107 108 class TestPyScanstring(TestScanstring, PyTest): pass 109 class TestCScanstring(TestScanstring, CTest): pass -
python/trunk/Lib/json/tests/test_separators.py
r2 r391 1 1 import textwrap 2 from unittest import TestCase 3 4 import json 2 from json.tests import PyTest, CTest 5 3 6 4 7 class TestSeparators( TestCase):5 class TestSeparators(object): 8 6 def test_separators(self): 9 7 h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth', … … 32 30 33 31 34 d1 = json.dumps(h)35 d2 = json.dumps(h, indent=2, sort_keys=True, separators=(' ,', ' : '))32 d1 = self.dumps(h) 33 d2 = self.dumps(h, indent=2, sort_keys=True, separators=(' ,', ' : ')) 36 34 37 h1 = json.loads(d1)38 h2 = json.loads(d2)35 h1 = self.loads(d1) 36 h2 = self.loads(d2) 39 37 40 self.assertEquals(h1, h) 41 self.assertEquals(h2, h) 42 self.assertEquals(d2, expect) 38 self.assertEqual(h1, h) 39 self.assertEqual(h2, h) 40 self.assertEqual(d2, expect) 41 42 43 class TestPySeparators(TestSeparators, PyTest): pass 44 class TestCSeparators(TestSeparators, CTest): pass -
python/trunk/Lib/json/tests/test_speedups.py
r2 r391 1 import decimal 2 from unittest import TestCase 1 from json.tests import CTest 3 2 4 from json import decoder5 from json import encoder6 3 7 class TestSpeedups( TestCase):4 class TestSpeedups(CTest): 8 5 def test_scanstring(self): 9 self.assertEqual s(decoder.scanstring.__module__, "_json")10 self.assert _(decoder.scanstring isdecoder.c_scanstring)6 self.assertEqual(self.json.decoder.scanstring.__module__, "_json") 7 self.assertIs(self.json.decoder.scanstring, self.json.decoder.c_scanstring) 11 8 12 9 def test_encode_basestring_ascii(self): 13 self.assertEquals(encoder.encode_basestring_ascii.__module__, "_json") 14 self.assert_(encoder.encode_basestring_ascii is 15 encoder.c_encode_basestring_ascii) 10 self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__, 11 "_json") 12 self.assertIs(self.json.encoder.encode_basestring_ascii, 13 self.json.encoder.c_encode_basestring_ascii) 14 15 class TestDecode(CTest): 16 def test_make_scanner(self): 17 self.assertRaises(AttributeError, self.json.scanner.c_make_scanner, 1) 18 19 def test_make_encoder(self): 20 self.assertRaises(TypeError, self.json.encoder.c_make_encoder, 21 None, 22 "\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75", 23 None) -
python/trunk/Lib/json/tests/test_unicode.py
r2 r391 1 from unittest import TestCase 1 from collections import OrderedDict 2 from json.tests import PyTest, CTest 2 3 3 import json4 4 5 class TestUnicode( TestCase):5 class TestUnicode(object): 6 6 def test_encoding1(self): 7 encoder = json.JSONEncoder(encoding='utf-8')7 encoder = self.json.JSONEncoder(encoding='utf-8') 8 8 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 9 9 s = u.encode('utf-8') 10 10 ju = encoder.encode(u) 11 11 js = encoder.encode(s) 12 self.assertEqual s(ju, js)12 self.assertEqual(ju, js) 13 13 14 14 def test_encoding2(self): 15 15 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 16 16 s = u.encode('utf-8') 17 ju = json.dumps(u, encoding='utf-8')18 js = json.dumps(s, encoding='utf-8')19 self.assertEqual s(ju, js)17 ju = self.dumps(u, encoding='utf-8') 18 js = self.dumps(s, encoding='utf-8') 19 self.assertEqual(ju, js) 20 20 21 21 def test_encoding3(self): 22 22 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 23 j = json.dumps(u)24 self.assertEqual s(j, '"\\u03b1\\u03a9"')23 j = self.dumps(u) 24 self.assertEqual(j, '"\\u03b1\\u03a9"') 25 25 26 26 def test_encoding4(self): 27 27 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 28 j = json.dumps([u])29 self.assertEqual s(j, '["\\u03b1\\u03a9"]')28 j = self.dumps([u]) 29 self.assertEqual(j, '["\\u03b1\\u03a9"]') 30 30 31 31 def test_encoding5(self): 32 32 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 33 j = json.dumps(u, ensure_ascii=False)34 self.assertEqual s(j, u'"{0}"'.format(u))33 j = self.dumps(u, ensure_ascii=False) 34 self.assertEqual(j, u'"{0}"'.format(u)) 35 35 36 36 def test_encoding6(self): 37 37 u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' 38 j = json.dumps([u], ensure_ascii=False)39 self.assertEqual s(j, u'["{0}"]'.format(u))38 j = self.dumps([u], ensure_ascii=False) 39 self.assertEqual(j, u'["{0}"]'.format(u)) 40 40 41 41 def test_big_unicode_encode(self): 42 42 u = u'\U0001d120' 43 self.assertEqual s(json.dumps(u), '"\\ud834\\udd20"')44 self.assertEqual s(json.dumps(u, ensure_ascii=False), u'"\U0001d120"')43 self.assertEqual(self.dumps(u), '"\\ud834\\udd20"') 44 self.assertEqual(self.dumps(u, ensure_ascii=False), u'"\U0001d120"') 45 45 46 46 def test_big_unicode_decode(self): 47 47 u = u'z\U0001d120x' 48 self.assertEqual s(json.loads('"' + u + '"'), u)49 self.assertEqual s(json.loads('"z\\ud834\\udd20x"'), u)48 self.assertEqual(self.loads('"' + u + '"'), u) 49 self.assertEqual(self.loads('"z\\ud834\\udd20x"'), u) 50 50 51 51 def test_unicode_decode(self): 52 52 for i in range(0, 0xd7ff): 53 53 u = unichr(i) 54 js = '"\\u{0:04x}"'.format(i) 55 self.assertEquals(json.loads(js), u) 54 s = '"\\u{0:04x}"'.format(i) 55 self.assertEqual(self.loads(s), u) 56 57 def test_object_pairs_hook_with_unicode(self): 58 s = u'{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' 59 p = [(u"xkd", 1), (u"kcw", 2), (u"art", 3), (u"hxm", 4), 60 (u"qrt", 5), (u"pad", 6), (u"hoy", 7)] 61 self.assertEqual(self.loads(s), eval(s)) 62 self.assertEqual(self.loads(s, object_pairs_hook = lambda x: x), p) 63 od = self.loads(s, object_pairs_hook = OrderedDict) 64 self.assertEqual(od, OrderedDict(p)) 65 self.assertEqual(type(od), OrderedDict) 66 # the object_pairs_hook takes priority over the object_hook 67 self.assertEqual(self.loads(s, 68 object_pairs_hook = OrderedDict, 69 object_hook = lambda x: None), 70 OrderedDict(p)) 71 72 def test_default_encoding(self): 73 self.assertEqual(self.loads(u'{"a": "\xe9"}'.encode('utf-8')), 74 {'a': u'\xe9'}) 75 76 def test_unicode_preservation(self): 77 self.assertEqual(type(self.loads(u'""')), unicode) 78 self.assertEqual(type(self.loads(u'"a"')), unicode) 79 self.assertEqual(type(self.loads(u'["a"]')[0]), unicode) 80 # Issue 10038. 81 self.assertEqual(type(self.loads('"foo"')), unicode) 82 83 def test_bad_encoding(self): 84 self.assertRaises(UnicodeEncodeError, self.loads, '"a"', u"rat\xe9") 85 self.assertRaises(TypeError, self.loads, '"a"', 1) 86 87 88 class TestPyUnicode(TestUnicode, PyTest): pass 89 class TestCUnicode(TestUnicode, CTest): pass
Note:
See TracChangeset
for help on using the changeset viewer.