| 1 | package agent |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "sync" |
| 7 | "testing" |
| 8 | ) |
| 9 | |
| 10 | type identifiedGate struct { |
| 11 | id int |
| 12 | } |
| 13 | |
| 14 | func (*identifiedGate) Check(context.Context, string, json.RawMessage, bool) (bool, string, error) { |
| 15 | return true, "", nil |
| 16 | } |
| 17 | |
| 18 | func TestAgentServicesGateSwapIsRaceSafe(t *testing.T) { |
| 19 | first := &identifiedGate{id: 1} |
| 20 | second := &identifiedGate{id: 2} |
| 21 | services := agentServices{gate: first} |
| 22 | |
| 23 | start := make(chan struct{}) |
| 24 | var wg sync.WaitGroup |
| 25 | wg.Add(9) |
| 26 | go func() { |
| 27 | defer wg.Done() |
| 28 | <-start |
| 29 | for i := range 10_000 { |
| 30 | if i%2 == 0 { |
| 31 | services.setGate(second) |
| 32 | } else { |
| 33 | services.setGate(first) |
| 34 | } |
| 35 | } |
| 36 | }() |
| 37 | for range 8 { |
| 38 | go func() { |
| 39 | defer wg.Done() |
| 40 | <-start |
| 41 | for range 10_000 { |
| 42 | got := services.gateSnapshot() |
| 43 | if got != first && got != second { |
| 44 | t.Errorf("gate snapshot = %#v, want one complete installed gate", got) |
| 45 | return |
| 46 | } |
| 47 | } |
| 48 | }() |
| 49 | } |
| 50 | close(start) |
| 51 | wg.Wait() |
| 52 | } |
| 53 |