test-qapi.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225
  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. import argparse
  14. import difflib
  15. import os
  16. import sys
  17. from io import StringIO
  18. from qapi.error import QAPIError
  19. from qapi.schema import QAPISchema, QAPISchemaVisitor
  20. class QAPISchemaTestVisitor(QAPISchemaVisitor):
  21. def visit_module(self, name):
  22. print('module %s' % name)
  23. def visit_include(self, name, info):
  24. print('include %s' % name)
  25. def visit_enum_type(self, name, info, ifcond, features, members, prefix):
  26. print('enum %s' % name)
  27. if prefix:
  28. print(' prefix %s' % prefix)
  29. for m in members:
  30. print(' member %s' % m.name)
  31. self._print_if(m.ifcond, indent=8)
  32. self._print_features(m.features, indent=8)
  33. self._print_if(ifcond)
  34. self._print_features(features)
  35. def visit_array_type(self, name, info, ifcond, element_type):
  36. if not info:
  37. return # suppress built-in arrays
  38. print('array %s %s' % (name, element_type.name))
  39. self._print_if(ifcond)
  40. def visit_object_type(self, name, info, ifcond, features,
  41. base, members, variants):
  42. print('object %s' % name)
  43. if base:
  44. print(' base %s' % base.name)
  45. for m in members:
  46. print(' member %s: %s optional=%s'
  47. % (m.name, m.type.name, m.optional))
  48. self._print_if(m.ifcond, 8)
  49. self._print_features(m.features, indent=8)
  50. self._print_variants(variants)
  51. self._print_if(ifcond)
  52. self._print_features(features)
  53. def visit_alternate_type(self, name, info, ifcond, features, variants):
  54. print('alternate %s' % name)
  55. self._print_variants(variants)
  56. self._print_if(ifcond)
  57. self._print_features(features)
  58. def visit_command(self, name, info, ifcond, features,
  59. arg_type, ret_type, gen, success_response, boxed,
  60. allow_oob, allow_preconfig, coroutine):
  61. print('command %s %s -> %s'
  62. % (name, arg_type and arg_type.name,
  63. ret_type and ret_type.name))
  64. print(' gen=%s success_response=%s boxed=%s oob=%s preconfig=%s%s'
  65. % (gen, success_response, boxed, allow_oob, allow_preconfig,
  66. " coroutine=True" if coroutine else ""))
  67. self._print_if(ifcond)
  68. self._print_features(features)
  69. def visit_event(self, name, info, ifcond, features, arg_type, boxed):
  70. print('event %s %s' % (name, arg_type and arg_type.name))
  71. print(' boxed=%s' % boxed)
  72. self._print_if(ifcond)
  73. self._print_features(features)
  74. @staticmethod
  75. def _print_variants(variants):
  76. if variants:
  77. print(' tag %s' % variants.tag_member.name)
  78. for v in variants.variants:
  79. print(' case %s: %s' % (v.name, v.type.name))
  80. QAPISchemaTestVisitor._print_if(v.ifcond, indent=8)
  81. @staticmethod
  82. def _print_if(ifcond, indent=4):
  83. # TODO Drop this hack after replacing OrderedDict by plain
  84. # dict (requires Python 3.7)
  85. def _massage(subcond):
  86. if isinstance(subcond, str):
  87. return subcond
  88. if isinstance(subcond, list):
  89. return [_massage(val) for val in subcond]
  90. return {key: _massage(val) for key, val in subcond.items()}
  91. if ifcond.is_present():
  92. print('%sif %s' % (' ' * indent, _massage(ifcond.ifcond)))
  93. @classmethod
  94. def _print_features(cls, features, indent=4):
  95. if features:
  96. for f in features:
  97. print('%sfeature %s' % (' ' * indent, f.name))
  98. cls._print_if(f.ifcond, indent + 4)
  99. def test_frontend(fname):
  100. schema = QAPISchema(fname)
  101. schema.visit(QAPISchemaTestVisitor())
  102. for doc in schema.docs:
  103. if doc.symbol:
  104. print('doc symbol=%s' % doc.symbol)
  105. else:
  106. print('doc freeform')
  107. print(' body=\n%s' % doc.body.text)
  108. for arg, section in doc.args.items():
  109. print(' arg=%s\n%s' % (arg, section.text))
  110. for feat, section in doc.features.items():
  111. print(' feature=%s\n%s' % (feat, section.text))
  112. for section in doc.sections:
  113. print(' section=%s\n%s' % (section.name, section.text))
  114. def open_test_result(dir_name, file_name, update):
  115. mode = 'r+' if update else 'r'
  116. try:
  117. fp = open(os.path.join(dir_name, file_name), mode)
  118. except FileNotFoundError:
  119. if not update:
  120. raise
  121. fp = open(os.path.join(dir_name, file_name), 'w+')
  122. return fp
  123. def test_and_diff(test_name, dir_name, update):
  124. sys.stdout = StringIO()
  125. try:
  126. test_frontend(os.path.join(dir_name, test_name + '.json'))
  127. except QAPIError as err:
  128. errstr = str(err) + '\n'
  129. if dir_name:
  130. errstr = errstr.replace(dir_name + '/', '')
  131. actual_err = errstr.splitlines(True)
  132. else:
  133. actual_err = []
  134. finally:
  135. actual_out = sys.stdout.getvalue().splitlines(True)
  136. sys.stdout.close()
  137. sys.stdout = sys.__stdout__
  138. try:
  139. outfp = open_test_result(dir_name, test_name + '.out', update)
  140. errfp = open_test_result(dir_name, test_name + '.err', update)
  141. expected_out = outfp.readlines()
  142. expected_err = errfp.readlines()
  143. except OSError as err:
  144. print("%s: can't open '%s': %s"
  145. % (sys.argv[0], err.filename, err.strerror),
  146. file=sys.stderr)
  147. return 2
  148. if actual_out == expected_out and actual_err == expected_err:
  149. return 0
  150. print("%s %s" % (test_name, 'UPDATE' if update else 'FAIL'),
  151. file=sys.stderr)
  152. out_diff = difflib.unified_diff(expected_out, actual_out, outfp.name)
  153. err_diff = difflib.unified_diff(expected_err, actual_err, errfp.name)
  154. sys.stdout.writelines(out_diff)
  155. sys.stdout.writelines(err_diff)
  156. if not update:
  157. return 1
  158. try:
  159. outfp.truncate(0)
  160. outfp.seek(0)
  161. outfp.writelines(actual_out)
  162. errfp.truncate(0)
  163. errfp.seek(0)
  164. errfp.writelines(actual_err)
  165. except OSError as err:
  166. print("%s: can't write '%s': %s"
  167. % (sys.argv[0], err.filename, err.strerror),
  168. file=sys.stderr)
  169. return 2
  170. return 0
  171. def main(argv):
  172. parser = argparse.ArgumentParser(
  173. description='QAPI schema tester')
  174. parser.add_argument('-d', '--dir', action='store', default='',
  175. help="directory containing tests")
  176. parser.add_argument('-u', '--update', action='store_true',
  177. help="update expected test results")
  178. parser.add_argument('tests', nargs='*', metavar='TEST', action='store')
  179. args = parser.parse_args()
  180. status = 0
  181. for t in args.tests:
  182. (dir_name, base_name) = os.path.split(t)
  183. dir_name = dir_name or args.dir
  184. test_name = os.path.splitext(base_name)[0]
  185. status |= test_and_diff(test_name, dir_name, args.update)
  186. exit(status)
  187. if __name__ == '__main__':
  188. main(sys.argv)
  189. exit(0)