How to make sh_test depend on building docker image?

Viewed 280

I have a sh_test invoking docker run my_image where my_image is produced by a container_bundle rule. I need the container_bundle rule to be run as dependency to sh_test. How to achieve that? Adding container_bundle to sh_test's data only invokes container_bundle build, but I need run which pushes an image to a docker registry.

2 Answers

What we do is pass the rootpath of the container image rule to the script (as $IMAGE_LOADER) and do:

$IMAGE_LOADER --norun | tee image-loader.log
IMAGE_ID=$(cat ./image-loader.log | grep "Loaded image ID" | cut -d":" -f2-)

The easiest way I know is wrapping a docker_push rule around your bundle. Then your test rule can run the docker_push's output file, which is a binary that will do the docker load. Use runfiles.bash to get its full path.

Something like this:

# --- begin runfiles.bash initialization v2 ---
# Copy-pasted from the Bazel Bash runfiles library v2.
set -uo pipefail; f=bazel_tools/tools/bash/runfiles/runfiles.bash
source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \
  source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \
  source "$0.runfiles/$f" 2>/dev/null || \
  source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
  source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
  { echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e
 # --- end runfiles.bash initialization v2 ---

$(rlocation "my_workspace/some/package/my_container_push")

With some/package/BUILD having this:

load("@io_bazel_rules_docker//contrib:push-all.bzl", "docker_push")
load("@io_bazel_rules_docker//container:container.bzl", "container_bundle")

container_bundle(
    name = "my_container_bundle",
    # All your existing attrs here, etc etc.
)

docker_push(
    name = "my_container_push",
    bundle = ":my_container_bundle",
)

sh_test(
    name = "my_test",
    data = [
        ":my_container_push",
    ],
    deps = [
        "@bazel_tools//tools/bash/runfiles",
    ],
)
Related