...

Source file src/go.mongodb.org/mongo-driver/x/mongo/driver/topology/server_rtt_test.go

Documentation: go.mongodb.org/mongo-driver/x/mongo/driver/topology

     1  // Copyright (C) MongoDB, Inc. 2017-present.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License"); you may
     4  // not use this file except in compliance with the License. You may obtain
     5  // a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
     6  
     7  package topology
     8  
     9  import (
    10  	"encoding/json"
    11  	"io/ioutil"
    12  	"path"
    13  	"testing"
    14  	"time"
    15  
    16  	"go.mongodb.org/mongo-driver/internal/assert"
    17  	"go.mongodb.org/mongo-driver/internal/spectest"
    18  )
    19  
    20  // Test case for all server selection rtt spec tests.
    21  func TestServerSelectionRTTSpec(t *testing.T) {
    22  
    23  	type testCase struct {
    24  		// AvgRttMs is either "NULL" or float
    25  		AvgRttMs  interface{} `json:"avg_rtt_ms"`
    26  		NewRttMs  float64     `json:"new_rtt_ms"`
    27  		NewAvgRtt float64     `json:"new_avg_rtt"`
    28  	}
    29  
    30  	const testsDir string = "../../../../testdata/server-selection/rtt"
    31  
    32  	for _, file := range spectest.FindJSONFilesInDir(t, testsDir) {
    33  		func(t *testing.T, filename string) {
    34  			filepath := path.Join(testsDir, filename)
    35  			content, err := ioutil.ReadFile(filepath)
    36  			assert.Nil(t, err, "ReadFile error for %s: %v", filepath, err)
    37  
    38  			// Remove ".json" from filename.
    39  			testName := filename[:len(filename)-5]
    40  
    41  			t.Run(testName, func(t *testing.T) {
    42  				var test testCase
    43  				err = json.Unmarshal(content, &test)
    44  				assert.Nil(t, err, "Unmarshal error: %v", err)
    45  
    46  				monitor := newRTTMonitor(&rttConfig{
    47  					interval: 10 * time.Second,
    48  				})
    49  				if test.AvgRttMs != "NULL" {
    50  					// If not "NULL", then must be a number, so typecast to float64
    51  					monitor.addSample(time.Duration(test.AvgRttMs.(float64) * float64(time.Millisecond)))
    52  				}
    53  
    54  				monitor.addSample(time.Duration(test.NewRttMs * float64(time.Millisecond)))
    55  				expectedRTT := time.Duration(test.NewAvgRtt * float64(time.Millisecond))
    56  				actualRTT := monitor.EWMA()
    57  				assert.Equal(t, expectedRTT, actualRTT, "expected average RTT %s, got %s", expectedRTT, actualRTT)
    58  			})
    59  		}(t, file)
    60  	}
    61  }
    62  

View as plain text