How to pass test args in Skylark Bazel?

813 views Asked by At

I'm writing some bazel tests where I need to be able to provide the full path to some file.

bazel test //webservice:checkstyle-test --test_arg="path_to_some_file"

My question is how can you parse the input arguments in your bazel test? Is there anything like ctx.arg?

BUILD

load("//:checkstyle.bzl", "checkstyle_test")

checkstyle_test(
   name = ""
   src = []
   config = ""
)

checkstyle.bzl

def _checkstyle_test_impl(ctx):
    // How can I get my input parameter here? 

checkstyle_test = rule(
    implementation = _checkstyle_test_impl,
    test = True,
    attrs = {
        "_classpath": attr.label_list(default=[
            Label("@com_puppycrawl_tools_checkstyle//jar")
        ]),
        "config": attr.label(allow_single_file=True, default = "//config:checkstyle"),
        "suppressions": attr.label(allow_single_file=True, default = "//config:suppressions"),
        "license": attr.label(allow_single_file=True, default = "//config:license"),
        "properties": attr.label(allow_single_file=True),
        "opts": attr.string_list(),
        "string_opts": attr.string_dict(),
        "srcs": attr.label_list(allow_files = True),
        "deps": attr.label_list(),
    },
)
1

There are 1 answers

0
ahumesky On

The value of --test_arg is passed to the test executable as program arguments when bazel runs it during bazel test, see https://docs.bazel.build/versions/main/command-line-reference.html#flag--test_arg

For example:

def _impl(ctx):
  ctx.actions.write(
      output = ctx.outputs.executable,
      content = "echo test args: ; echo $@",
  )

my_test = rule(
  implementation = _impl,
  test = True,
)
load(":defs.bzl", "my_test")
my_test(name = "foo")
$ bazel test foo --test_arg=--abc=123 --test_output=streamed
WARNING: Streamed test output requested. All tests will be run locally, without sharding, one at a time
INFO: Analyzed target //:foo (24 packages loaded, 277 targets configured).
INFO: Found 1 test target...
test args:
--abc=123
Target //:foo up-to-date:
  bazel-bin/foo
INFO: Elapsed time: 0.559s, Critical Path: 0.13s
INFO: 5 processes: 3 internal, 2 linux-sandbox.
INFO: Build completed successfully, 5 total actions
//:foo                                                                   PASSED in 0.0s

Executed 1 out of 1 test: 1 test passes.
INFO: Build completed successfully, 5 total actions

I don't think there's currently a way to get the value of --test_arg in a Starlark rule implementation (it's not added under ctx.fragments for example).