I have to take over a go project from a colleague and I've never touched Go before and it doesn't have tests so I've started to add them but I cannot run them.
The go command for running tests is go test but it doesn't seem to run at the root level.
My project structure is:
/project/main.go
/project/engine/*.go
/project/api/*.go
If I cd into either engine or api, and run go test it works but not in the root folder.
cd /project
go test
? /project [no test files]
Is there anyway to run all tests from the root?
You can use the ... (ellipsis) operator to test all subpackages of the current package. Like that: go test ./....
There are other solutions that you might want to try later if you do something more sophisticated, like using the list tool. Like that (for example): go test $(go list ./... | grep [regex]). That's useful to exclude the vendor directory from your tests.
Another thing you may want to know about is the gt command that can be found here https://godoc.org/rsc.io/gt and add caching to the go test command.
Finally, don't hesitate to read https://blog.golang.org/cover to get informations about code-coverage analysis in golang.
I find this irritating that go test ./... when run from project root will actually run from pkg/pkg_name/ folder. There is a way you can set the tests to project root by setting cwd in the init() helper function.
I found the solution here You could try the following snippet in your _file:
func init() {
_, filename, _, _ := runtime.Caller(0)
dir := path.Join(path.Dir(filename), "../..") // change to suit test file location
err := os.Chdir(dir)
if err != nil {
panic(err)
}
}
This snippet above works for my tests in pkg/$name/$name_test.go.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With