ovn: Remove top ovn directory from PATHs.
[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
23
24 def print_json(json):
25     if type(json) in [str, unicode]:
26         print("error: %s" % json)
27         return False
28     else:
29         ovs.json.to_stream(json, sys.stdout)
30         sys.stdout.write("\n")
31         return True
32
33
34 def parse_multiple(stream):
35     buf = stream.read(4096)
36     ok = True
37     parser = None
38     while len(buf):
39         if parser is None and buf[0] in " \t\r\n":
40             buf = buf[1:]
41         else:
42             if parser is None:
43                 parser = ovs.json.Parser()
44             n = parser.feed(buf)
45             buf = buf[n:]
46             if len(buf):
47                 if not print_json(parser.finish()):
48                     ok = False
49                 parser = None
50         if len(buf) == 0:
51             buf = stream.read(4096)
52     if parser and not print_json(parser.finish()):
53         ok = False
54     return ok
55
56
57 def main(argv):
58     argv0 = argv[0]
59
60     # Make stdout and stderr UTF-8, even if they are redirected to a file.
61     sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
62     sys.stderr = codecs.getwriter("utf-8")(sys.stderr)
63
64     try:
65         options, args = getopt.gnu_getopt(argv[1:], '', ['multiple'])
66     except getopt.GetoptError as geo:
67         sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
68         sys.exit(1)
69
70     multiple = False
71     for key, value in options:
72         if key == '--multiple':
73             multiple = True
74         else:
75             sys.stderr.write("%s: unhandled option %s\n" % (argv0, key))
76             sys.exit(1)
77
78     if len(args) != 1:
79         sys.stderr.write("usage: %s [--multiple] INPUT.json\n" % argv0)
80         sys.exit(1)
81
82     input_file = args[0]
83     if input_file == "-":
84         stream = sys.stdin
85     else:
86         stream = open(input_file, "r")
87
88     if multiple:
89         ok = parse_multiple(stream)
90     else:
91         ok = print_json(ovs.json.from_stream(stream))
92
93     if not ok:
94         sys.exit(1)
95
96
97 if __name__ == '__main__':
98     main(sys.argv)