liveBook · Manning

Testing.T.Parallel

As explained in Learn Go with Pocket-Sized Projects

testing.T.Parallel marks a Go test so that it may execute in parallel with other parallel tests.

testing.T.Parallel marks a Go test as non-blocking, allowing it to run with other parallel tests in the same scope. Use it when independent tests can reduce runtime or when concurrent access should be exercised. section 7.3.2

Concurrent cache writes

Two subtests call t.Parallel() and write different values to the same cache index. Running the test with race detection can expose an unsafe concurrent implementation. section 7.3.2 section 7.6

Listing 7.10 Cooking example using t.Parallel()
func TestCache_Parallel(t *testing.T) {
    c := cache.New[int, string]() #1

    t.Run("write six", func(t *testing.T) {
        t.Parallel() #2
        c.Upsert(6, "six")
    })

    t.Run("write kuus", func(t *testing.T) {
        t.Parallel() #3
        c.Upsert(6, "kuus")
    })
}

Shows two parallel subtests operating on the same cache key, making the concurrency scenario concrete. section 7.3.2

Light tests are good candidates for parallel execution. Tests consuming substantial CPU, memory, disk, or network resources may be better kept sequential. section 7.4.1

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines same-scope scheduling and demonstrates subtests, but defers race diagnosis to the -race flag and synchronization design.
Examples
Demonstrates concurrent cache writes and a lightweight time-to-live cache test.
What it assumes
Assumes Go test functions, subtests, and cache operations while teaching the parallel-test marker from its scheduling behavior.
What you can do after
Apply it via Go's testing package to run suitable tests concurrently and combine it with -race for race detection.
How it connects
Connects parallel test execution with data races, subtests, mutexes, and the Go testing package.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.