]> git.proxmox.com Git - ovs.git/blob - tests/test-json.py
Fix ovs-dpctl-top by removing 3 wrong hunks in py3-compat.patch.
[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 import getopt
16 import sys
17
18 import ovs.json
19
20
21 def print_json(json):
22 if isinstance(json, str):
23 print("error: %s" % json)
24 return False
25 else:
26 ovs.json.to_stream(json, sys.stdout)
27 sys.stdout.write("\n")
28 return True
29
30
31 def parse_multiple(stream):
32 buf = stream.read(4096)
33 ok = True
34 parser = None
35 while len(buf):
36 if parser is None and buf[0] in " \t\r\n":
37 buf = buf[1:]
38 else:
39 if parser is None:
40 parser = ovs.json.Parser()
41 n = parser.feed(buf)
42 buf = buf[n:]
43 if len(buf):
44 if not print_json(parser.finish()):
45 ok = False
46 parser = None
47 if len(buf) == 0:
48 buf = stream.read(4096)
49 if parser and not print_json(parser.finish()):
50 ok = False
51 return ok
52
53
54 def main(argv):
55 argv0 = argv[0]
56
57 try:
58 options, args = getopt.gnu_getopt(argv[1:], '', ['multiple'])
59 except getopt.GetoptError as geo:
60 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
61 sys.exit(1)
62
63 multiple = False
64 for key, value in options:
65 if key == '--multiple':
66 multiple = True
67 else:
68 sys.stderr.write("%s: unhandled option %s\n" % (argv0, key))
69 sys.exit(1)
70
71 if len(args) != 1:
72 sys.stderr.write("usage: %s [--multiple] INPUT.json\n" % argv0)
73 sys.exit(1)
74
75 input_file = args[0]
76 if input_file == "-":
77 stream = sys.stdin
78 else:
79 stream = open(input_file, "r")
80
81 if multiple:
82 ok = parse_multiple(stream)
83 else:
84 ok = print_json(ovs.json.from_stream(stream))
85
86 if not ok:
87 sys.exit(1)
88
89
90 if __name__ == '__main__':
91 main(sys.argv)