I have couple of packages and their unit tests. Each unit test opens a port and listens on it. Sequential running those tests result in port in use
errors.
What I need is something similar to static
variable in C++. One counter variable which will preserve its value in each unit test call. I will open subsequent ports for each unit test.
I'm doing this for opening subsequent ports for Nomad. They already use it in their codebase (https://github.com/hashicorp/nomad/blob/master/testutil/server.go#L30) however offset is not preserved at each unit test.
Here is sample code to reproduce the issue:
A.go
package a
var Offset uint64
A_test.go
package a
import "testing"
func TestVar(t *testing.T) {
Offset = Offset + 1
t.Log(Offset)
}
B_test.go
package b
import (
"testing"
"github.com/test/test/a"
)
func TestVar(t *testing.T) {
a.Offset = a.Offset + 1
t.Log(a.Offset)
}
Run tests:
$ go test -v ./...
=== RUN TestVar
--- PASS: TestVar (0.00s)
A_test.go:7: 1
PASS
ok github.com/test/test/a 0.005s
=== RUN TestVar
--- PASS: TestVar (0.00s)
B_test.go:11: 1
PASS
ok github.com/test/test/b 0.007s