rules.bzl 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. def _tests_as_input_file_rule_impl(ctx):
  10. out = ctx.actions.declare_file(ctx.label.name + ".txt")
  11. data_files = []
  12. for tests in ctx.attr.data:
  13. data_files.extend(
  14. [f.path for f in tests[DefaultInfo].data_runfiles.files.to_list()],
  15. )
  16. data_files.extend(
  17. [f.path for f in tests[DefaultInfo].files.to_list()],
  18. )
  19. ctx.actions.write(out, "\n".join(data_files) + "\n")
  20. return [DefaultInfo(files = depset([out]))]
  21. _tests_as_input_file_rule = rule(
  22. attrs = {
  23. "data": attr.label_list(allow_files = True),
  24. },
  25. implementation = _tests_as_input_file_rule_impl,
  26. )
  27. def file_test(
  28. name,
  29. tests,
  30. data = [],
  31. args = [],
  32. prebuilt_binary = None,
  33. **kwargs):
  34. """Generates tests using the file_test base.
  35. There will be one main test using `name` that can be sharded, and includes
  36. all files. Additionally, per-file tests will be generated as
  37. `name.file_path`; these per-file tests will be manual.
  38. Args:
  39. name: The base name of the tests.
  40. tests: The list of test files to use as data, typically a glob.
  41. data: Passed to cc_test.
  42. args: Passed to cc_test.
  43. prebuilt_binary: If set, specifies a prebuilt test binary to use instead
  44. of building a new one.
  45. **kwargs: Passed to cc_test.
  46. """
  47. # Ensure tests are always a filegroup for tests_as_input_file_rule.
  48. tests_file = "{0}.tests".format(name)
  49. _tests_as_input_file_rule(
  50. name = tests_file,
  51. data = tests,
  52. testonly = 1,
  53. )
  54. args = ["--test_targets_file=$(rootpath :{0})".format(tests_file)] + args
  55. data = [":" + tests_file] + tests + data
  56. if prebuilt_binary:
  57. native.sh_test(
  58. name = name,
  59. srcs = [prebuilt_binary],
  60. data = data,
  61. args = args,
  62. **kwargs
  63. )
  64. else:
  65. cc_test(
  66. name = name,
  67. data = data,
  68. args = args,
  69. **kwargs
  70. )