pyjsontestrunner.py 2.3 KB

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