Skip to content

Commit

Permalink
Improves the flexibility of bats_test
Browse files Browse the repository at this point in the history
- Added the "env" dict to pass in environment variables.

- Added a test that verifies passing of env vars.

- Removed leftover printf debugging.
  • Loading branch information
filmil committed Mar 13, 2019
1 parent 1679441 commit db0ec2f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 13 deletions.
23 changes: 10 additions & 13 deletions rules.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -11,51 +11,48 @@ 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

BASH_TEMPLATE = """#!/usr/bin/env bash
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,
Expand Down
4 changes: 4 additions & 0 deletions tests/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -26,3 +29,4 @@ bats_test(
"hello_world_2.bats",
],
)

4 changes: 4 additions & 0 deletions tests/hello_world.bats
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@
[ "$result" -eq 4 ]
}

@test "Test program name" {
[ "${PROGRAM}" == "hello_world" ]
}

0 comments on commit db0ec2f

Please sign in to comment.