1 import os 2 import sys 3 import json 4 import doctest 5 import unittest 6 7 from test import test_support 8 9 # import json with and without accelerations 10 cjson = test_support.import_fresh_module('json', fresh=['_json']) 11 pyjson = test_support.import_fresh_module('json', blocked=['_json']) 12 13 # create two base classes that will be used by the other tests 14 class PyTest(unittest.TestCase): 15 json = pyjson 16 loads = staticmethod(pyjson.loads) 17 dumps = staticmethod(pyjson.dumps) 18 19 @unittest.skipUnless(cjson, 'requires _json') 20 class 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 27 class 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 36 class 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 44 45 here = os.path.dirname(__file__) 46 47 def test_suite(): 48 suite = additional_tests() 49 loader = unittest.TestLoader() 50 for fn in os.listdir(here): 51 if fn.startswith("test") and fn.endswith(".py"): 52 modname = "json.tests." + fn[:-3] 53 __import__(modname) 54 module = sys.modules[modname] 55 suite.addTests(loader.loadTestsFromModule(module)) 56 return suite 57 58 def additional_tests(): 59 suite = unittest.TestSuite() 60 for mod in (json, json.encoder, json.decoder): 61 suite.addTest(doctest.DocTestSuite(mod)) 62 suite.addTest(TestPyTest('test_pyjson')) 63 suite.addTest(TestCTest('test_cjson')) 64 return suite 65 66 def main(): 67 suite = test_suite() 68 runner = unittest.TextTestRunner() 69 runner.run(suite) 70 71 if __name__ == '__main__': 72 sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) 73 main() 74