xref: /qemu/tests/qapi-schema/test-qapi.py (revision 94d689d0c6f23dc3129e8432c496ccb866788dbf)
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_features(m.features, indent=8)
41        self._print_if(ifcond)
42        self._print_features(features)
43
44    def visit_array_type(self, name, info, ifcond, element_type):
45        if not info:
46            return              # suppress built-in arrays
47        print('array %s %s' % (name, element_type.name))
48        self._print_if(ifcond)
49
50    def visit_object_type(self, name, info, ifcond, features,
51                          base, members, branches):
52        print('object %s' % name)
53        if base:
54            print('    base %s' % base.name)
55        for m in members:
56            print('    member %s: %s optional=%s'
57                  % (m.name, m.type.name, m.optional))
58            self._print_if(m.ifcond, 8)
59            self._print_features(m.features, indent=8)
60        self._print_variants(branches)
61        self._print_if(ifcond)
62        self._print_features(features)
63
64    def visit_alternate_type(self, name, info, ifcond, features,
65                             alternatives):
66        print('alternate %s' % name)
67        self._print_variants(alternatives)
68        self._print_if(ifcond)
69        self._print_features(features)
70
71    def visit_command(self, name, info, ifcond, features,
72                      arg_type, ret_type, gen, success_response, boxed,
73                      allow_oob, allow_preconfig, coroutine):
74        print('command %s %s -> %s'
75              % (name, arg_type and arg_type.name,
76                 ret_type and ret_type.name))
77        print('    gen=%s success_response=%s boxed=%s oob=%s preconfig=%s%s'
78              % (gen, success_response, boxed, allow_oob, allow_preconfig,
79                 " coroutine=True" if coroutine else ""))
80        self._print_if(ifcond)
81        self._print_features(features)
82
83    def visit_event(self, name, info, ifcond, features, arg_type, boxed):
84        print('event %s %s' % (name, arg_type and arg_type.name))
85        print('    boxed=%s' % boxed)
86        self._print_if(ifcond)
87        self._print_features(features)
88
89    @staticmethod
90    def _print_variants(variants):
91        if variants:
92            print('    tag %s' % variants.tag_member.name)
93            for v in variants.variants:
94                print('    case %s: %s' % (v.name, v.type.name))
95                QAPISchemaTestVisitor._print_if(v.ifcond, indent=8)
96
97    @staticmethod
98    def _print_if(ifcond, indent=4):
99        if ifcond.is_present():
100            print('%sif %s' % (' ' * indent, ifcond.ifcond))
101
102    @classmethod
103    def _print_features(cls, features, indent=4):
104        if features:
105            for f in features:
106                print('%sfeature %s' % (' ' * indent, f.name))
107                cls._print_if(f.ifcond, indent + 4)
108
109
110def test_frontend(fname):
111    schema = QAPISchema(fname)
112    schema.visit(QAPISchemaTestVisitor())
113
114    for doc in schema.docs:
115        if doc.symbol:
116            print('doc symbol=%s' % doc.symbol)
117        else:
118            print('doc freeform')
119        print('    body=\n%s' % doc.body.text)
120        for arg, section in doc.args.items():
121            print('    arg=%s\n%s' % (arg, section.text))
122        for feat, section in doc.features.items():
123            print('    feature=%s\n%s' % (feat, section.text))
124        for section in doc.sections:
125            print('    section=%s\n%s' % (section.kind, section.text))
126
127
128def open_test_result(dir_name, file_name, update):
129    mode = 'r+' if update else 'r'
130    try:
131        return open(os.path.join(dir_name, file_name), mode, encoding='utf-8')
132    except FileNotFoundError:
133        if not update:
134            raise
135    return open(os.path.join(dir_name, file_name), 'w+', encoding='utf-8')
136
137
138def test_and_diff(test_name, dir_name, update):
139    sys.stdout = StringIO()
140    try:
141        test_frontend(os.path.join(dir_name, test_name + '.json'))
142    except QAPIError as err:
143        errstr = str(err) + '\n'
144        if dir_name:
145            errstr = errstr.replace(dir_name + '/', '')
146        actual_err = errstr.splitlines(True)
147    else:
148        actual_err = []
149    finally:
150        actual_out = sys.stdout.getvalue().splitlines(True)
151        sys.stdout.close()
152        sys.stdout = sys.__stdout__
153
154    try:
155        outfp = open_test_result(dir_name, test_name + '.out', update)
156        errfp = open_test_result(dir_name, test_name + '.err', update)
157        expected_out = outfp.readlines()
158        expected_err = errfp.readlines()
159    except OSError as err:
160        print("%s: can't open '%s': %s"
161              % (sys.argv[0], err.filename, err.strerror),
162              file=sys.stderr)
163        return 2
164
165    if actual_out == expected_out and actual_err == expected_err:
166        return 0
167
168    print("%s %s" % (test_name, 'UPDATE' if update else 'FAIL'),
169          file=sys.stderr)
170    out_diff = difflib.unified_diff(expected_out, actual_out, outfp.name)
171    err_diff = difflib.unified_diff(expected_err, actual_err, errfp.name)
172    sys.stdout.writelines(out_diff)
173    sys.stdout.writelines(err_diff)
174
175    if not update:
176        return 1
177
178    try:
179        outfp.truncate(0)
180        outfp.seek(0)
181        outfp.writelines(actual_out)
182        errfp.truncate(0)
183        errfp.seek(0)
184        errfp.writelines(actual_err)
185    except OSError as err:
186        print("%s: can't write '%s': %s"
187              % (sys.argv[0], err.filename, err.strerror),
188              file=sys.stderr)
189        return 2
190
191    return 0
192
193
194def main(argv):
195    parser = argparse.ArgumentParser(
196        description='QAPI schema tester')
197    parser.add_argument('-d', '--dir', action='store', default='',
198                        help="directory containing tests")
199    parser.add_argument('-u', '--update', action='store_true',
200                        default='QAPI_TEST_UPDATE' in os.environ,
201                        help="update expected test results")
202    parser.add_argument('tests', nargs='*', metavar='TEST', action='store')
203    args = parser.parse_args()
204
205    status = 0
206    for t in args.tests:
207        (dir_name, base_name) = os.path.split(t)
208        dir_name = dir_name or args.dir
209        test_name = os.path.splitext(base_name)[0]
210        status |= test_and_diff(test_name, dir_name, args.update)
211
212    sys.exit(status)
213
214
215if __name__ == '__main__':
216    main(sys.argv)
217    sys.exit(0)
218