@@ -11,6 +11,8 @@ import (
1111 "net"
1212 "os"
1313 "runtime"
14+ "sync"
15+ "sync/atomic"
1416 "testing"
1517 "time"
1618
@@ -232,4 +234,45 @@ func TestServerHeartbeatStartedEvent(t *testing.T) {
232234 }
233235 assert .Equal (t , expectedEvents , actualEvents )
234236 })
237+
238+ mt := mtest .New (t )
239+
240+ mt .Run ("polling must await frequency" , func (mt * mtest.T ) {
241+ var heartbeatStartedCount atomic.Int64
242+
243+ servers := map [string ]bool {}
244+ serversMu := sync.RWMutex {} // Guard the servers set
245+
246+ serverMonitor := & event.ServerMonitor {
247+ ServerHeartbeatStarted : func (* event.ServerHeartbeatStartedEvent ) {
248+ heartbeatStartedCount .Add (1 )
249+ },
250+ TopologyDescriptionChanged : func (evt * event.TopologyDescriptionChangedEvent ) {
251+ serversMu .Lock ()
252+ defer serversMu .Unlock ()
253+
254+ for _ , srv := range evt .NewDescription .Servers {
255+ servers [srv .Addr .String ()] = true
256+ }
257+ },
258+ }
259+
260+ // Create a client with heartbeatFrequency=100ms,
261+ // serverMonitoringMode=poll. Use SDAM to record the number of times the
262+ // a heartbeat is started and the number of servers discovered.
263+ mt .ResetClient (options .Client ().
264+ SetServerMonitor (serverMonitor ).
265+ SetServerMonitoringMode (options .ServerMonitoringModePoll ))
266+
267+ // Per specifications, minHeartbeatFrequencyMS=500ms. So, within the first
268+ // 500ms the heartbeatStartedCount should be LEQ to the number of discovered
269+ // servers.
270+ time .Sleep (500 * time .Millisecond )
271+
272+ serversMu .Lock ()
273+ serverCount := int64 (len (servers ))
274+ serversMu .Unlock ()
275+
276+ assert .LessOrEqual (mt , heartbeatStartedCount .Load (), serverCount )
277+ })
235278}
0 commit comments