Skip to content

Commit c775ea8

Browse files
authored
test: fix a race in TestReinit (#17902)
closes coder/internal#632 `pubsubReinitSpy` used to signal that a subscription had happened before it actually had. This created a slight opportunity for the main goroutine to publish before the actual subscription was listening. The published event was then dropped, leading to a failed test.
1 parent 1a41608 commit c775ea8

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

coderd/workspaceagents_test.go

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -2650,8 +2650,8 @@ func TestReinit(t *testing.T) {
26502650

26512651
db, ps := dbtestutil.NewDB(t)
26522652
pubsubSpy := pubsubReinitSpy{
2653-
Pubsub: ps,
2654-
subscribed: make(chan string),
2653+
Pubsub: ps,
2654+
triedToSubscribe: make(chan string),
26552655
}
26562656
client := coderdtest.New(t, &coderdtest.Options{
26572657
Database: db,
@@ -2664,9 +2664,9 @@ func TestReinit(t *testing.T) {
26642664
OwnerID: user.UserID,
26652665
}).WithAgent().Do()
26662666

2667-
pubsubSpy.Mutex.Lock()
2667+
pubsubSpy.Lock()
26682668
pubsubSpy.expectedEvent = agentsdk.PrebuildClaimedChannel(r.Workspace.ID)
2669-
pubsubSpy.Mutex.Unlock()
2669+
pubsubSpy.Unlock()
26702670

26712671
agentCtx := testutil.Context(t, testutil.WaitShort)
26722672
agentClient := agentsdk.New(client.URL)
@@ -2681,7 +2681,7 @@ func TestReinit(t *testing.T) {
26812681

26822682
// We need to subscribe before we publish, lest we miss the event
26832683
ctx := testutil.Context(t, testutil.WaitShort)
2684-
testutil.TryReceive(ctx, t, pubsubSpy.subscribed) // Wait for the appropriate subscription
2684+
testutil.TryReceive(ctx, t, pubsubSpy.triedToSubscribe)
26852685

26862686
// Now that we're subscribed, publish the event
26872687
err := prebuilds.NewPubsubWorkspaceClaimPublisher(ps).PublishWorkspaceClaim(agentsdk.ReinitializationEvent{
@@ -2699,15 +2699,16 @@ func TestReinit(t *testing.T) {
26992699
type pubsubReinitSpy struct {
27002700
pubsub.Pubsub
27012701
sync.Mutex
2702-
subscribed chan string
2703-
expectedEvent string
2702+
triedToSubscribe chan string
2703+
expectedEvent string
27042704
}
27052705

27062706
func (p *pubsubReinitSpy) Subscribe(event string, listener pubsub.Listener) (cancel func(), err error) {
2707+
cancel, err = p.Pubsub.Subscribe(event, listener)
27072708
p.Lock()
27082709
if p.expectedEvent != "" && event == p.expectedEvent {
2709-
close(p.subscribed)
2710+
close(p.triedToSubscribe)
27102711
}
27112712
p.Unlock()
2712-
return p.Pubsub.Subscribe(event, listener)
2713+
return cancel, err
27132714
}

0 commit comments

Comments
 (0)