1from collections import OrderedDict
2from test.test_json import PyTest, CTest
3from test.support import bigaddrspacetest
4
5
6CASES = [
7    ('/\\"\ucafe\ubabe\uab98\ufcde\ubcda\uef4a\x08\x0c\n\r\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?', '"/\\\\\\"\\ucafe\\ubabe\\uab98\\ufcde\\ubcda\\uef4a\\b\\f\\n\\r\\t`1~!@#$%^&*()_+-=[]{}|;:\',./<>?"'),
8    ('\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'),
9    ('controls', '"controls"'),
10    ('\x08\x0c\n\r\t', '"\\b\\f\\n\\r\\t"'),
11    ('{"object with 1 member":["array with 1 element"]}', '"{\\"object with 1 member\\":[\\"array with 1 element\\"]}"'),
12    (' s p a c e d ', '" s p a c e d "'),
13    ('\U0001d120', '"\\ud834\\udd20"'),
14    ('\u03b1\u03a9', '"\\u03b1\\u03a9"'),
15    ("`1~!@#$%^&*()_+-={':[,]}|;.</>?", '"`1~!@#$%^&*()_+-={\':[,]}|;.</>?"'),
16    ('\x08\x0c\n\r\t', '"\\b\\f\\n\\r\\t"'),
17    ('\u0123\u4567\u89ab\ucdef\uabcd\uef4a', '"\\u0123\\u4567\\u89ab\\ucdef\\uabcd\\uef4a"'),
18]
19
20class TestEncodeBasestringAscii:
21    def test_encode_basestring_ascii(self):
22        fname = self.json.encoder.encode_basestring_ascii.__name__
23        for input_string, expect in CASES:
24            result = self.json.encoder.encode_basestring_ascii(input_string)
25            self.assertEqual(result, expect,
26                '{0!r} != {1!r} for {2}({3!r})'.format(
27                    result, expect, fname, input_string))
28
29    def test_ordered_dict(self):
30        # See issue 6105
31        items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
32        s = self.dumps(OrderedDict(items))
33        self.assertEqual(s, '{"one": 1, "two": 2, "three": 3, "four": 4, "five": 5}')
34
35    def test_sorted_dict(self):
36        items = [('one', 1), ('two', 2), ('three', 3), ('four', 4), ('five', 5)]
37        s = self.dumps(dict(items), sort_keys=True)
38        self.assertEqual(s, '{"five": 5, "four": 4, "one": 1, "three": 3, "two": 2}')
39
40
41class TestPyEncodeBasestringAscii(TestEncodeBasestringAscii, PyTest): pass
42class TestCEncodeBasestringAscii(TestEncodeBasestringAscii, CTest):
43    @bigaddrspacetest
44    def test_overflow(self):
45        size = (2**32)//6 + 1
46        s = "\x00"*size
47        with self.assertRaises(OverflowError):
48            self.json.encoder.encode_basestring_ascii(s)
49