File: client_test.go

package info (click to toggle)
golang-github-cactus-go-statsd-client 5.0.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 204 kB
  • sloc: makefile: 5
file content (297 lines) | stat: -rw-r--r-- 7,681 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
// Copyright (c) 2012-2016 Eli Janssen
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

package statsd

import (
	"bytes"
	"log"
	"net"
	"reflect"
	"testing"
	"time"
)

var statsdPacketTests = []struct {
	Prefix   string
	Method   string
	Stat     string
	Value    interface{}
	Rate     float32
	Expected string
}{
	{"test", "Gauge", "gauge", int64(1), 1.0, "test.gauge:1|g"},
	{"test", "Inc", "count", int64(1), 0.999999, "test.count:1|c|@0.999999"},
	{"test", "Inc", "count", int64(1), 1.0, "test.count:1|c"},
	{"test", "Dec", "count", int64(1), 1.0, "test.count:-1|c"},
	{"test", "Timing", "timing", int64(1), 1.0, "test.timing:1|ms"},
	{"test", "TimingDuration", "timing", 1500 * time.Microsecond, 1.0, "test.timing:1.5|ms"},
	{"test", "TimingDuration", "timing", 3 * time.Microsecond, 1.0, "test.timing:0.003|ms"},
	{"test", "Set", "strset", "pickle", 1.0, "test.strset:pickle|s"},
	{"test", "SetInt", "intset", int64(1), 1.0, "test.intset:1|s"},
	{"test", "GaugeDelta", "gauge", int64(1), 1.0, "test.gauge:+1|g"},
	{"test", "GaugeDelta", "gauge", int64(-1), 1.0, "test.gauge:-1|g"},

	{"", "Gauge", "gauge", int64(1), 1.0, "gauge:1|g"},
	{"", "Inc", "count", int64(1), 0.999999, "count:1|c|@0.999999"},
	{"", "Inc", "count", int64(1), 1.0, "count:1|c"},
	{"", "Dec", "count", int64(1), 1.0, "count:-1|c"},
	{"", "Timing", "timing", int64(1), 1.0, "timing:1|ms"},
	{"", "TimingDuration", "timing", 1500 * time.Microsecond, 1.0, "timing:1.5|ms"},
	{"", "Set", "strset", "pickle", 1.0, "strset:pickle|s"},
	{"", "SetInt", "intset", int64(1), 1.0, "intset:1|s"},
	{"", "GaugeDelta", "gauge", int64(1), 1.0, "gauge:+1|g"},
	{"", "GaugeDelta", "gauge", int64(-1), 1.0, "gauge:-1|g"},
}

