rules.bzl 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. # Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. # Exceptions. See /LICENSE for license information.
  3. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. """Rules for building file tests.
  5. file_test uses the tests_as_input_file rule to transform test dependencies into
  6. a file which can be accessed as a list. This avoids long argument parsing.
  7. """
  8. load("@rules_cc//cc:defs.bzl", "cc_test")
  9. DataFilesInfo = provider(
  10. "Data files for this target.",
  11. fields = {
  12. "data_files": "Data files for this target",
  13. },
  14. )
  15. def _tests_as_input_file_rule_impl(ctx):
  16. data_files = []
  17. for tests in ctx.attr.data:
  18. data_files.extend(
  19. [f.path for f in tests[DefaultInfo].data_runfiles.files.to_list()],
  20. )
  21. data_files.extend(
  22. [f.path for f in tests[DefaultInfo].files.to_list()],
  23. )
  24. ctx.actions.write(ctx.outputs.data_files, "\n".join(data_files) + "\n")
  25. _tests_as_input_file_rule = rule(
  26. attrs = {
  27. "data": attr.label_list(allow_files = True),
  28. },
  29. outputs = {
  30. "data_files": "%{name}.txt",
  31. },
  32. implementation = _tests_as_input_file_rule_impl,
  33. )
  34. def file_test(
  35. name,
  36. tests,
  37. data = [],
  38. args = [],
  39. prebuilt_binary = None,
  40. **kwargs):
  41. """Generates tests using the file_test base.
  42. There will be one main test using `name` that can be sharded, and includes
  43. all files. Additionally, per-file tests will be generated as
  44. `name.file_path`; these per-file tests will be manual.
  45. Args:
  46. name: The base name of the tests.
  47. tests: The list of test files to use as data, typically a glob.
  48. data: Passed to cc_test.
  49. args: Passed to cc_test.
  50. prebuilt_binary: If set, specifies a prebuilt test binary to use instead
  51. of building a new one.
  52. **kwargs: Passed to cc_test.
  53. """
  54. # Ensure tests are always a filegroup for tests_as_input_file_rule.
  55. tests_file = "{0}.tests".format(name)
  56. _tests_as_input_file_rule(
  57. name = tests_file,
  58. data = tests,
  59. testonly = 1,
  60. )
  61. args = ["--test_targets_file=$(rootpath :{0})".format(tests_file)] + args
  62. data = [tests_file] + tests + data
  63. if prebuilt_binary:
  64. native.sh_test(
  65. name = name,
  66. srcs = [prebuilt_binary],
  67. data = data,
  68. args = args,
  69. **kwargs
  70. )
  71. else:
  72. cc_test(
  73. name = name,
  74. data = data,
  75. args = args,
  76. **kwargs
  77. )