Skip to content

Best way, if any, to include source files only for testing. #4166

Open
@mmonaco

Description

@mmonaco

What version of rules_go are you using?

0.48.0

What version of gazelle are you using?

0.37.0

What version of Bazel are you using?

7.2.0

Does this issue reproduce with the latest releases of all the above?

This is a question, not a bug.

What operating system and processor architecture are you using?

Linux, amd64

Question

I'm in the process of converting some packages to bazel. I've done the following in a few packages and I'm not sure the best way -- or if possible at all -- going forward.

// file: foo/foo.go
package foo

type Foo struct {}
func (f Foo) NormalMethod() {}
// file: foo/foo_testutil.go
//go:build testing
package foo

func (f Foo) TestOnlyMethod() {}
// file: foo/foo_test.go
package foo

import (
  "testing"
)

func TestFoo(t *testing.T) { ... }

I can build the above with go build and test with go test -tags=testing. I can make this work within the foo package:

go_library(
  name = "foo",
  srcs = ["foo.go"],
  importpath = "...",
)

go_library(
  name = "foo_testutil",
  testonly = True,
  srcs = ["foo_testutil.go"],
)

go_test(
  name = "foo_test",
  srcs = ["foo_test.go"],
  embed = [":foo", ":foo_testutil"],
  gotags = ["testing"],
)

What I can't get to work however are the the other packages which depend on foo and use the methods in foo_testutil.go in their own unit tests. Prior to bazel I just ran go test -tags=testing globally so any bar.go which imported foo didn't see the test-only methods and any bar_test.go which imported foo magically did see the test-only methods.

I've tried a few combinations of playing with importpath, separate instances of the go_library() for testing vs prod, embed, etc. I like this setup because it keeps Foo simple for its main production use while also adding a few handy features for testing (e.g., for modifying private fields).

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions