generate_tests.py 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. #! /usr/bin/python3
  2. #
  3. # Copyright (c) 2022 Google LLC
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. import glob
  17. import os
  18. import subprocess
  19. import sys
  20. # A handful of relevant tests are hand-picked to generate extra unit tests with
  21. # specific options of spirv-diff.
  22. IGNORE_SET_BINDING_TESTS = ['different_decorations_vertex']
  23. IGNORE_LOCATION_TESTS = ['different_decorations_fragment']
  24. IGNORE_DECORATIONS_TESTS = ['different_decorations_vertex', 'different_decorations_fragment']
  25. DUMP_IDS_TESTS = ['basic', 'int_vs_uint_constants', 'multiple_same_entry_points', 'small_functions_small_diffs']
  26. LICENSE = u"""Copyright (c) 2022 Google LLC.
  27. Licensed under the Apache License, Version 2.0 (the "License");
  28. you may not use this file except in compliance with the License.
  29. You may obtain a copy of the License at
  30. http://www.apache.org/licenses/LICENSE-2.0
  31. Unless required by applicable law or agreed to in writing, software
  32. distributed under the License is distributed on an "AS IS" BASIS,
  33. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  34. See the License for the specific language governing permissions and
  35. limitations under the License.
  36. """
  37. TEMPLATE_TEST_FILE = u"""// GENERATED FILE - DO NOT EDIT.
  38. // Generated by {script_name}
  39. //
  40. {license}
  41. #include "../diff_test_utils.h"
  42. #include "gtest/gtest.h"
  43. namespace spvtools {{
  44. namespace diff {{
  45. namespace {{
  46. {test_comment}
  47. constexpr char kSrc[] = R"({src_spirv})";
  48. constexpr char kDst[] = R"({dst_spirv})";
  49. TEST(DiffTest, {test_name}) {{
  50. constexpr char kDiff[] = R"({diff_spirv})";
  51. Options options;
  52. DoStringDiffTest(kSrc, kDst, kDiff, options);
  53. }}
  54. TEST(DiffTest, {test_name}NoDebug) {{
  55. constexpr char kSrcNoDebug[] = R"({src_spirv_no_debug})";
  56. constexpr char kDstNoDebug[] = R"({dst_spirv_no_debug})";
  57. constexpr char kDiff[] = R"({diff_spirv_no_debug})";
  58. Options options;
  59. DoStringDiffTest(kSrcNoDebug, kDstNoDebug, kDiff, options);
  60. }}
  61. {extra_tests}
  62. }} // namespace
  63. }} // namespace diff
  64. }} // namespace spvtools
  65. """
  66. TEMPLATE_TEST_FUNC = u"""
  67. TEST(DiffTest, {test_name}{test_tag}) {{
  68. constexpr char kDiff[] = R"({diff_spirv})";
  69. Options options;
  70. {test_options}
  71. DoStringDiffTest(kSrc, kDst, kDiff, options);
  72. }}
  73. """
  74. TEMPLATE_TEST_FILES_CMAKE = u"""# GENERATED FILE - DO NOT EDIT.
  75. # Generated by {script_name}
  76. #
  77. {license}
  78. list(APPEND DIFF_TEST_FILES
  79. {test_files}
  80. )
  81. """
  82. VARIANT_NONE = 0
  83. VARIANT_IGNORE_SET_BINDING = 1
  84. VARIANT_IGNORE_LOCATION = 2
  85. VARIANT_IGNORE_DECORATIONS = 3
  86. VARIANT_DUMP_IDS = 4
  87. def print_usage():
  88. print("Usage: {} <path-to-spirv-diff>".format(sys.argv[0]))
  89. def remove_debug_info(in_path):
  90. tmp_dir = '.no_dbg'
  91. if not os.path.exists(tmp_dir):
  92. os.makedirs(tmp_dir)
  93. (in_basename, in_ext) = os.path.splitext(in_path)
  94. out_name = in_basename + '_no_dbg' + in_ext
  95. out_path = os.path.join(tmp_dir, out_name)
  96. with open(in_path, 'r') as fin:
  97. with open(out_path, 'w') as fout:
  98. for line in fin:
  99. ops = line.strip().split()
  100. op = ops[0] if len(ops) > 0 else ''
  101. if (op != ';;' and op != 'OpName' and op != 'OpMemberName' and op != 'OpString' and
  102. op != 'OpLine' and op != 'OpNoLine' and op != 'OpModuleProcessed'):
  103. fout.write(line)
  104. return out_path
  105. def make_src_file(test_name):
  106. return '{}_src.spvasm'.format(test_name)
  107. def make_dst_file(test_name):
  108. return '{}_dst.spvasm'.format(test_name)
  109. def make_cpp_file(test_name):
  110. return '{}_autogen.cpp'.format(test_name)
  111. def make_camel_case(test_name):
  112. return test_name.replace('_', ' ').title().replace(' ', '')
  113. def make_comment(text, comment_prefix):
  114. return '\n'.join([comment_prefix + (' ' if line.strip() else '') + line for line in text.splitlines()])
  115. def read_file(file_name):
  116. with open(file_name, 'r') as f:
  117. content = f.read()
  118. # Use unix line endings.
  119. content = content.replace('\r\n', '\n')
  120. return content
  121. def parse_test_comment(src_spirv_file_name, src_spirv):
  122. src_spirv_lines = src_spirv.splitlines()
  123. comment_line_count = 0
  124. while comment_line_count < len(src_spirv_lines):
  125. if not src_spirv_lines[comment_line_count].strip().startswith(';;'):
  126. break
  127. comment_line_count += 1
  128. if comment_line_count == 0:
  129. print("Expected comment on test file '{}'. See README.md next to this file.".format(src_spirv_file_name))
  130. sys.exit(1)
  131. comment_block = src_spirv_lines[:comment_line_count]
  132. spirv_block = src_spirv_lines[comment_line_count:]
  133. comment_block = ['// ' + line.replace(';;', '').strip() for line in comment_block]
  134. return '\n'.join(spirv_block), '\n'.join(comment_block)
  135. def run_diff_tool(diff_tool, src_file, dst_file, variant):
  136. args = [diff_tool]
  137. if variant == VARIANT_IGNORE_SET_BINDING or variant == VARIANT_IGNORE_DECORATIONS:
  138. args.append('--ignore-set-binding')
  139. if variant == VARIANT_IGNORE_LOCATION or variant == VARIANT_IGNORE_DECORATIONS:
  140. args.append('--ignore-location')
  141. if variant == VARIANT_DUMP_IDS:
  142. args.append('--with-id-map')
  143. args.append('--no-color')
  144. args.append('--no-indent')
  145. args.append(src_file)
  146. args.append(dst_file)
  147. success = True
  148. print(' '.join(args))
  149. process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
  150. out, err = process.communicate()
  151. if process.returncode != 0:
  152. print(err)
  153. sys.exit(process.returncode)
  154. # Use unix line endings.
  155. out = out.replace('\r\n', '\n')
  156. return out
  157. def generate_extra_test(diff_tool, src_file, dst_file, variant, test_name_camel_case, test_tag, test_options):
  158. diff = run_diff_tool(diff_tool, src_file, dst_file, variant)
  159. return TEMPLATE_TEST_FUNC.format(
  160. test_name = test_name_camel_case,
  161. test_tag = test_tag,
  162. test_options = test_options,
  163. diff_spirv = diff)
  164. def generate_test(diff_tool, test_name):
  165. src_file = make_src_file(test_name)
  166. dst_file = make_dst_file(test_name)
  167. src_file_no_debug = remove_debug_info(src_file)
  168. dst_file_no_debug = remove_debug_info(dst_file)
  169. src_spirv = read_file(src_file)
  170. dst_spirv = read_file(dst_file)
  171. src_spirv_no_debug = read_file(src_file_no_debug)
  172. dst_spirv_no_debug = read_file(dst_file_no_debug)
  173. test_name_camel_case = make_camel_case(test_name)
  174. diff_spirv = run_diff_tool(diff_tool, src_file, dst_file, VARIANT_NONE)
  175. diff_spirv_no_debug = run_diff_tool(diff_tool, src_file_no_debug, dst_file_no_debug, VARIANT_NONE)
  176. extra_tests = []
  177. if test_name in IGNORE_SET_BINDING_TESTS:
  178. extra_tests.append(generate_extra_test(diff_tool, src_file, dst_file, VARIANT_IGNORE_SET_BINDING,
  179. test_name_camel_case, 'IgnoreSetBinding', 'options.ignore_set_binding = true;'))
  180. if test_name in IGNORE_LOCATION_TESTS:
  181. extra_tests.append(generate_extra_test(diff_tool, src_file, dst_file, VARIANT_IGNORE_LOCATION,
  182. test_name_camel_case, 'IgnoreLocation', 'options.ignore_location = true;'))
  183. if test_name in IGNORE_DECORATIONS_TESTS:
  184. extra_tests.append(generate_extra_test(diff_tool, src_file, dst_file, VARIANT_IGNORE_DECORATIONS,
  185. test_name_camel_case, 'IgnoreSetBindingLocation',
  186. '\n '.join(['options.ignore_set_binding = true;', 'options.ignore_location = true;'])))
  187. if test_name in DUMP_IDS_TESTS:
  188. extra_tests.append(generate_extra_test(diff_tool, src_file, dst_file, VARIANT_DUMP_IDS,
  189. test_name_camel_case, 'DumpIds', 'options.dump_id_map = true;'))
  190. src_spirv, test_comment = parse_test_comment(src_file, src_spirv)
  191. test_file = TEMPLATE_TEST_FILE.format(
  192. script_name = os.path.basename(__file__),
  193. license = make_comment(LICENSE, '//'),
  194. test_comment = test_comment,
  195. test_name = test_name_camel_case,
  196. src_spirv = src_spirv,
  197. dst_spirv = dst_spirv,
  198. diff_spirv = diff_spirv,
  199. src_spirv_no_debug = src_spirv_no_debug,
  200. dst_spirv_no_debug = dst_spirv_no_debug,
  201. diff_spirv_no_debug = diff_spirv_no_debug,
  202. extra_tests = ''.join(extra_tests))
  203. test_file_name = make_cpp_file(test_name)
  204. with open(test_file_name, 'wb') as fout:
  205. fout.write(str.encode(test_file))
  206. return test_file_name
  207. def generate_tests(diff_tool, test_names):
  208. return [generate_test(diff_tool, test_name) for test_name in test_names]
  209. def generate_cmake(test_files):
  210. cmake = TEMPLATE_TEST_FILES_CMAKE.format(
  211. script_name = os.path.basename(__file__),
  212. license = make_comment(LICENSE, '#'),
  213. test_files = '\n'.join(['"diff_files/{}"'.format(f) for f in test_files]))
  214. with open('diff_test_files_autogen.cmake', 'wb') as fout:
  215. fout.write(str.encode(cmake))
  216. def main():
  217. if len(sys.argv) != 2:
  218. print_usage()
  219. return 1
  220. diff_tool = sys.argv[1]
  221. if not os.path.exists(diff_tool):
  222. print("No such file: {}".format(diff_tool))
  223. print_usage()
  224. return 1
  225. diff_tool = os.path.realpath(diff_tool)
  226. os.chdir(os.path.dirname(__file__))
  227. test_names = sorted([f[:-11] for f in glob.glob("*_src.spvasm")])
  228. test_files = generate_tests(diff_tool, test_names)
  229. generate_cmake(test_files)
  230. return 0
  231. if __name__ == '__main__':
  232. sys.exit(main())