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