Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I package golang test helper code?

Tags:

testing

go

I have some test helper code in my golang library that I want to use when testing in various subpackages. However, I've hit a snag:

outer
|
+- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

To use the code in test_helpers_test.go, I have to import the outer package. But when I import the outer package from something_test.go, it complains "import cycle not allowed in test"

So I tried making a package for the shared test helpers:

outer
|
+- test
|  |
|  +- test_helpers_test.go
|
+- inner
   |
   +- something.go
   +- something_test.go

And now it complains "no non-test Go files in /home/karl/Projects/outer/test"

I don't want to call it test_helpers.go because it's part of my testing code, not my library code. I don't want to ship that code in the library.

How do I solve this?


Update: I can work around the issue by creating a dummy.go file in the test directory, but now there's a new problem: Importing a package DOESN'T import its test code! So now I get: ./something_test.go:12:2: undefined: test.AssertDoesPanic

like image 558
Karl Avatar asked Jun 01 '19 06:06

Karl


People also ask

What does T helper do Golang?

Note: The t. Helper() function indicates to the Go test runner that our Equal() function is a test helper. This means that when t. Errorf() is called from our Equal() function, the Go test runner will report the filename and line number of the code which called our Equal() function in the output.

How do I run a single test file in Golang?

Use the go test -run flag to run a specific test. The flag is documented in the testing flags section of the go tool documentation: -run regexp Run only those tests and examples matching the regular expression.


2 Answers

You are right that you cannot import test code from another package so your helper functions have to go into proper code files rather than test files.

If it isn't imported from your non-test code then it won't be built into the final binary.

Authors tend to call the package ...test to indicate it is just test helpers, for instance httptest from the standard library or zaptest from open source.

https://golang.org/pkg/net/http/httptest/ https://godoc.org/go.uber.org/zap/zaptest

like image 189
Iain Duncan Avatar answered Oct 09 '22 03:10

Iain Duncan


Following go issue 8279, I have seen dummy files added, as in tommie/acme-cli commit 479f8c7

outer/outer.go

// +build ignore+
package outer

See if that could help here, as a workaround.


As commented above, using a test helper code in an internal package (from Go 1.4+) is another option, since no client from this project would be able to access said helper. See design document.
You can see it used in a typical Go project layout.

like image 2
VonC Avatar answered Oct 09 '22 03:10

VonC