]> git.proxmox.com Git - mirror_ovs.git/blob - tests/test-json.py
conntrack: Support zone limits.
[mirror_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 import six
24
25
26 def print_json(json):
27 if isinstance(json, six.string_types):
28 print("error: %s" % json)
29 return False
30 else:
31 ovs.json.to_stream(json, sys.stdout)
32 sys.stdout.write("\n")
33 return True
34
35
36 def parse_multiple(stream):
37 buf = stream.read(4096)
38 ok = True
39 parser = None
40 while len(buf):
41 if parser is None and buf[0] in " \t\r\n":
42 buf = buf[1:]
43 else:
44 if parser is None:
45 parser = ovs.json.Parser()
46 n = parser.feed(buf)
47 buf = buf[n:]
48 if len(buf):
49 if not print_json(parser.finish()):
50 ok = False
51 parser = None
52 if len(buf) == 0:
53 buf = stream.read(4096)
54 if parser and not print_json(parser.finish()):
55 ok = False
56 return ok
57
58
59 def main(argv):
60 argv0 = argv[0]
61
62 # When this is used with Python 3, the program produces no output.
63 if six.PY2:
64 # Make stdout and stderr UTF-8, even if they are redirected to a file.
65 sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
66 sys.stderr = codecs.getwriter("utf-8")(sys.stderr)
67
68 try:
69 options, args = getopt.gnu_getopt(argv[1:], '', ['multiple'])
70 except getopt.GetoptError as geo:
71 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
72 sys.exit(1)
73
74 multiple = False
75 for key, value in options:
76 if key == '--multiple':
77 multiple = True
78 else:
79 sys.stderr.write("%s: unhandled option %s\n" % (argv0, key))
80 sys.exit(1)
81
82 if len(args) != 1:
83 sys.stderr.write("usage: %s [--multiple] INPUT.json\n" % argv0)
84 sys.exit(1)
85
86 input_file = args[0]
87 if input_file == "-":
88 stream = sys.stdin
89 else:
90 stream = open(input_file, "r")
91
92 if multiple:
93 ok = parse_multiple(stream)
94 else:
95 ok = print_json(ovs.json.from_stream(stream))
96
97 if not ok:
98 sys.exit(1)
99
100
101 if __name__ == '__main__':
102 main(sys.argv)