From db0ec2f829ee8540edeafea26e936e096c41533b Mon Sep 17 00:00:00 2001 From: Filip Filmar Date: Wed, 13 Mar 2019 01:21:47 -0700 Subject: [PATCH] Improves the flexibility of bats_test - Added the "env" dict to pass in environment variables. - Added a test that verifies passing of env vars. - Removed leftover printf debugging. --- rules.bzl | 23 ++++++++++------------- tests/BUILD.bazel | 4 ++++ tests/hello_world.bats | 4 ++++ 3 files changed, 18 insertions(+), 13 deletions(-) diff --git a/rules.bzl b/rules.bzl index e873069..7a0dec9 100644 --- a/rules.bzl +++ b/rules.bzl @@ -11,9 +11,10 @@ def _bats_test_impl(ctx): files = ctx.files.srcs, collect_data = True, ) - tests = ["\"{}\"".format(f.short_path) for f in ctx.files.srcs] path = ["$PWD/" + _dirname(b.short_path) for b in ctx.files.deps] + l = ['export {}="{}"'.format(key, val) for key, val in ctx.attr.env.items()] + env = "\n".join(l) sep = ctx.configuration.host_path_separator @@ -21,41 +22,37 @@ def _bats_test_impl(ctx): set -e export TMPDIR="$TEST_TMPDIR" export PATH="{bats_bins_path}":$PATH +{env} "{bats}" {test_paths} """ - - - print("path={path}; tests={tests}; bats={bats}".format( - path=path, - tests=tests, - bats=ctx.executable._bats.short_path, - )) content = BASH_TEMPLATE.format( bats = ctx.executable._bats.short_path, - test_paths = " ".join(tests), bats_bins_path = sep.join(path), + env=env, + test_paths = " ".join(tests), ) ctx.file_action( output = ctx.outputs.executable, executable = True, content = content, ) - runfiles = runfiles.merge(ctx.attr._bats.default_runfiles) - print("runfiles={runfiles}".format(runfiles=runfiles)) - return DefaultInfo( runfiles = runfiles, ) + bats_test = rule( _bats_test_impl, attrs = { + "deps": attr.label_list(), + "env": attr.string_dict( + doc = "A list of key-value pairs of environment variables to define", + ), "srcs": attr.label_list( allow_files = [".bats"], doc = "Source files to run a bats test on", ), - "deps": attr.label_list(), "_bats": attr.label( default = Label("@bats_core//:bats"), executable = True, diff --git a/tests/BUILD.bazel b/tests/BUILD.bazel index ef897ae..4607965 100644 --- a/tests/BUILD.bazel +++ b/tests/BUILD.bazel @@ -3,6 +3,9 @@ load("@bazel_bats//:rules.bzl", "bats_test") bats_test( name = "hello_world_test", srcs = ["hello_world.bats"], + env = { + "PROGRAM": "hello_world", + }, ) bats_test( @@ -26,3 +29,4 @@ bats_test( "hello_world_2.bats", ], ) + diff --git a/tests/hello_world.bats b/tests/hello_world.bats index d01303b..e452d9c 100644 --- a/tests/hello_world.bats +++ b/tests/hello_world.bats @@ -5,3 +5,7 @@ [ "$result" -eq 4 ] } +@test "Test program name" { + [ "${PROGRAM}" == "hello_world" ] +} +