2

If I have different packages and each have a test file (pkg_test.go) is there a way for me to make sure that they run in a particular order ?

Say pkg1_test.go gets executed first and then the rest.

I tried using go channels but it seems to hang.

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
kbinstance
  • 346
  • 5
  • 17

2 Answers2

1

It isn't obvious, considering a go test ./... triggers test on all packages... but runs in parallel: see "Go: how to run tests for multiple packages?".

go test -p 1 would run the tests sequentially, but not necessarily in the order you would need.

A simple script calling go test on the packages listed in the right expected order would be easier to do.


Update 6 years later: the best practice is to not rely on test order.
So much so issue 28592 advocates for adding -shuffle and -shuffleseed to shuffle tests.

CL 310033 mentions:

This CL adds a new flag to the testing package and the go test command which randomizes the execution order for tests and benchmarks.

This can be useful for identifying unwanted dependencies between test or benchmark functions.

The flag is off by default.

  • If -shuffle is set to on then the system clock will be used as the seed value.
  • If -shuffle is set to an integer N, then N will be used as the seed value.

In both cases, the seed will be reported for failed runs so that they can reproduced later on.

Picked up for Go 1.17 (Aug. 2021) in commit cbb3f09.

See more at "Benchmarking with Go".

VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
0

I found a hack to get around this. I named my test files as follow:

A_{test_file1}_test.go
B_{test_file2}_test.go
C_{test_file3}_test.go

The A B C will ensure they are run in order.