func TestClient(t *testing.T) {
	l, err := newUDPListener("127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer l.Close()
	for _, tt := range statsdPacketTests {
		c, err := NewClient(l.LocalAddr().String(), tt.Prefix)
		if err != nil {
			t.Fatal(err)
		}
		method := reflect.ValueOf(c).MethodByName(tt.Method)
		values := []reflect.Value{
			reflect.ValueOf(tt.Stat),
			reflect.ValueOf(tt.Value),
			reflect.ValueOf(tt.Rate),
		}
		e := method.Call(values)[0]
		errInter := e.Interface()
		if errInter != nil {
			t.Fatal(errInter.(error))
		}

		data := make([]byte, 128)
		_, _, err = l.ReadFrom(data)
		if err != nil {
			c.Close()
			t.Fatal(err)
		}

		data = bytes.TrimRight(data, "\x00")
		if !bytes.Equal(data, []byte(tt.Expected)) {
			c.Close()
			t.Fatalf("%s got '%s' expected '%s'", tt.Method, data, tt.Expected)
		}
		c.Close()
	}
}

func TestClientTags(t *testing.T) {
	statsdTaggedPacketTests := []struct {
		TagFormat TagFormat
		Prefix    string
		Method    string
		Stat      string
		Value     interface{}
		Rate      float32
		Tags      []Tag
		Expected  string
	}{
		{
			SuffixOctothorpe,
			"test", "Inc", "count", int64(1), 0.999999,
			[]Tag{{"tag1", "val1"}},
			"test.count:1|c|@0.999999|#tag1:val1",
		},
		{
			SuffixOctothorpe,
			"test", "Inc", "count", int64(1), 1.0,
			[]Tag{{"tag1", "val1"}, {"tag2", "val2"}},
			"test.count:1|c|#tag1:val1,tag2:val2",
		},
		{
			InfixComma,
			"test", "Inc", "count", int64(1), 1.0,
			[]Tag{{"tag1", "val1"}},
			"test.count,tag1=val1:1|c",
		},
		{
			InfixComma,
			"test", "Inc", "count", int64(1), 1.0,
			[]Tag{{"tag1", "val1"}, {"tag2", "val2"}},
			"test.count,tag1=val1,tag2=val2:1|c",
		},
		{
			InfixSemicolon,
			"test", "Inc", "count", int64(1), 1.0,
			[]Tag{{"tag1", "val1"}},
			"test.count;tag1=val1:1|c",
		},
		{
			InfixSemicolon,
			"test", "Inc", "count", int64(1), 1.0,
			[]Tag{{"tag1", "val1"}, {"tag2", "val2"}},
			"test.count;tag1=val1;tag2=val2:1|c",
		},
	}

	l, err := newUDPListener("127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer l.Close()
	for _, tt := range statsdTaggedPacketTests {
		config := &ClientConfig{
			Address:   l.LocalAddr().String(),
			Prefix:    tt.Prefix,
			TagFormat: tt.TagFormat,
		}

		c, err := NewClientWithConfig(config)
		if err != nil {
			t.Fatal(err)
		}
		c.(*Client).tagFormat = tt.TagFormat
		method := reflect.ValueOf(c).MethodByName(tt.Method)
		values := []reflect.Value{
			reflect.ValueOf(tt.Stat),
			reflect.ValueOf(tt.Value),
			reflect.ValueOf(tt.Rate)}
		for _, tag := range tt.Tags {
			values = append(values, reflect.ValueOf(tag))
		}
		e := method.Call(values)[0]
		errInter := e.Interface()
		if errInter != nil {
			t.Fatal(errInter.(error))
		}

		data := make([]byte, 128)
		_, _, err = l.ReadFrom(data)
		if err != nil {
			c.Close()
			t.Fatal(err)
		}

		data = bytes.TrimRight(data, "\x00")
		if !bytes.Equal(data, []byte(tt.Expected)) {
			c.Close()
			t.Fatalf("%s got '%s' expected '%s'", tt.Method, data, tt.Expected)
		}
		c.Close()
	}
}

func TestNilClient(t *testing.T) {
	l, err := newUDPListener("127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer l.Close()
	for _, tt := range statsdPacketTests {
		var c *Client

		method := reflect.ValueOf(c).MethodByName(tt.Method)
		e := method.Call([]reflect.Value{
			reflect.ValueOf(tt.Stat),
			reflect.ValueOf(tt.Value),
			reflect.ValueOf(tt.Rate)})[0]
		errInter := e.Interface()
		if errInter != nil {
			t.Fatal(errInter.(error))
		}

		data := make([]byte, 128)
		n, _, err := l.ReadFrom(data)
		// this is expected to error, since there should
		// be no udp data sent, so the read will time out
		if err == nil || n != 0 {
			c.Close()
			t.Fatal(err)
		}
		c.Close()
	}
}

func newUDPListener(addr string) (*net.UDPConn, error) {
	l, err := net.ListenPacket("udp", addr)
	if err != nil {
		return nil, err
	}
	l.SetDeadline(time.Now().Add(100 * time.Millisecond))
	l.SetReadDeadline(time.Now().Add(100 * time.Millisecond))
	l.SetWriteDeadline(time.Now().Add(100 * time.Millisecond))
	return l.(*net.UDPConn), nil
}

func ExampleClient() {
	// First create a client config. Here is a simple config that sends one
	// stat per packet (for compatibility).
	config := &ClientConfig{
		Address: "127.0.0.1:8125",
		Prefix:  "test-client",
	}

	// Now create the client
	client, err := NewClientWithConfig(config)

	// and handle any initialization errors
	if err != nil {
		log.Fatal(err)
	}

	// make sure to clean up
	defer client.Close()

	// Send a stat
	err = client.Inc("stat1", 42, 1.0)
	// handle any errors
	if err != nil {
		log.Printf("Error sending metric: %+v", err)
	}
}

func ExampleClient_legacySimple() {
	// first create a client
	client, err := NewClient("127.0.0.1:8125", "test-client")
	// handle any errors
	if err != nil {
		log.Fatal(err)
	}
	// make sure to close to clean up when done, to avoid leaks.
	defer client.Close()

	// Send a stat
	err = client.Inc("stat1", 42, 1.0)
	// handle any errors
	if err != nil {
		log.Printf("Error sending metric: %+v", err)
	}
}

func ExampleClient_nil() {
	// use interface so we can sub nil client if needed
	var client Statter
	var err error

	// First create a client config. Here is a simple config that sends one
	// stat per packet (for compatibility).
	config := &ClientConfig{
		Address: "not-resolvable:8125",
		Prefix:  "test-client",
	}

	// Now create the client
	client, err = NewClientWithConfig(config)

	// Let us say real client creation fails, but you don't care enough about
	// stats that you don't want your program to run. Just log an error and
	// make a nil instead
	if err != nil {
		log.Println("Remote endpoint did not resolve. Disabling stats", err)
	}
	// at this point, client is a nil *Client. This will work like a noop client.
	// It is ok to call close when client is nil. It will be a noop too.
	defer client.Close()

	// Sicne client is nil, this is a noop.
	err = client.Inc("stat1", 42, 1.0)
}