Home | History | Annotate | Download | only in test
      1 # Simple implementation of a json test runner to run the test against json-py.
      2 from __future__ import print_function
      3 import sys
      4 import os.path
      5 import json
      6 import types
      7 
      8 if len(sys.argv) != 2:
      9     print("Usage: %s input-json-file", sys.argv[0])
     10     sys.exit(3)
     11     
     12 input_path = sys.argv[1]
     13 base_path = os.path.splitext(input_path)[0]
     14 actual_path = base_path + '.actual'
     15 rewrite_path = base_path + '.rewrite'
     16 rewrite_actual_path = base_path + '.actual-rewrite'
     17 
     18 def 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         
     46 def 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 
     53 def 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     
     59 input = file( input_path, 'rt' ).read()
     60 root = parseAndSaveValueTree( input, actual_path )
     61 rewrite = rewriteValueTree( json.write( root ), rewrite_path )
     62 rewrite_root = parseAndSaveValueTree( rewrite, rewrite_actual_path )
     63 
     64 sys.exit( 0 )
     65