Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 golang.org/x/net/http2. 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:

../../../golang.org/x/net/http2/transport.go:214: req.Cancel undefined (type *http.Request has no field or method Cancel)
../../../golang.org/x/net/http2/transport.go:218: req.Cancel undefined (type *http.Request has no field or method Cancel)
../../../golang.org/x/net/http2/transport.go:777: 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?

like image 324
F21 Avatar asked Jun 02 '16 08:06

F21


1 Answers

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
2
3  package yourpackage
like image 77
icza Avatar answered Nov 15 '22 08:11

icza