]> git.proxmox.com Git - ovs.git/blob - tests/test-json.py
datapath: Fix off-by-one error in dev_get_stats() compat code.
[ovs.git] / tests / test-json.py
1 # Copyright (c) 2009, 2010 Nicira Networks.
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 codecs
16 import getopt
17 import sys
18
19 import ovs.json
20
21 def print_json(json):
22 if type(json) in [str, unicode]:
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 def parse_multiple(stream):
31 buf = stream.read(4096)
32 ok = True
33 parser = None
34 while len(buf):
35 if parser is None and buf[0] in " \t\r\n":
36 buf = buf[1:]
37 else:
38 if parser is None:
39 parser = ovs.json.Parser()
40 n = parser.feed(buf)
41 buf = buf[n:]
42 if len(buf):
43 if not print_json(parser.finish()):
44 ok = False
45 parser = None
46 if len(buf) == 0:
47 buf = stream.read(4096)
48 if parser and not print_json(parser.finish()):
49 ok = False
50 return ok
51
52 def main(argv):
53 argv0 = argv[0]
54
55 # Make stdout and stderr UTF-8, even if they are redirected to a file.
56 sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
57 sys.stderr = codecs.getwriter("utf-8")(sys.stderr)
58
59 try:
60 options, args = getopt.gnu_getopt(argv[1:], '', ['multiple'])
61 except getopt.GetoptError, geo:
62 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
63 sys.exit(1)
64
65 multiple = False
66 for key, value in options:
67 if key == '--multiple':
68 multiple = True
69 else:
70 sys.stderr.write("%s: unhandled option %s\n" % (argv0, key))
71 sys.exit(1)
72
73 if len(args) != 1:
74 sys.stderr.write("usage: %s [--multiple] INPUT.json\n" % argv0)
75 sys.exit(1)
76
77 input_file = args[0]
78 if input_file == "-":
79 stream = sys.stdin
80 else:
81 stream = open(input_file, "r")
82
83 if multiple:
84 ok = parse_multiple(stream)
85 else:
86 ok = print_json(ovs.json.from_stream(stream))
87
88 if not ok:
89 sys.exit(1)
90
91 if __name__ == '__main__':
92 main(sys.argv)