How do I skip a tests file if it is run on systems with go 1.4 and below?


I have a file containing some tests that should be run on Go 1.5+.

I am able to get the Go runtime version using runtime.Version() and doing various comparisons.

However, the test file imports The http2 package requires request.Cancel() from net/http, but that is only available on Go 1.5+.

That causes these errors in my CI environment causing the build to fail:

../../../ req.Cancel undefined (type *http.Request has no field or method Cancel)
../../../ req.Cancel undefined (type *http.Request has no field or method Cancel)
../../../ req.Cancel undefined (type *http.Request has no field or method Cancel)

I tried adding // +build go1.5 to the top of the file, but it didn’t work.

Is there anyway I can limit a unit test file so that it is built and tested only on Go 1.5+ systems?


The build constraints is the proper way to do it.

But note that your error messages refer to the http2 package which was added in Go 1.6, so you need at least go1.6 build constraint.

The build constraint

// +build go1.5

Will cause the file to be compiled with Go 1.5 and onward. So if you want your test file to only compile and run with Go 1.6 and above, then use

// +build go1.6

Also don’t forget that:

Constraints may appear in any kind of source file (not just Go), but they must appear near the top of the file, preceded only by blank lines and other line comments. These rules mean that in Go files a build constraint must appear before the package clause.

To distinguish build constraints from package documentation, a series of build constraints must be followed by a blank line.

A working example:

1  // +build go1.6
3  package yourpackage

Answered By – icza

Answer Checked By – Candace Johnson (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.