xref: /openbmc/qemu/tests/qapi-schema/test-qapi.py (revision 013b4efc9be9af8276bd891cd52267d409f1d712)
1#!/usr/bin/env python3
2#
3# QAPI parser test harness
4#
5# Copyright (c) 2013 Red Hat Inc.
6#
7# Authors:
8#  Markus Armbruster <armbru@redhat.com>
9#
10# This work is licensed under the terms of the GNU GPL, version 2 or later.
11# See the COPYING file in the top-level directory.
12#
13
14
15import argparse
16import difflib
17import os
18import sys
19from io import StringIO
20
21from qapi.error import QAPIError
22from qapi.schema import QAPISchema, QAPISchemaVisitor
23
24
25class QAPISchemaTestVisitor(QAPISchemaVisitor):
26
27    def visit_module(self, name):
28        print('module %s' % name)
29
30    def visit_include(self, name, info):
31        print('include %s' % name)
32
33    def visit_enum_type(self, name, info, ifcond, features, members, prefix):
34        print('enum %s' % name)
35        if prefix:
36            print('    prefix %s' % prefix)
37        for m in members:
38            print('    member %s' % m.name)
39            self._print_if(m.ifcond, indent=8)
40        self._print_if(ifcond)
41        self._print_features(features)
42
43    def visit_array_type(self, name, info, ifcond, element_type):
44        if not info:
45            return              # suppress built-in arrays
46        print('array %s %s' % (name, element_type.name))
47        self._print_if(ifcond)
48
49    def visit_object_type(self, name, info, ifcond, base, members, variants,
50                          features):
51        print('object %s' % name)
52        if base:
53            print('    base %s' % base.name)
54        for m in members:
55            print('    member %s: %s optional=%s'
56                  % (m.name, m.type.name, m.optional))
57            self._print_if(m.ifcond, 8)
58        self._print_variants(variants)
59        self._print_if(ifcond)
60        self._print_features(features)
61
62    def visit_alternate_type(self, name, info, ifcond, features, variants):
63        print('alternate %s' % name)
64        self._print_variants(variants)
65        self._print_if(ifcond)
66        self._print_features(features)
67
68    def visit_command(self, name, info, ifcond, arg_type, ret_type, gen,
69                      success_response, boxed, allow_oob, allow_preconfig,
70                      features):
71        print('command %s %s -> %s'
72              % (name, arg_type and arg_type.name,
73                 ret_type and ret_type.name))
74        print('    gen=%s success_response=%s boxed=%s oob=%s preconfig=%s'
75              % (gen, success_response, boxed, allow_oob, allow_preconfig))
76        self._print_if(ifcond)
77        self._print_features(features)
78
79    def visit_event(self, name, info, ifcond, features, arg_type, boxed):
80        print('event %s %s' % (name, arg_type and arg_type.name))
81        print('    boxed=%s' % boxed)
82        self._print_if(ifcond)
83        self._print_features(features)
84
85    @staticmethod
86    def _print_variants(variants):
87        if variants:
88            print('    tag %s' % variants.tag_member.name)
89            for v in variants.variants:
90                print('    case %s: %s' % (v.name, v.type.name))
91                QAPISchemaTestVisitor._print_if(v.ifcond, indent=8)
92
93    @staticmethod
94    def _print_if(ifcond, indent=4):
95        if ifcond:
96            print('%sif %s' % (' ' * indent, ifcond))
97
98    @classmethod
99    def _print_features(cls, features):
100        if features:
101            for f in features:
102                print('    feature %s' % f.name)
103                cls._print_if(f.ifcond, 8)
104
105
106def test_frontend(fname):
107    schema = QAPISchema(fname)
108    schema.visit(QAPISchemaTestVisitor())
109
110    for doc in schema.docs:
111        if doc.symbol:
112            print('doc symbol=%s' % doc.symbol)
113        else:
114            print('doc freeform')
115        print('    body=\n%s' % doc.body.text)
116        for arg, section in doc.args.items():
117            print('    arg=%s\n%s' % (arg, section.text))
118        for feat, section in doc.features.items():
119            print('    feature=%s\n%s' % (feat, section.text))
120        for section in doc.sections:
121            print('    section=%s\n%s' % (section.name, section.text))
122
123
124def test_and_diff(test_name, dir_name, update):
125    sys.stdout = StringIO()
126    try:
127        test_frontend(os.path.join(dir_name, test_name + '.json'))
128    except QAPIError as err:
129        if err.info.fname is None:
130            print("%s" % err, file=sys.stderr)
131            return 2
132        errstr = str(err) + '\n'
133        if dir_name:
134            errstr = errstr.replace(dir_name + '/', '')
135        actual_err = errstr.splitlines(True)
136    else:
137        actual_err = []
138    finally:
139        actual_out = sys.stdout.getvalue().splitlines(True)
140        sys.stdout.close()
141        sys.stdout = sys.__stdout__
142
143    mode = 'r+' if update else 'r'
144    try:
145        outfp = open(os.path.join(dir_name, test_name + '.out'), mode)
146        errfp = open(os.path.join(dir_name, test_name + '.err'), mode)
147        expected_out = outfp.readlines()
148        expected_err = errfp.readlines()
149    except IOError as err:
150        print("%s: can't open '%s': %s"
151              % (sys.argv[0], err.filename, err.strerror),
152              file=sys.stderr)
153        return 2
154
155    if actual_out == expected_out and actual_err == expected_err:
156        return 0
157
158    print("%s %s" % (test_name, 'UPDATE' if update else 'FAIL'),
159          file=sys.stderr)
160    out_diff = difflib.unified_diff(expected_out, actual_out, outfp.name)
161    err_diff = difflib.unified_diff(expected_err, actual_err, errfp.name)
162    sys.stdout.writelines(out_diff)
163    sys.stdout.writelines(err_diff)
164
165    if not update:
166        return 1
167
168    try:
169        outfp.truncate(0)
170        outfp.seek(0)
171        outfp.writelines(actual_out)
172        errfp.truncate(0)
173        errfp.seek(0)
174        errfp.writelines(actual_err)
175    except IOError as err:
176        print("%s: can't write '%s': %s"
177              % (sys.argv[0], err.filename, err.strerror),
178              file=sys.stderr)
179        return 2
180
181    return 0
182
183
184def main(argv):
185    parser = argparse.ArgumentParser(
186        description='QAPI schema tester')
187    parser.add_argument('-d', '--dir', action='store', default='',
188                        help="directory containing tests")
189    parser.add_argument('-u', '--update', action='store_true',
190                        help="update expected test results")
191    parser.add_argument('tests', nargs='*', metavar='TEST', action='store')
192    args = parser.parse_args()
193
194    status = 0
195    for t in args.tests:
196        (dir_name, base_name) = os.path.split(t)
197        dir_name = dir_name or args.dir
198        test_name = os.path.splitext(base_name)[0]
199        status |= test_and_diff(test_name, dir_name, args.update)
200
201    exit(status)
202
203
204if __name__ == '__main__':
205    main(sys.argv)
206    exit(0)
207