Skip to content

Commit 5ccba5d

Browse files
GODRIVER-3444 Add tests for CalculateMaxTimeMS
1 parent 34dff0f commit 5ccba5d

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package driverutil
2+
3+
import (
4+
"context"
5+
"math"
6+
"testing"
7+
"time"
8+
9+
"go.mongodb.org/mongo-driver/v2/internal/assert"
10+
)
11+
12+
//nolint:govet
13+
func TestCalculateMaxTimeMS(t *testing.T) {
14+
tests := []struct {
15+
name string
16+
ctx context.Context
17+
rttMin time.Duration
18+
wantZero bool
19+
wantOk bool
20+
wantPositive bool
21+
wantExact int64
22+
}{
23+
{
24+
name: "no deadline",
25+
ctx: context.Background(),
26+
rttMin: 10 * time.Millisecond,
27+
wantZero: true,
28+
wantOk: true,
29+
wantPositive: false,
30+
},
31+
{
32+
name: "deadline expired",
33+
ctx: func() context.Context {
34+
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(-1*time.Second)) //nolint:govet
35+
return ctx
36+
}(),
37+
wantZero: true,
38+
wantOk: false,
39+
wantPositive: false,
40+
},
41+
{
42+
name: "remaining timeout < rttMin",
43+
ctx: func() context.Context {
44+
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(1*time.Millisecond))
45+
return ctx
46+
}(),
47+
rttMin: 10 * time.Millisecond,
48+
wantZero: true,
49+
wantOk: false,
50+
wantPositive: false,
51+
},
52+
{
53+
name: "normal positive result",
54+
ctx: func() context.Context {
55+
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(100*time.Millisecond))
56+
return ctx
57+
}(),
58+
wantZero: false,
59+
wantOk: true,
60+
wantPositive: true,
61+
},
62+
{
63+
name: "beyond maxInt32",
64+
ctx: func() context.Context {
65+
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(time.Duration(math.MaxInt32+1000)*time.Millisecond))
66+
return ctx
67+
}(),
68+
wantZero: true,
69+
wantOk: true,
70+
wantPositive: false,
71+
},
72+
{
73+
name: "round up to 1ms",
74+
ctx: func() context.Context {
75+
ctx, _ := context.WithDeadline(context.Background(), time.Now().Add(999*time.Microsecond))
76+
return ctx
77+
}(),
78+
wantOk: true,
79+
wantExact: 1,
80+
},
81+
}
82+
83+
for _, tt := range tests {
84+
t.Run(tt.name, func(t *testing.T) {
85+
got, got1 := CalculateMaxTimeMS(tt.ctx, tt.rttMin)
86+
87+
assert.Equal(t, tt.wantOk, got1)
88+
89+
if tt.wantExact > 0 && got != tt.wantExact {
90+
t.Errorf("CalculateMaxTimeMS() got = %v, want %v", got, tt.wantExact)
91+
}
92+
93+
if tt.wantZero && got != 0 {
94+
t.Errorf("CalculateMaxTimeMS() got = %v, want 0", got)
95+
}
96+
97+
if !tt.wantZero && got == 0 {
98+
t.Errorf("CalculateMaxTimeMS() got = %v, want > 0", got)
99+
}
100+
101+
if !tt.wantZero && tt.wantPositive && got <= 0 {
102+
t.Errorf("CalculateMaxTimeMS() got = %v, want > 0", got)
103+
}
104+
})
105+
}
106+
107+
}

0 commit comments

Comments
 (0)