|
| 1 | +# paralleltestctx |
| 2 | + |
| 3 | +A Go static analysis tool that warns when contexts with a deadline are used in |
| 4 | +parallel subtests. |
| 5 | + |
| 6 | +## Problem |
| 7 | + |
| 8 | +See [our blog post](https://coder.com/blog/go-testing-contexts-and-t-parallel) |
| 9 | +for an in-depth explanation of the problem. |
| 10 | + |
| 11 | +## Usage |
| 12 | + |
| 13 | +```bash |
| 14 | +go run github.com/coder/paralleltestctx/cmd/paralleltestctx@latest ./... |
| 15 | +``` |
| 16 | + |
| 17 | +### Custom functions that produce contexts with timeouts |
| 18 | + |
| 19 | +By default, the linter detects `context.WithTimeout` and `context.WithDeadline` |
| 20 | +as producing contexts with timeouts or deadlines. Additional functions that |
| 21 | +create a context with a deadline or timeout can be specified using the |
| 22 | +`-custom-funcs` flag. |
| 23 | + |
| 24 | +```bash |
| 25 | +go run github.com/coder/paralleltestctx/cmd/paralleltestctx@latest -custom-funcs="testutil.Context" ./... |
| 26 | +``` |
| 27 | + |
| 28 | +## Examples |
| 29 | + |
| 30 | +### ❌ Potentially flakey test |
| 31 | + |
| 32 | +```go |
| 33 | +func TestBad(t *testing.T) { |
| 34 | + ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond) |
| 35 | + defer cancel() |
| 36 | + // WARNING: do not do this! |
| 37 | + t.Parallel() |
| 38 | + |
| 39 | + uut := newUnitUnderTest() |
| 40 | + // Danger! Context may have timed out by this point |
| 41 | + writeCtx(ctx, t, uut.Input, 5) |
| 42 | + output := readCtx(ctx, t, uut.Output) |
| 43 | + if output != 25 { |
| 44 | + t.Errorf("expected 25 got %d", output) |
| 45 | + } |
| 46 | +} |
| 47 | +``` |
| 48 | + |
| 49 | +### ❌ Potentially flakey parallel subtest |
| 50 | + |
| 51 | +```go |
| 52 | +func TestBad(t *testing.T) { |
| 53 | + t.Parallel() |
| 54 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second * 5) |
| 55 | + t.Cleanup(cancel) |
| 56 | + t.Run("sub", func(t *testing.T) { |
| 57 | + t.Parallel() |
| 58 | + // Danger! Context may have timed out by this point |
| 59 | + doSomething(ctx) // Warning: timeout context used after t.Parallel call |
| 60 | + }) |
| 61 | +} |
| 62 | +``` |
| 63 | + |
| 64 | +### ✅ Fixed test - create a new context |
| 65 | + |
| 66 | +```go |
| 67 | +func TestGood(t *testing.T) { |
| 68 | + t.Parallel() |
| 69 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second * 5) |
| 70 | + t.Cleanup(cancel) |
| 71 | + t.Run("sub", func(t *testing.T) { |
| 72 | + t.Parallel() |
| 73 | + // We're shadowing the parent context with a new deadline, so this is fine |
| 74 | + ctx, cancel := context.WithTimeout(context.Background(), time.Second * 5) |
| 75 | + t.Cleanup(cancel) |
| 76 | + doSomething(ctx) |
| 77 | + }) |
| 78 | +} |
| 79 | +``` |
| 80 | + |
| 81 | +## License |
| 82 | + |
| 83 | +This project is licensed under the MIT License - see the [LICENSE](LICENSE) file |
| 84 | +for details. |
0 commit comments