pezpezpez
pezpezpez

Reputation: 694

Running go tests from root project folder

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?

Upvotes: 7

Views: 7415

Answers (3)

Daithí
Daithí

Reputation: 4079

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.

Upvotes: 1

Sharon Katz
Sharon Katz

Reputation: 1118

just running sudo go test -v ./... will probably fail because you probably do not have your root environment setup for GO just like you set the non-root env.

You can go and reset everything in the root, or do this easy step:

sudo -E go test -v ./...

This will run as root but keep your env settings.

Upvotes: 0

Elwinar
Elwinar

Reputation: 9509

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.

Upvotes: 8

Related Questions