1from test.test_json import CTest
2
3
4class BadBool:
5    def __bool__(self):
6        1/0
7
8
9class TestSpeedups(CTest):
10    def test_scanstring(self):
11        self.assertEqual(self.json.decoder.scanstring.__module__, "_json")
12        self.assertIs(self.json.decoder.scanstring, self.json.decoder.c_scanstring)
13
14    def test_encode_basestring_ascii(self):
15        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
16                         "_json")
17        self.assertIs(self.json.encoder.encode_basestring_ascii,
18                      self.json.encoder.c_encode_basestring_ascii)
19
20
21class TestDecode(CTest):
22    def test_make_scanner(self):
23        self.assertRaises(AttributeError, self.json.scanner.c_make_scanner, 1)
24
25    def test_bad_bool_args(self):
26        def test(value):
27            self.json.decoder.JSONDecoder(strict=BadBool()).decode(value)
28        self.assertRaises(ZeroDivisionError, test, '""')
29        self.assertRaises(ZeroDivisionError, test, '{}')
30
31
32class TestEncode(CTest):
33    def test_make_encoder(self):
34        self.assertRaises(TypeError, self.json.encoder.c_make_encoder,
35            (True, False),
36            b"\xCD\x7D\x3D\x4E\x12\x4C\xF9\x79\xD7\x52\xBA\x82\xF2\x27\x4A\x7D\xA0\xCA\x75",
37            None)
38
39    def test_bad_str_encoder(self):
40        # Issue #31505: There shouldn't be an assertion failure in case
41        # c_make_encoder() receives a bad encoder() argument.
42        def bad_encoder1(*args):
43            return None
44        enc = self.json.encoder.c_make_encoder(None, lambda obj: str(obj),
45                                               bad_encoder1, None, ': ', ', ',
46                                               False, False, False)
47        with self.assertRaises(TypeError):
48            enc('spam', 4)
49        with self.assertRaises(TypeError):
50            enc({'spam': 42}, 4)
51
52        def bad_encoder2(*args):
53            1/0
54        enc = self.json.encoder.c_make_encoder(None, lambda obj: str(obj),
55                                               bad_encoder2, None, ': ', ', ',
56                                               False, False, False)
57        with self.assertRaises(ZeroDivisionError):
58            enc('spam', 4)
59
60    def test_bad_bool_args(self):
61        def test(name):
62            self.json.encoder.JSONEncoder(**{name: BadBool()}).encode({'a': 1})
63        self.assertRaises(ZeroDivisionError, test, 'skipkeys')
64        self.assertRaises(ZeroDivisionError, test, 'ensure_ascii')
65        self.assertRaises(ZeroDivisionError, test, 'check_circular')
66        self.assertRaises(ZeroDivisionError, test, 'allow_nan')
67        self.assertRaises(ZeroDivisionError, test, 'sort_keys')
68
69    def test_unsortable_keys(self):
70        with self.assertRaises(TypeError):
71            self.json.encoder.JSONEncoder(sort_keys=True).encode({'a': 1, 1: 'a'})
72