]> git.proxmox.com Git - mirror_ovs.git/blame - tests/test-json.py
test: Reverse the order of commands added by ON_EXIT macro
[mirror_ovs.git] / tests / test-json.py
CommitLineData
e0edde6f 1# Copyright (c) 2009, 2010 Nicira, Inc.
26bb0f31 2#
99155935
BP
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:
26bb0f31 6#
99155935 7# http://www.apache.org/licenses/LICENSE-2.0
26bb0f31 8#
99155935
BP
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
15import codecs
16import getopt
17import sys
18
19import ovs.json
20
26bb0f31 21
99155935
BP
22def print_json(json):
23 if type(json) in [str, unicode]:
24 print "error: %s" % json
25 return False
26 else:
27 ovs.json.to_stream(json, sys.stdout)
28 sys.stdout.write("\n")
29 return True
30
26bb0f31 31
99155935
BP
32def parse_multiple(stream):
33 buf = stream.read(4096)
34 ok = True
35 parser = None
36 while len(buf):
37 if parser is None and buf[0] in " \t\r\n":
38 buf = buf[1:]
39 else:
40 if parser is None:
41 parser = ovs.json.Parser()
42 n = parser.feed(buf)
43 buf = buf[n:]
44 if len(buf):
45 if not print_json(parser.finish()):
46 ok = False
47 parser = None
48 if len(buf) == 0:
49 buf = stream.read(4096)
50 if parser and not print_json(parser.finish()):
51 ok = False
52 return ok
53
26bb0f31 54
99155935
BP
55def main(argv):
56 argv0 = argv[0]
57
58 # Make stdout and stderr UTF-8, even if they are redirected to a file.
59 sys.stdout = codecs.getwriter("utf-8")(sys.stdout)
60 sys.stderr = codecs.getwriter("utf-8")(sys.stderr)
61
62 try:
63 options, args = getopt.gnu_getopt(argv[1:], '', ['multiple'])
64 except getopt.GetoptError, geo:
65 sys.stderr.write("%s: %s\n" % (argv0, geo.msg))
66 sys.exit(1)
67
68 multiple = False
69 for key, value in options:
70 if key == '--multiple':
71 multiple = True
72 else:
73 sys.stderr.write("%s: unhandled option %s\n" % (argv0, key))
74 sys.exit(1)
75
76 if len(args) != 1:
77 sys.stderr.write("usage: %s [--multiple] INPUT.json\n" % argv0)
78 sys.exit(1)
79
80 input_file = args[0]
81 if input_file == "-":
82 stream = sys.stdin
83 else:
84 stream = open(input_file, "r")
85
86 if multiple:
87 ok = parse_multiple(stream)
88 else:
89 ok = print_json(ovs.json.from_stream(stream))
90
91 if not ok:
92 sys.exit(1)
93
26bb0f31 94
99155935
BP
95if __name__ == '__main__':
96 main(sys.argv)