1# Simple implementation of a json test runner to run the test against json-py. 2from __future__ import print_function 3import sys 4import os.path 5import json 6import types 7 8if len(sys.argv) != 2: 9 print("Usage: %s input-json-file", sys.argv[0]) 10 sys.exit(3) 11 12input_path = sys.argv[1] 13base_path = os.path.splitext(input_path)[0] 14actual_path = base_path + '.actual' 15rewrite_path = base_path + '.rewrite' 16rewrite_actual_path = base_path + '.actual-rewrite' 17 18def valueTreeToString( fout, value, path = '.' ): 19 ty = type(value) 20 if ty is types.DictType: 21 fout.write( '%s={}\n' % path ) 22 suffix = path[-1] != '.' and '.' or '' 23 names = value.keys() 24 names.sort() 25 for name in names: 26 valueTreeToString( fout, value[name], path + suffix + name ) 27 elif ty is types.ListType: 28 fout.write( '%s=[]\n' % path ) 29 for index, childValue in zip( xrange(0,len(value)), value ): 30 valueTreeToString( fout, childValue, path + '[%d]' % index ) 31 elif ty is types.StringType: 32 fout.write( '%s="%s"\n' % (path,value) ) 33 elif ty is types.IntType: 34 fout.write( '%s=%d\n' % (path,value) ) 35 elif ty is types.FloatType: 36 fout.write( '%s=%.16g\n' % (path,value) ) 37 elif value is True: 38 fout.write( '%s=true\n' % path ) 39 elif value is False: 40 fout.write( '%s=false\n' % path ) 41 elif value is None: 42 fout.write( '%s=null\n' % path ) 43 else: 44 assert False and "Unexpected value type" 45 46def parseAndSaveValueTree( input, actual_path ): 47 root = json.loads( input ) 48 fout = file( actual_path, 'wt' ) 49 valueTreeToString( fout, root ) 50 fout.close() 51 return root 52 53def rewriteValueTree( value, rewrite_path ): 54 rewrite = json.dumps( value ) 55 #rewrite = rewrite[1:-1] # Somehow the string is quoted ! jsonpy bug ? 56 file( rewrite_path, 'wt').write( rewrite + '\n' ) 57 return rewrite 58 59input = file( input_path, 'rt' ).read() 60root = parseAndSaveValueTree( input, actual_path ) 61rewrite = rewriteValueTree( json.write( root ), rewrite_path ) 62rewrite_root = parseAndSaveValueTree( rewrite, rewrite_actual_path ) 63 64sys.exit( 0 ) 65