• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1import os
2import json
3import doctest
4import unittest
5
6from test import support
7from test.support import import_helper
8
9
10# import json with and without accelerations
11cjson = import_helper.import_fresh_module('json', fresh=['_json'])
12pyjson = import_helper.import_fresh_module('json', blocked=['_json'])
13# JSONDecodeError is cached inside the _json module
14cjson.JSONDecodeError = cjson.decoder.JSONDecodeError = json.JSONDecodeError
15
16# create two base classes that will be used by the other tests
17class PyTest(unittest.TestCase):
18    json = pyjson
19    loads = staticmethod(pyjson.loads)
20    dumps = staticmethod(pyjson.dumps)
21    JSONDecodeError = staticmethod(pyjson.JSONDecodeError)
22
23@unittest.skipUnless(cjson, 'requires _json')
24class CTest(unittest.TestCase):
25    if cjson is not None:
26        json = cjson
27        loads = staticmethod(cjson.loads)
28        dumps = staticmethod(cjson.dumps)
29        JSONDecodeError = staticmethod(cjson.JSONDecodeError)
30
31# test PyTest and CTest checking if the functions come from the right module
32class TestPyTest(PyTest):
33    def test_pyjson(self):
34        self.assertEqual(self.json.scanner.make_scanner.__module__,
35                         'json.scanner')
36        self.assertEqual(self.json.decoder.scanstring.__module__,
37                         'json.decoder')
38        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
39                         'json.encoder')
40
41class TestCTest(CTest):
42    def test_cjson(self):
43        self.assertEqual(self.json.scanner.make_scanner.__module__, '_json')
44        self.assertEqual(self.json.decoder.scanstring.__module__, '_json')
45        self.assertEqual(self.json.encoder.c_make_encoder.__module__, '_json')
46        self.assertEqual(self.json.encoder.encode_basestring_ascii.__module__,
47                         '_json')
48
49
50def load_tests(loader, _, pattern):
51    suite = unittest.TestSuite()
52    for mod in (json, json.encoder, json.decoder):
53        suite.addTest(doctest.DocTestSuite(mod))
54    suite.addTest(TestPyTest('test_pyjson'))
55    suite.addTest(TestCTest('test_cjson'))
56
57    pkg_dir = os.path.dirname(__file__)
58    return support.load_package_tests(pkg_dir, loader, suite, pattern)
59