Skip to content

Commit ddd9f4d

Browse files
committed
chore(natpmp): fix determinism for test Test_Client_ExternalAddress
1 parent 7e58b4b commit ddd9f4d

2 files changed

Lines changed: 9 additions & 4 deletions

File tree

internal/natpmp/externaladdress_test.go

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package natpmp
22

33
import (
44
"context"
5+
"net"
56
"net/netip"
67
"testing"
78
"time"
@@ -23,14 +24,15 @@ func Test_Client_ExternalAddress(t *testing.T) {
2324
durationSinceStartOfEpoch time.Duration
2425
externalIPv4Address netip.Addr
2526
err error
26-
errMessage string
27+
errMessageRegex string
2728
}{
2829
"failure": {
2930
ctx: canceledCtx,
3031
gateway: netip.AddrFrom4([4]byte{127, 0, 0, 1}),
3132
initialConnDuration: initialConnectionDuration,
32-
err: context.Canceled,
33-
errMessage: "executing remote procedure call: reading from udp connection: context canceled",
33+
err: net.ErrClosed,
34+
errMessageRegex: "executing remote procedure call: setting connection deadline: " +
35+
"set udp 127.0.0.1:[1-9][0-9]{1,4}: use of closed network connection",
3436
},
3537
"success": {
3638
ctx: context.Background(),
@@ -60,7 +62,7 @@ func Test_Client_ExternalAddress(t *testing.T) {
6062
durationSinceStartOfEpoch, externalIPv4Address, err := client.ExternalAddress(testCase.ctx, testCase.gateway)
6163
assert.ErrorIs(t, err, testCase.err)
6264
if testCase.err != nil {
63-
assert.EqualError(t, err, testCase.errMessage)
65+
assert.Regexp(t, testCase.errMessageRegex, err.Error())
6466
}
6567
assert.Equal(t, testCase.durationSinceStartOfEpoch, durationSinceStartOfEpoch)
6668
assert.Equal(t, testCase.externalIPv4Address, externalIPv4Address)

internal/natpmp/rpc.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,8 +45,10 @@ func (c *Client) rpc(ctx context.Context, gateway netip.Addr,
4545
cancel()
4646
<-endGoroutineDone
4747
}()
48+
ctxListeningReady := make(chan struct{})
4849
go func() {
4950
defer close(endGoroutineDone)
51+
close(ctxListeningReady)
5052
// Context is canceled either by the parent context or
5153
// when this function returns.
5254
<-ctx.Done()
@@ -60,6 +62,7 @@ func (c *Client) rpc(ctx context.Context, gateway netip.Addr,
6062
}
6163
err = fmt.Errorf("%w; closing connection: %w", err, closeErr)
6264
}()
65+
<-ctxListeningReady // really to make unit testing reliable
6366

6467
const maxResponseSize = 16
6568
response = make([]byte, maxResponseSize)

0 commit comments

Comments
 (0)