DEV Community

Cover image for The Ultimate Guide to Parallel Testing in Go: -p, -parallel, and t.Parallel() Demystified
Emil Valeev
Emil Valeev

Posted on

The Ultimate Guide to Parallel Testing in Go: -p, -parallel, and t.Parallel() Demystified

Go has three ways to tweak parallelism in tests:

  • -p flag
  • -parallel flag
  • t.Parallel() function call

How many of you know what they do? Why do we need all three? :slight_smile:

It turns out -p controls "how many test packages can run in parallel," -parallel determines "how many test functions inside a single test package can run in parallel," and finally, t.Parallel() marks a test function, telling Go that it can be run in parallel with other functions in the same package.

Example 1

Example: Let's say we have 999 packages with 999 test functions each, but not a single test function uses t.Parallel(). What will happen?

Answer: N test packages will run in parallel (where N equals the number of CPU cores), but each package will run its test functions sequentially. So, N test functions will run in parallel.

Example 2

Another example: same scenario, but we add -p 1. What will happen?

Answer: completely sequential execution.

Example 3

One more example: same as before, but this time we add t.Parallel(). Well, t.Parallel() combined with -p 1 results in "only one package runs at a time, but N test functions run in parallel," where N is again the number of CPU cores.

Conclusion

The most fine-grained control is achieved using all three: -p X -parallel Y and t.Parallel().

We need to be careful with stateful tests (as usual, state is the root of all evil, but it's impossible to avoid).

The Neva Programming Language

Go developer? Check out Nevalang - it's a work-in-progress programming language built on top of Go, that fixes some of Go's issues such as data-races, nil pointer-dereference, etc. In 2025 it will have visual editor, Rust-like enums and much more. Eventually you will be able to call it from Go and vice-versa.

Image description

Interested? Give us a star and join our community. We need developers (not just gophers!) to contribute and test the language. Let's change programming together - Go is awesome but we can do even better:

Top comments (0)