|
21 | 21 | package fx_test
|
22 | 22 |
|
23 | 23 | import (
|
| 24 | + "context" |
| 25 | + "sync" |
24 | 26 | "testing"
|
25 | 27 |
|
26 | 28 | "github.com/stretchr/testify/assert"
|
| 29 | + "github.com/stretchr/testify/require" |
27 | 30 | "go.uber.org/fx"
|
28 | 31 | "go.uber.org/fx/fxtest"
|
29 | 32 | )
|
@@ -65,4 +68,62 @@ func TestShutdown(t *testing.T) {
|
65 | 68 | "unexpected error returned when shutdown is called with a blocked channel")
|
66 | 69 | assert.NotNil(t, <-done, "done channel did not receive signal")
|
67 | 70 | })
|
| 71 | + |
| 72 | + t.Run("shutdown app before calling Done()", func(t *testing.T) { |
| 73 | + t.Parallel() |
| 74 | + |
| 75 | + var s fx.Shutdowner |
| 76 | + app := fxtest.New( |
| 77 | + t, |
| 78 | + fx.Populate(&s), |
| 79 | + ) |
| 80 | + |
| 81 | + require.NoError(t, app.Start(context.Background()), "error starting app") |
| 82 | + assert.NoError(t, s.Shutdown(), "error in app shutdown") |
| 83 | + done1, done2 := app.Done(), app.Done() |
| 84 | + defer app.Stop(context.Background()) |
| 85 | + // Receiving on done1 and done2 will deadlock in the event that app.Done() |
| 86 | + // doesn't work as expected. |
| 87 | + assert.NotNil(t, <-done1, "done channel 1 did not receive signal") |
| 88 | + assert.NotNil(t, <-done2, "done channel 2 did not receive signal") |
| 89 | + }) |
| 90 | +} |
| 91 | + |
| 92 | +func TestDataRace(t *testing.T) { |
| 93 | + t.Parallel() |
| 94 | + |
| 95 | + var s fx.Shutdowner |
| 96 | + app := fxtest.New( |
| 97 | + t, |
| 98 | + fx.Populate(&s), |
| 99 | + ) |
| 100 | + require.NoError(t, app.Start(context.Background()), "error starting app") |
| 101 | + |
| 102 | + const N = 50 |
| 103 | + ready := make(chan struct{}) // used to orchestrate goroutines for Done() and ShutdownOption() |
| 104 | + var wg sync.WaitGroup // tracks and waits for all goroutines |
| 105 | + |
| 106 | + // Spawn N goroutines, each of which call app.Done() and assert |
| 107 | + // the signal received. |
| 108 | + wg.Add(N) |
| 109 | + for i := 0; i < N; i++ { |
| 110 | + i := i |
| 111 | + go func() { |
| 112 | + defer wg.Done() |
| 113 | + <-ready |
| 114 | + done := app.Done() |
| 115 | + assert.NotNil(t, <-done, "done channel %v did not receive signal", i) |
| 116 | + }() |
| 117 | + } |
| 118 | + |
| 119 | + // call Shutdown() |
| 120 | + wg.Add(1) |
| 121 | + go func() { |
| 122 | + <-ready |
| 123 | + defer wg.Done() |
| 124 | + assert.NoError(t, s.Shutdown(), "error in app shutdown") |
| 125 | + }() |
| 126 | + |
| 127 | + close(ready) |
| 128 | + wg.Wait() |
68 | 129 | }
|
0 commit comments