77package mongoutil
88
99import (
10+ "context"
1011 "strings"
1112 "testing"
13+ "time"
1214
15+ "go.mongodb.org/mongo-driver/v2/internal/assert"
16+ "go.mongodb.org/mongo-driver/v2/internal/ptrutil"
1317 "go.mongodb.org/mongo-driver/v2/mongo/options"
1418)
1519
@@ -32,3 +36,77 @@ func BenchmarkNewOptions(b *testing.B) {
3236 }
3337 })
3438}
39+
40+ func TestValidChangeStreamTimeouts (t * testing.T ) {
41+ tests := []struct {
42+ name string
43+ ctxTimeout * time.Duration
44+ timeout time.Duration
45+ wantTimeout time.Duration
46+ want bool
47+ }{
48+ {
49+ name : "No timeout provided, no context deadline" ,
50+ ctxTimeout : nil ,
51+ timeout : nil ,
52+ want : true ,
53+ },
54+ {
55+ name : "Timeout shorter than context deadline" ,
56+ ctxTimeout : ptrutil .Ptr (10 * time .Second ),
57+ timeout : 1 * time .Second ,
58+ want : true ,
59+ },
60+ {
61+ name : "Timeout equal to context deadline" ,
62+ ctxTimeout : ptrutil .Ptr (1 * time .Second ),
63+ timeout : 1 * time .Second ,
64+ want : false ,
65+ },
66+ {
67+ name : "Timeout greater than context deadline" ,
68+ ctxTimeout : ptrutil .Ptr (1 * time .Second ),
69+ timeout : 10 * time .Second ,
70+ want : false ,
71+ },
72+ {
73+ name : "Context deadline already expired" ,
74+ ctxTimeout : ptrutil .Ptr (- 1 * time .Second ),
75+ timeout : 1 * time .Second ,
76+ want : true , // *timeout <= 0 branch in code
77+ },
78+ {
79+ name : "Timeout is zero, context deadline in future" ,
80+ ctxTimeout : ptrutil .Ptr (10 * time .Second ),
81+ timeout : 0 * time .Second ,
82+ want : true ,
83+ },
84+ {
85+ name : "Timeout is negative, context deadline in future" ,
86+ ctxTimeout : ptrutil .Ptr (10 * time .Second ),
87+ timeout : - 1 * time .Second ,
88+ want : true ,
89+ },
90+ {
91+ name : "Timeout provided, context has no deadline" ,
92+ ctxTimeout : nil ,
93+ timeout : 1 * time .Second ,
94+ want : true ,
95+ },
96+ }
97+
98+ for _ , test := range tests {
99+ t .Run (test .name , func (t * testing.T ) {
100+ ctx := context .Background ()
101+ if test .ctxTimeout != nil {
102+ var cancel context.CancelFunc
103+
104+ ctx , cancel = context .WithTimeout (ctx , * test .ctxTimeout )
105+ defer cancel ()
106+ }
107+
108+ got := TimeoutWithinContext (ctx , test .timeout )
109+ assert .Equal (t , test .want , got )
110+ })
111+ }
112+ }
0 commit comments