Ignore:
Timestamp:
Mar 19, 2014, 11:31:01 PM (11 years ago)
Author:
dmik
Message:

python: Merge vendor 2.7.6 to trunk.

Location:
python/trunk
Files:
17 edited
2 copied

Legend:

Unmodified
Added
Removed
  • python/trunk

  • python/trunk/Lib/json/tests/__init__.py

    r2 r391  
    11import os
    22import sys
     3import json
     4import doctest
    35import unittest
    4 import doctest
     6
     7from test import test_support
     8
     9# import json with and without accelerations
     10cjson = test_support.import_fresh_module('json', fresh=['_json'])
     11pyjson = test_support.import_fresh_module('json', blocked=['_json'])
     12
     13# create two base classes that will be used by the other tests
     14class PyTest(unittest.TestCase):
     15    json = pyjson
     16    loads = staticmethod(pyjson.loads)
     17    dumps = staticmethod(pyjson.dumps)
     18
     19@unittest.skipUnless(cjson, 'requires _json')
     20class 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
     27class 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
     36class 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
    544
    645here = os.path.dirname(__file__)
     
    1857
    1958def additional_tests():
    20     import json
    21     import json.encoder
    22     import json.decoder
    2359    suite = unittest.TestSuite()
    2460    for mod in (json, json.encoder, json.decoder):
    2561        suite.addTest(doctest.DocTestSuite(mod))
     62    suite.addTest(TestPyTest('test_pyjson'))
     63    suite.addTest(TestCTest('test_cjson'))
    2664    return suite
    2765
  • python/trunk/Lib/json/tests/test_decode.py

    r2 r391  
    11import decimal
    2 from unittest import TestCase
     2from StringIO import StringIO
     3from collections import OrderedDict
     4from json.tests import PyTest, CTest
    35
    4 import json
    56
    6 class TestDecode(TestCase):
     7class TestDecode(object):
    78    def test_decimal(self):
    8         rval = json.loads('1.1', parse_float=decimal.Decimal)
    9         self.assert_(isinstance(rval, decimal.Decimal))
    10         self.assertEquals(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'))
    1112
    1213    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
     63class TestPyDecode(TestDecode, PyTest): pass
     64class TestCDecode(TestDecode, CTest): pass
  • python/trunk/Lib/json/tests/test_default.py

    r2 r391  
    1 from unittest import TestCase
     1from json.tests import PyTest, CTest
    22
    3 import json
    43
    5 class TestDefault(TestCase):
     4class TestDefault(object):
    65    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
     11class TestPyDefault(TestDefault, PyTest): pass
     12class TestCDefault(TestDefault, CTest): pass
  • python/trunk/Lib/json/tests/test_dump.py

    r2 r391  
    1 from unittest import TestCase
    21from cStringIO import StringIO
     2from json.tests import PyTest, CTest
    33
    4 import json
    54
    6 class TestDump(TestCase):
     5class TestDump(object):
    76    def test_dump(self):
    87        sio = StringIO()
    9         json.dump({}, sio)
    10         self.assertEquals(sio.getvalue(), '{}')
     8        self.json.dump({}, sio)
     9        self.assertEqual(sio.getvalue(), '{}')
    1110
    1211    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
     31class TestPyDump(TestDump, PyTest): pass
     32class TestCDump(TestDump, CTest): pass
  • python/trunk/Lib/json/tests/test_encode_basestring_ascii.py

    r2 r391  
    1 from unittest import TestCase
     1from collections import OrderedDict
     2from json.tests import PyTest, CTest
    23
    3 import json.encoder
    44
    55CASES = [
     
    2222]
    2323
    24 class TestEncodeBaseStringAscii(TestCase):
    25     def test_py_encode_basestring_ascii(self):
    26         self._test_encode_basestring_ascii(json.encoder.py_encode_basestring_ascii)
     24class 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))
    2732
    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}')
    3038
    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
     40class TestPyEncodeBasestringAscii(TestEncodeBasestringAscii, PyTest): pass
     41class TestCEncodeBasestringAscii(TestEncodeBasestringAscii, CTest): pass
  • python/trunk/Lib/json/tests/test_fail.py

    r2 r391  
    1 from unittest import TestCase
     1from json.tests import PyTest, CTest
    22
    3 import json
    4 
    5 # Fri Dec 30 18:57:26 2005
     3# 2007-10-05
    64JSONDOCS = [
    75    # http://json.org/JSON_checker/test/fail1.json
     
    108    '["Unclosed array"',
    119    # http://json.org/JSON_checker/test/fail3.json
    12     '{unquoted_key: "keys must be quoted}',
     10    '{unquoted_key: "keys must be quoted"}',
    1311    # http://json.org/JSON_checker/test/fail4.json
    1412    '["extra comma",]',
     
    3634    '["Illegal backslash escape: \\x15"]',
    3735    # http://json.org/JSON_checker/test/fail16.json
    38     '["Illegal backslash escape: \\\'"]',
     36    '[\\naked]',
    3937    # http://json.org/JSON_checker/test/fail17.json
    4038    '["Illegal backslash escape: \\017"]',
     
    5351    # http://json.org/JSON_checker/test/fail24.json
    5452    "['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"}',
    5571    # http://code.google.com/p/simplejson/issues/detail?id=3
    5672    u'["A\u001FZ control characters in string"]',
     
    6278}
    6379
    64 class TestFail(TestCase):
     80class TestFail(object):
    6581    def test_failures(self):
    6682        for idx, doc in enumerate(JSONDOCS):
    6783            idx = idx + 1
    6884            if idx in SKIPS:
    69                 json.loads(doc)
     85                self.loads(doc)
    7086                continue
    7187            try:
    72                 json.loads(doc)
     88                self.loads(doc)
    7389            except ValueError:
    7490                pass
    7591            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
     104class TestPyFail(TestFail, PyTest): pass
     105class TestCFail(TestFail, CTest): pass
  • python/trunk/Lib/json/tests/test_float.py

    r2 r391  
    11import math
    2 from unittest import TestCase
     2from json.tests import PyTest, CTest
    33
    4 import json
    54
    6 class TestFloat(TestCase):
     5class TestFloat(object):
    76    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
     36class TestPyFloat(TestFloat, PyTest): pass
     37class TestCFloat(TestFloat, CTest): pass
  • python/trunk/Lib/json/tests/test_indent.py

    r2 r391  
    1 from unittest import TestCase
     1import textwrap
     2from StringIO import StringIO
     3from json.tests import PyTest, CTest
    24
    3 import json
    4 import textwrap
    55
    6 class TestIndent(TestCase):
     6class TestIndent(object):
    77    def test_indent(self):
    88        h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
     
    3131
    3232
    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=(',', ': '))
    3535
    36         h1 = json.loads(d1)
    37         h2 = json.loads(d2)
     36        h1 = self.loads(d1)
     37        h2 = self.loads(d2)
    3838
    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
     59class TestPyIndent(TestIndent, PyTest): pass
     60class TestCIndent(TestIndent, CTest): pass
  • python/trunk/Lib/json/tests/test_pass1.py

    r2 r391  
    1 from unittest import TestCase
     1from json.tests import PyTest, CTest
    22
    3 import json
    43
    54# from http://json.org/JSON_checker/test/pass1.json
     
    1918        "e": 0.123456789e-12,
    2019        "E": 1.234567890E+34,
    21         "":  23456789012E666,
     20        "":  23456789012E66,
    2221        "zero": 0,
    2322        "one": 1,
     
    3029        "ALPHA": "ABCDEFGHIJKLMNOPQRSTUVWYZ",
    3130        "digit": "0123456789",
     31        "0123456789": "digit",
    3232        "special": "`1~!@#$%^&*()_+-={':[,]}|;.</>?",
    3333        "hex": "\u0123\u4567\u89AB\uCDEF\uabcd\uef4A",
     
    4545,
    4646
    47 4 , 5        ,          6           ,7        ],
    48         "compact": [1,2,3,4,5,6,7],
     474 , 5        ,          6           ,7        ],"compact":[1,2,3,4,5,6,7],
    4948        "jsontext": "{\"object with 1 member\":[\"array with 1 element\"]}",
    5049        "quotes": "&#34; \u0022 %22 0x22 034 &#x22;",
     
    5756,
    5857
    59 1066
    60 
    61 
     581066,
     591e1,
     600.1e1,
     611e-1,
     621e00,2e+00,2e-00
    6263,"rosebud"]
    6364'''
    6465
    65 class TestPass1(TestCase):
     66class TestPass1(object):
    6667    def test_parse(self):
    6768        # 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
     74class TestPyPass1(TestPass1, PyTest): pass
     75class TestCPass1(TestPass1, CTest): pass
  • python/trunk/Lib/json/tests/test_pass2.py

    r2 r391  
    1 from unittest import TestCase
    2 import json
     1from json.tests import PyTest, CTest
     2
    33
    44# from http://json.org/JSON_checker/test/pass2.json
     
    77'''
    88
    9 class TestPass2(TestCase):
     9class TestPass2(object):
    1010    def test_parse(self):
    1111        # 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
     17class TestPyPass2(TestPass2, PyTest): pass
     18class TestCPass2(TestPass2, CTest): pass
  • python/trunk/Lib/json/tests/test_pass3.py

    r2 r391  
    1 from unittest import TestCase
     1from json.tests import PyTest, CTest
    22
    3 import json
    43
    54# from http://json.org/JSON_checker/test/pass3.json
     
    1312'''
    1413
    15 class TestPass3(TestCase):
     14
     15class TestPass3(object):
    1616    def test_parse(self):
    1717        # 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
     23class TestPyPass3(TestPass3, PyTest): pass
     24class TestCPass3(TestPass3, CTest): pass
  • python/trunk/Lib/json/tests/test_recursion.py

    r2 r391  
    1 from unittest import TestCase
     1from json.tests import PyTest, CTest
    22
    3 import json
    43
    54class JSONTestObject:
     
    76
    87
    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):
     8class TestRecursion(object):
    219    def test_listrecursion(self):
    2210        x = []
    2311        x.append(x)
    2412        try:
    25             json.dumps(x)
     13            self.dumps(x)
    2614        except ValueError:
    2715            pass
     
    3220        x.append(y)
    3321        try:
    34             json.dumps(x)
     22            self.dumps(x)
    3523        except ValueError:
    3624            pass
     
    4028        x = [y, y]
    4129        # ensure that the marker is cleared
    42         json.dumps(x)
     30        self.dumps(x)
    4331
    4432    def test_dictrecursion(self):
     
    4634        x["test"] = x
    4735        try:
    48             json.dumps(x)
     36            self.dumps(x)
    4937        except ValueError:
    5038            pass
     
    5442        y = {"a": x, "b": x}
    5543        # ensure that the marker is cleared
    56         json.dumps(x)
     44        self.dumps(x)
    5745
    5846    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
    5957        enc = RecursiveJSONEncoder()
    60         self.assertEquals(enc.encode(JSONTestObject), '"JSONTestObject"')
     58        self.assertEqual(enc.encode(JSONTestObject), '"JSONTestObject"')
    6159        enc.recurse = True
    6260        try:
     
    6664        else:
    6765            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
     107class TestPyRecursion(TestRecursion, PyTest): pass
     108class TestCRecursion(TestRecursion, CTest): pass
  • python/trunk/Lib/json/tests/test_scanstring.py

    r2 r391  
    11import sys
    2 import decimal
    3 from unittest import TestCase
     2from json.tests import PyTest, CTest
    43
    5 import json
    6 import json.decoder
    74
    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(
     5class TestScanstring(object):
     6    def test_scanstring(self):
     7        scanstring = self.json.decoder.scanstring
     8        self.assertEqual(
    179            scanstring('"z\\ud834\\udd20x"', 1, None, True),
    1810            (u'z\U0001d120x', 16))
    1911
    2012        if sys.maxunicode == 65535:
    21             self.assertEquals(
     13            self.assertEqual(
    2214                scanstring(u'"z\U0001d120x"', 1, None, True),
    2315                (u'z\U0001d120x', 6))
    2416        else:
    25             self.assertEquals(
     17            self.assertEqual(
    2618                scanstring(u'"z\U0001d120x"', 1, None, True),
    2719                (u'z\U0001d120x', 5))
    2820
    29         self.assertEquals(
     21        self.assertEqual(
    3022            scanstring('"\\u007b"', 1, None, True),
    3123            (u'{', 8))
    3224
    33         self.assertEquals(
     25        self.assertEqual(
    3426            scanstring('"A JSON payload should be an object or array, not a string."', 1, None, True),
    3527            (u'A JSON payload should be an object or array, not a string.', 60))
    3628
    37         self.assertEquals(
     29        self.assertEqual(
    3830            scanstring('["Unclosed array"', 2, None, True),
    3931            (u'Unclosed array', 17))
    4032
    41         self.assertEquals(
     33        self.assertEqual(
    4234            scanstring('["extra comma",]', 2, None, True),
    4335            (u'extra comma', 14))
    4436
    45         self.assertEquals(
     37        self.assertEqual(
    4638            scanstring('["double extra comma",,]', 2, None, True),
    4739            (u'double extra comma', 21))
    4840
    49         self.assertEquals(
     41        self.assertEqual(
    5042            scanstring('["Comma after the close"],', 2, None, True),
    5143            (u'Comma after the close', 24))
    5244
    53         self.assertEquals(
     45        self.assertEqual(
    5446            scanstring('["Extra close"]]', 2, None, True),
    5547            (u'Extra close', 14))
    5648
    57         self.assertEquals(
     49        self.assertEqual(
    5850            scanstring('{"Extra comma": true,}', 2, None, True),
    5951            (u'Extra comma', 14))
    6052
    61         self.assertEquals(
     53        self.assertEqual(
    6254            scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, None, True),
    6355            (u'Extra value after close', 26))
    6456
    65         self.assertEquals(
     57        self.assertEqual(
    6658            scanstring('{"Illegal expression": 1 + 2}', 2, None, True),
    6759            (u'Illegal expression', 21))
    6860
    69         self.assertEquals(
     61        self.assertEqual(
    7062            scanstring('{"Illegal invocation": alert()}', 2, None, True),
    7163            (u'Illegal invocation', 21))
    7264
    73         self.assertEquals(
     65        self.assertEqual(
    7466            scanstring('{"Numbers cannot have leading zeroes": 013}', 2, None, True),
    7567            (u'Numbers cannot have leading zeroes', 37))
    7668
    77         self.assertEquals(
     69        self.assertEqual(
    7870            scanstring('{"Numbers cannot be hex": 0x14}', 2, None, True),
    7971            (u'Numbers cannot be hex', 24))
    8072
    81         self.assertEquals(
     73        self.assertEqual(
    8274            scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, None, True),
    8375            (u'Too deep', 30))
    8476
    85         self.assertEquals(
     77        self.assertEqual(
    8678            scanstring('{"Missing colon" null}', 2, None, True),
    8779            (u'Missing colon', 16))
    8880
    89         self.assertEquals(
     81        self.assertEqual(
    9082            scanstring('{"Double colon":: null}', 2, None, True),
    9183            (u'Double colon', 15))
    9284
    93         self.assertEquals(
     85        self.assertEqual(
    9486            scanstring('{"Comma instead of colon", null}', 2, None, True),
    9587            (u'Comma instead of colon', 25))
    9688
    97         self.assertEquals(
     89        self.assertEqual(
    9890            scanstring('["Colon instead of comma": false]', 2, None, True),
    9991            (u'Colon instead of comma', 25))
    10092
    101         self.assertEquals(
     93        self.assertEqual(
    10294            scanstring('["Bad value", truth]', 2, None, True),
    10395            (u'Bad value', 12))
    10496
    10597    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,
    10799                          "xxx")
    108100        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
     108class TestPyScanstring(TestScanstring, PyTest): pass
     109class TestCScanstring(TestScanstring, CTest): pass
  • python/trunk/Lib/json/tests/test_separators.py

    r2 r391  
    11import textwrap
    2 from unittest import TestCase
    3 
    4 import json
     2from json.tests import PyTest, CTest
    53
    64
    7 class TestSeparators(TestCase):
     5class TestSeparators(object):
    86    def test_separators(self):
    97        h = [['blorpie'], ['whoops'], [], 'd-shtaeou', 'd-nthiouh', 'i-vhbjkhnth',
     
    3230
    3331
    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=(' ,', ' : '))
    3634
    37         h1 = json.loads(d1)
    38         h2 = json.loads(d2)
     35        h1 = self.loads(d1)
     36        h2 = self.loads(d2)
    3937
    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
     43class TestPySeparators(TestSeparators, PyTest): pass
     44class TestCSeparators(TestSeparators, CTest): pass
  • python/trunk/Lib/json/tests/test_speedups.py

    r2 r391  
    1 import decimal
    2 from unittest import TestCase
     1from json.tests import CTest
    32
    4 from json import decoder
    5 from json import encoder
    63
    7 class TestSpeedups(TestCase):
     4class TestSpeedups(CTest):
    85    def test_scanstring(self):
    9         self.assertEquals(decoder.scanstring.__module__, "_json")
    10         self.assert_(decoder.scanstring is decoder.c_scanstring)
     6        self.assertEqual(self.json.decoder.scanstring.__module__, "_json")
     7        self.assertIs(self.json.decoder.scanstring, self.json.decoder.c_scanstring)
    118
    129    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
     15class 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
     1from collections import OrderedDict
     2from json.tests import PyTest, CTest
    23
    3 import json
    44
    5 class TestUnicode(TestCase):
     5class TestUnicode(object):
    66    def test_encoding1(self):
    7         encoder = json.JSONEncoder(encoding='utf-8')
     7        encoder = self.json.JSONEncoder(encoding='utf-8')
    88        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
    99        s = u.encode('utf-8')
    1010        ju = encoder.encode(u)
    1111        js = encoder.encode(s)
    12         self.assertEquals(ju, js)
     12        self.assertEqual(ju, js)
    1313
    1414    def test_encoding2(self):
    1515        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
    1616        s = u.encode('utf-8')
    17         ju = json.dumps(u, encoding='utf-8')
    18         js = json.dumps(s, encoding='utf-8')
    19         self.assertEquals(ju, js)
     17        ju = self.dumps(u, encoding='utf-8')
     18        js = self.dumps(s, encoding='utf-8')
     19        self.assertEqual(ju, js)
    2020
    2121    def test_encoding3(self):
    2222        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
    23         j = json.dumps(u)
    24         self.assertEquals(j, '"\\u03b1\\u03a9"')
     23        j = self.dumps(u)
     24        self.assertEqual(j, '"\\u03b1\\u03a9"')
    2525
    2626    def test_encoding4(self):
    2727        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
    28         j = json.dumps([u])
    29         self.assertEquals(j, '["\\u03b1\\u03a9"]')
     28        j = self.dumps([u])
     29        self.assertEqual(j, '["\\u03b1\\u03a9"]')
    3030
    3131    def test_encoding5(self):
    3232        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
    33         j = json.dumps(u, ensure_ascii=False)
    34         self.assertEquals(j, u'"{0}"'.format(u))
     33        j = self.dumps(u, ensure_ascii=False)
     34        self.assertEqual(j, u'"{0}"'.format(u))
    3535
    3636    def test_encoding6(self):
    3737        u = u'\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
    38         j = json.dumps([u], ensure_ascii=False)
    39         self.assertEquals(j, u'["{0}"]'.format(u))
     38        j = self.dumps([u], ensure_ascii=False)
     39        self.assertEqual(j, u'["{0}"]'.format(u))
    4040
    4141    def test_big_unicode_encode(self):
    4242        u = u'\U0001d120'
    43         self.assertEquals(json.dumps(u), '"\\ud834\\udd20"')
    44         self.assertEquals(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"')
    4545
    4646    def test_big_unicode_decode(self):
    4747        u = u'z\U0001d120x'
    48         self.assertEquals(json.loads('"' + u + '"'), u)
    49         self.assertEquals(json.loads('"z\\ud834\\udd20x"'), u)
     48        self.assertEqual(self.loads('"' + u + '"'), u)
     49        self.assertEqual(self.loads('"z\\ud834\\udd20x"'), u)
    5050
    5151    def test_unicode_decode(self):
    5252        for i in range(0, 0xd7ff):
    5353            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
     88class TestPyUnicode(TestUnicode, PyTest): pass
     89class TestCUnicode(TestUnicode, CTest): pass
Note: See TracChangeset for help on using the changeset viewer.