|
1 | 1 | package databasefake_test
|
2 | 2 |
|
3 | 3 | import (
|
| 4 | + "context" |
| 5 | + "database/sql" |
4 | 6 | "fmt"
|
5 | 7 | "reflect"
|
6 | 8 | "testing"
|
| 9 | + "time" |
| 10 | + |
| 11 | + "github.com/stretchr/testify/assert" |
7 | 12 |
|
8 | 13 | "github.com/coder/coder/coderd/database"
|
9 | 14 |
|
10 | 15 | "github.com/coder/coder/coderd/database/databasefake"
|
11 | 16 | )
|
12 | 17 |
|
| 18 | +// test that transactions don't deadlock, and that we don't see intermediate state. |
| 19 | +func TestInTx(t *testing.T) { |
| 20 | + t.Parallel() |
| 21 | + |
| 22 | + uut := databasefake.New() |
| 23 | + |
| 24 | + inTx := make(chan any) |
| 25 | + queriesDone := make(chan any) |
| 26 | + queriesStarted := make(chan any) |
| 27 | + go func() { |
| 28 | + err := uut.InTx(func(tx database.Store) error { |
| 29 | + close(inTx) |
| 30 | + _, err := tx.InsertOrganization(context.Background(), database.InsertOrganizationParams{ |
| 31 | + Name: "1", |
| 32 | + }) |
| 33 | + assert.NoError(t, err) |
| 34 | + <-queriesStarted |
| 35 | + time.Sleep(5 * time.Millisecond) |
| 36 | + _, err = tx.InsertOrganization(context.Background(), database.InsertOrganizationParams{ |
| 37 | + Name: "2", |
| 38 | + }) |
| 39 | + assert.NoError(t, err) |
| 40 | + return nil |
| 41 | + }) |
| 42 | + assert.NoError(t, err) |
| 43 | + }() |
| 44 | + var nums []int |
| 45 | + go func() { |
| 46 | + <-inTx |
| 47 | + for i := 0; i < 20; i++ { |
| 48 | + orgs, err := uut.GetOrganizations(context.Background()) |
| 49 | + if err != nil { |
| 50 | + assert.ErrorIs(t, err, sql.ErrNoRows) |
| 51 | + } |
| 52 | + nums = append(nums, len(orgs)) |
| 53 | + time.Sleep(time.Millisecond) |
| 54 | + } |
| 55 | + close(queriesDone) |
| 56 | + }() |
| 57 | + close(queriesStarted) |
| 58 | + <-queriesDone |
| 59 | + // ensure we never saw 1 org, only 0 or 2. |
| 60 | + for i := 0; i < 20; i++ { |
| 61 | + assert.NotEqual(t, 1, nums[i]) |
| 62 | + } |
| 63 | +} |
| 64 | + |
13 | 65 | // TestExactMethods will ensure the fake database does not hold onto excessive
|
14 | 66 | // functions. The fake database is a manual implementation, so it is possible
|
15 | 67 | // we forget to delete functions that we remove. This unit test just ensures
|
|
0 commit comments