16b3fae5d09750e11503063e56cff7e9d2889194
[cascardo/ovs.git] / tests / test-json.py
1 # Copyright (c) 2009, 2010 Nicira, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #     http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 from __future__ import print_function
16
17 import codecs
18 import getopt
19 import sys
20
21 import ovs.json
22 import six
23
24
25 def print_json(json):
26     if isinstance(json, six.string_types):
27         print("error: %s" % json)
28         return False
29     else:
30         ovs.json.to_stream(json, sys.stdout)
31         sys.stdout.write("\n")
32         return True
33
34
35 def parse_multiple(stream):
36     buf = stream.read(4096)
37     ok = True
38     parser = None
39     while len(buf):
40         if parser is None and buf[0] in " \t\r\n":
41             buf = buf[1:]
42         else:
43             if parser is None:
44                 parser = ovs.json.Parser()
45             n = parser.feed(buf)
46             buf = buf[n:]
47             if len(buf):
48                 if not print_json(parser.finish()):
49                     ok = False
50                 parser = None
51         if len(buf) == 0:
52             buf = stream.read(4096)
53     if parser and not print_json(parser.finish()):
54         ok = False
55     return ok
56
57
58 def main(argv):
59     argv0 = argv[0]
60
61     # Make stdout and stderr UTF-8, even if they are redirected to a file.
62     sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
63     sys.stderr = codecs.getwriter("utf-8")(sys.stderr)
64
65     try:
66         options, args = getopt.gnu_getopt(argv[1:], '', ['multiple'])
67     except getopt.GetoptError as geo:
68         sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
69         sys.exit(1)
70
71     multiple = False
72     for key, value in options:
73         if key == '--multiple':
74             multiple = True
75         else:
76             sys.stderr.write("%s: unhandled option %s\n" % (argv0, key))
77             sys.exit(1)
78
79     if len(args) != 1:
80         sys.stderr.write("usage: %s [--multiple] INPUT.json\n" % argv0)
81         sys.exit(1)
82
83     input_file = args[0]
84     if input_file == "-":
85         stream = sys.stdin
86     else:
87         stream = open(input_file, "r")
88
89     if multiple:
90         ok = parse_multiple(stream)
91     else:
92         ok = print_json(ovs.json.from_stream(stream))
93
94     if not ok:
95         sys.exit(1)
96
97
98 if __name__ == '__main__':
99     main(sys.argv)