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