bazel-contrib / bazel-contrib/rules_go

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

Open
#4,166 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
1.5k
Forks
760
Avg merge
1d 11h
Merged PRs (30d)
12

Description

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

Contributor guide

Open the contributing guide

Research direction

Start with foo.go, foo_testutil.go, foo_test.go, and the shown go_library/go_test targets. Read how rules_go handles gotags, testonly libraries, embed, and cross-package test dependencies, then reproduce the setup with a dependent bar package. Done means a supported configuration lets bar tests use Foo's test-only methods without exposing them to production builds.

Written by the indexing model from the issue text.

Assessment

Tech stack
go
Domain
build-system, testing
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.