Search code examples
dockergointegration-testingbazelbazel-rules

Add Go Test binary to container_image using Bazel


I am building a go test package that I would like to have included in a Docker image. The binary can be built using bazel build //testing/e2e:e2e_test. This creates a binary in the bazel_bin folder. Now I would like to take this binary and add it to a docker image...

container_image(
    name = "image",
    base = "@alpine_linux_amd64//image",
    entrypoint = ["/e2e_test"],
    files = [":e2e_test"],
)

This gives me the following error

ERROR: ...BUILD.bazel:27:16: in container_image_ rule //testing/e2e:image: non-test target '//testing/e2e:image' depends on testonly target '//testing/e2e:e2e_test' and doesn't have testonly attribute set
ERROR: Analysis of target '//testing/e2e:image' failed; build aborted: Analysis of target '//testing/e2e:image' failed

Ultimately, what I am trying to accomplish is creating a application that contains a suite of end to end tests using the Go Test framework. I can then distribute these tests in a docker container to be run in testing environment.


Solution

  • The error is saying that a non-testonly target depends on a testonly one, which the docs for testonly say isn't allowed:

    If True, only testonly targets (such as tests) can depend on this target.

    Equivalently, a rule that is not testonly is not allowed to depend on any rule that is testonly.

    You can do what you're looking for by making your target testonly like this:

    container_image(
        name = "image",
        testonly = True,
        base = "@alpine_linux_amd64//image",
        entrypoint = ["/e2e_test"],
        files = [":e2e_test"],
    )