Reputation: 6980
Below is my project structure:
/user/home/go/src/github.com/my_go_proj /main.go /mypackage /service.go /service_test.go GOPATH points to /user/home/go cd /user/home/go/src/github.com/my_go_proj go build ---> This works and creates the `my_go_proj` executable. go test ? github.com/my_go_proj [no test files] go test github.com/my_go_proj/mypackage go build gopkg.in/tomb.v2: no buildable Go source files in FAIL github.com/my_go_proj/mypackage [build failed] go test ./... ? github.com/my_go_proj [no test files] go build gopkg.in/tomb.v2: no buildable Go source files in FAIL github.com/my_go_proj/mypackage [build failed]
How do I run go test
to run the service_test.go test inside mypackage?
Update: updated the behaviour for go test ./...
Upvotes: 10
Views: 10454
Reputation: 5659
Let's have the answer to the title question of "go build
works but go test
doesn't", since I think many people get here because of that title and not of their directory structure.
What happens is that go-build
and go-test
may have different compilation options. For example, a go-build
may tolerate warnings but go-test
doesn't.
The problem here is that in a typical project you have many tests (so typically inside your build system such as Meson or Make you have a call go test […list of tests goes here…]
). In which case the warning prints may appear at the wrong location, such as at the beginning of the go-test
. So you will see a wall of text (especially if you added a -v
), but the actual error will not be inside the text group relevant to the failing test.
What you can do here (besides of course peeking at the beginning of the log now that you know the problem) is you can run go test go-specific-path/to/test
, which will only run that test alone so you will definitely see what's failing.
So, given the OP's case: instead of running go test […list of tests goes here…]
just run that one test:
go test github.com/my_go_proj/mypackage
go build gopkg.in/tomb.v2: no buildable Go source files in
FAIL github.com/my_go_proj/mypackage [build failed]
Upvotes: 1
Reputation: 6980
The problem was with the directory structure. My project source should be in $GOPATH
. But it was inside $GOPATH/src
.
Incorrect /user/home/go/src/github.com/my_go_proj
Correct /user/home/go/github.com/my_go_proj
Upvotes: 0
Reputation: 461237
To test all subdirectories use:
$ go test ./...
From the Relative import paths section of the Command go documentation:
Relative patterns are also allowed, like
go test ./...
to test all subdirectories. See 'go help packages' for details on the pattern syntax.
Upvotes: 1