Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
mmonaco opened this issue Nov 7, 2024 · 0 comments
Open

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

mmonaco opened this issue Nov 7, 2024 · 0 comments

Comments

@mmonaco
Copy link

mmonaco commented Nov 7, 2024

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant