github.com/aristanetworks/goarista@v0.0.0-20240514173732-cca2755bbd44/influxlib/testlib.go (about) 1 // Copyright (c) 2018 Arista Networks, Inc. 2 // Use of this source code is governed by the Apache License 2.0 3 // that can be found in the COPYING file. 4 5 package influxlib 6 7 import ( 8 "bytes" 9 "errors" 10 "fmt" 11 "time" 12 13 influx "github.com/influxdata/influxdb1-client/v2" 14 ) 15 16 // This will serve as a fake client object to test off of. 17 // The idea is to provide a way to test the Influx Wrapper 18 // without having it connected to the database. 19 type fakeClient struct { 20 writer bytes.Buffer 21 failAll bool 22 } 23 24 func (w *fakeClient) Ping(timeout time.Duration) (time.Duration, 25 string, error) { 26 return 0, "", nil 27 } 28 29 func (w *fakeClient) Query(q influx.Query) (*influx.Response, error) { 30 if w.failAll { 31 return nil, errors.New("quering points failed") 32 } 33 34 return &influx.Response{Results: nil, Err: ""}, nil 35 } 36 37 func (w *fakeClient) QueryAsChunk(q influx.Query) (*influx.ChunkedResponse, error) { 38 return nil, nil 39 } 40 41 func (w *fakeClient) Close() error { 42 return nil 43 } 44 45 func (w *fakeClient) Write(bp influx.BatchPoints) error { 46 if w.failAll { 47 return errors.New("writing point failed") 48 } 49 w.writer.Reset() 50 for _, p := range bp.Points() { 51 fmt.Fprintf(&w.writer, p.String()+"\n") 52 } 53 return nil 54 } 55 56 func (w *fakeClient) qString() string { 57 return w.writer.String() 58 } 59 60 /***************************************************/ 61 62 // NewMockConnection returns an influxDBConnection with 63 // a "fake" client for offline testing. 64 func NewMockConnection() (*InfluxDBConnection, error) { 65 client := new(fakeClient) 66 config := &InfluxConfig{ 67 Hostname: "localhost", 68 Port: 8086, 69 Protocol: HTTP, 70 Database: "Test", 71 } 72 return &InfluxDBConnection{client, config}, nil 73 } 74 75 // GetTestBuffer returns the string that would normally 76 // be written to influx DB 77 func GetTestBuffer(con *InfluxDBConnection) (string, error) { 78 fc, ok := con.Client.(*fakeClient) 79 if !ok { 80 return "", errors.New("Expected a fake client but recieved a real one") 81 } 82 return fc.qString(), nil 83 }