-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathagent_test.go
More file actions
819 lines (725 loc) · 21.1 KB
/
Copy pathagent_test.go
File metadata and controls
819 lines (725 loc) · 21.1 KB
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
// (c) Copyright IBM Corp. 2022
package instana
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
"github.com/instana/go-sensor/acceptor"
"github.com/instana/go-sensor/autoprofile"
"github.com/stretchr/testify/assert"
)
func Test_agentS_SendSpans(t *testing.T) {
tests := []struct {
name string
spans []Span
}{
{
name: "big span",
spans: []Span{
{
Data: HTTPSpanData{
Tags: HTTPSpanTags{
URL: strings.Repeat("1", maxContentLength),
},
},
},
},
},
{
name: "multiple big span",
spans: []Span{
{Data: HTTPSpanData{Tags: HTTPSpanTags{URL: strings.Repeat("1", maxContentLength)}}},
{Data: HTTPSpanData{Tags: HTTPSpanTags{URL: strings.Repeat("1", maxContentLength)}}},
{Data: HTTPSpanData{Tags: HTTPSpanTags{URL: strings.Repeat("1", maxContentLength)}}},
{Data: HTTPSpanData{Tags: HTTPSpanTags{URL: strings.Repeat("1", maxContentLength)}}},
{Data: HTTPSpanData{Tags: HTTPSpanTags{URL: strings.Repeat("1", maxContentLength)}}},
{Data: HTTPSpanData{Tags: HTTPSpanTags{URL: strings.Repeat("1", maxContentLength)}}},
},
},
{
name: "not really a big span",
spans: []Span{
{
Data: HTTPSpanData{
Tags: HTTPSpanTags{
URL: strings.Repeat("1", maxContentLength/2),
},
},
},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ad := &agentCommunicator{
host: "", from: &fromS{},
client: &httpClientMock{
resp: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
},
},
}
agent := &agentS{agentComm: ad, logger: defaultLogger}
err := agent.SendSpans(tt.spans)
assert.NoError(t, err)
})
}
}
type httpClientMock struct {
resp *http.Response
err error
doFunc func(req *http.Request) (*http.Response, error)
}
func (h httpClientMock) Do(req *http.Request) (*http.Response, error) {
if h.doFunc != nil {
return h.doFunc(req)
}
return h.resp, h.err
}
func Test_agentResponse_getExtraHTTPHeaders(t *testing.T) {
tests := []struct {
name string
originalJSON string
want []string
}{
{
name: "old config",
originalJSON: `{"pid":37808,"agentUuid":"88:66:5a:ff:fe:05:a5:f0","extraHeaders":["expected-value"],"secrets":{"matcher":"contains-ignore-case","list":["key","pass","secret"]}}`,
want: []string{"expected-value"},
},
{
name: "new config",
originalJSON: `{"pid":38381,"agentUuid":"88:66:5a:ff:fe:05:a5:f0","tracing":{"extra-http-headers":["expected-value"]},"extraHeaders":["non-expected-value"],"secrets":{"matcher":"contains-ignore-case","list":["key","pass","secret"]}}`,
want: []string{"expected-value"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
r := &agentResponse{}
json.Unmarshal([]byte(tt.originalJSON), r)
assert.Equalf(t, tt.want, r.getExtraHTTPHeaders(), "getExtraHTTPHeaders()")
})
}
}
func Test_agentApplyHostSettings(t *testing.T) {
fsm := &fsmS{
agentComm: &agentCommunicator{
host: "",
from: &fromS{},
},
logger: defaultLogger,
}
response := agentResponse{
Pid: 37892,
HostID: "myhost",
Tracing: struct {
ExtraHTTPHeaders []string `json:"extra-http-headers"`
Disable []map[string]bool `json:"disable"`
}{
ExtraHTTPHeaders: []string{"my-unwanted-custom-headers"},
},
}
opts := &Options{
Service: "test_service",
Tracer: TracerOptions{
CollectableHTTPHeaders: []string{"x-custom-header-1", "x-custom-header-2"},
},
AgentClient: alwaysReadyClient{},
}
sensor = newSensor(opts)
defer func() {
sensor = nil
}()
fsm.applyHostAgentSettings(response)
assert.NotContains(t, sensor.options.Tracer.CollectableHTTPHeaders, "my-unwanted-custom-headers")
}
type alwaysReadyClient struct{}
func (alwaysReadyClient) Ready() bool { return true }
func (alwaysReadyClient) SendMetrics(data acceptor.Metrics) error { return nil }
func (alwaysReadyClient) SendEvent(event *EventData) error { return nil }
func (alwaysReadyClient) SendSpans(spans []Span) error { return nil }
func (alwaysReadyClient) SendProfiles(profiles []autoprofile.Profile) error { return nil }
func (alwaysReadyClient) Flush(context.Context) error { return nil }
func Test_agentS_SendEvent(t *testing.T) {
tests := []struct {
name string
event *EventData
mockResp *http.Response
mockErr error
expectedError bool
expectedErrorMsg string
}{
{
name: "successful event send with warning severity",
event: &EventData{
Title: "Test Event",
Text: "This is a test event",
Duration: 1000,
Severity: int(SeverityWarning),
Plugin: ServicePlugin,
ID: "test-service",
Host: ServiceHost,
},
mockResp: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
},
mockErr: nil,
expectedError: false,
},
{
name: "successful event send with critical severity",
event: &EventData{
Title: "Critical Event",
Text: "Critical issue detected",
Duration: 5000,
Severity: int(SeverityCritical),
Plugin: ServicePlugin,
ID: "critical-service",
Host: ServiceHost,
},
mockResp: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
},
mockErr: nil,
expectedError: false,
},
{
name: "successful event send with change severity",
event: &EventData{
Title: "Change Event",
Text: "Configuration changed",
Duration: 2000,
Severity: int(SeverityChange),
Plugin: ServicePlugin,
ID: "change-service",
Host: ServiceHost,
},
mockResp: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
},
mockErr: nil,
expectedError: false,
},
{
name: "event send with non-200 status code",
event: &EventData{
Title: "Server Error Event",
Text: "Server returned error",
Duration: 1000,
Severity: int(SeverityWarning),
},
mockResp: &http.Response{
StatusCode: 500,
Status: "Internal Server Error",
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
},
mockErr: nil,
expectedError: false,
},
{
name: "event with empty title",
event: &EventData{
Title: "",
Text: "Event with no title",
Duration: 1000,
Severity: int(SeverityWarning),
},
mockResp: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
},
mockErr: nil,
expectedError: false,
},
{
name: "event with minimal data",
event: &EventData{
Title: "Minimal Event",
},
mockResp: &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
},
mockErr: nil,
expectedError: false,
},
{
name: "event with payload too large",
event: &EventData{
Title: "Large Event",
Text: strings.Repeat("x", maxContentLength),
Duration: 1000,
Severity: int(SeverityWarning),
},
mockResp: nil,
mockErr: nil,
expectedError: true,
},
{
name: "nil event returns error",
event: nil,
mockResp: nil,
mockErr: nil,
expectedError: true,
expectedErrorMsg: "event cannot be nil",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a mock HTTP client
mockClient := &httpClientMock{
resp: tt.mockResp,
err: tt.mockErr,
}
// Create agent communicator with mock client
agentComm := &agentCommunicator{
host: "localhost",
port: "42699",
from: &fromS{EntityID: "12345"},
client: mockClient,
l: defaultLogger,
}
// Create agent with mock communicator
agent := &agentS{
agentComm: agentComm,
logger: defaultLogger,
}
// Execute SendEvent
err := agent.SendEvent(tt.event)
// Verify results
if tt.expectedError {
assert.Error(t, err)
if tt.expectedErrorMsg != "" {
assert.Contains(t, err.Error(), tt.expectedErrorMsg)
}
} else {
assert.NoError(t, err)
}
})
}
}
func Test_agentS_SendEvent_ConcurrentCalls(t *testing.T) {
// Test that concurrent SendEvent calls work correctly
// Create a mock client that returns a new response body for each request
// to avoid data races when multiple goroutines read from the same body
mockClient := &httpClientMock{
doFunc: func(req *http.Request) (*http.Response, error) {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewReader([]byte("{}"))),
}, nil
},
}
agentComm := &agentCommunicator{
host: "localhost",
port: "42699",
from: &fromS{EntityID: "12345"},
client: mockClient,
l: defaultLogger,
}
agent := &agentS{
agentComm: agentComm,
logger: defaultLogger,
}
// Send multiple events concurrently
const numEvents = 10
errChan := make(chan error, numEvents)
for i := 0; i < numEvents; i++ {
go func(index int) {
event := &EventData{
Title: "Concurrent Event " + strconv.Itoa(index),
Text: "Testing concurrent sends",
Duration: 1000,
Severity: int(SeverityWarning),
}
errChan <- agent.SendEvent(event)
}(i)
}
// Collect all results
for i := 0; i < numEvents; i++ {
err := <-errChan
assert.NoError(t, err)
}
}
// TestAgent_SendSpans_IPv6Support verifies that the agent can successfully send spans
// to an IPv6 endpoint. This test creates an IPv6 test server and validates that the
// agent's SendSpans method can communicate with IPv6 addresses using the format [::1]:port.
func TestAgent_SendSpans_IPv6Support(t *testing.T) {
// Create a test server that listens on IPv6
listener, err := net.Listen("tcp6", "[::1]:0") // IPv6 localhost
if err != nil {
t.Skipf("IPv6 not available on this system: %v", err)
}
defer listener.Close()
requestReceived := make(chan bool, 1)
var receivedPath string
// Create HTTP handler
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
// Verify it's a valid traces request
if !strings.HasPrefix(r.URL.Path, agentTracesURL) {
t.Errorf("unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
if r.Method != http.MethodPost {
t.Errorf("unexpected method: %s", r.Method)
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
requestReceived <- true
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
})
// Start server with IPv6 listener
server := &http.Server{Handler: handler}
go server.Serve(listener)
defer server.Close()
// Get the IPv6 address with port
addr := listener.Addr().(*net.TCPAddr)
ipv6Host := fmt.Sprintf("[%s]", addr.IP)
ipv6Port := strconv.Itoa(addr.Port)
t.Logf("Test server listening on IPv6: %s:%s", ipv6Host, ipv6Port)
// Create agent with IPv6 endpoint
agentComm := &agentCommunicator{
host: ipv6Host,
port: ipv6Port,
from: &fromS{EntityID: "12345"},
client: &http.Client{
Timeout: 5 * time.Second,
},
l: defaultLogger,
}
agent := &agentS{
agentComm: agentComm,
logger: defaultLogger,
}
// Send test spans
testSpans := []Span{
{
TraceID: 12345,
SpanID: 67890,
Name: "test-operation",
},
}
err = agent.SendSpans(testSpans)
if err != nil {
t.Fatalf("failed to send spans: %v", err)
}
// Wait for request to be received
select {
case <-requestReceived:
t.Logf("Successfully sent HTTP request to IPv6 endpoint")
// Verify correct endpoint was called
if !strings.HasPrefix(receivedPath, agentTracesURL) {
t.Errorf("Expected path to start with %s, got %s", agentTracesURL, receivedPath)
}
t.Logf("IPv6 endpoint support verified: SendSpans() successfully communicates with IPv6 addresses")
case <-time.After(3 * time.Second):
t.Fatal("timeout waiting for request - IPv6 communication failed")
}
}
// TestAgent_SendMetrics_IPv6Support verifies that the agent can successfully send metrics
// to an IPv6 endpoint. This test validates that the agent's SendMetrics method properly
// handles IPv6 addresses in the format [::1]:port.
func TestAgent_SendMetrics_IPv6Support(t *testing.T) {
// Create a test server that listens on IPv6
listener, err := net.Listen("tcp6", "[::1]:0")
if err != nil {
t.Skipf("IPv6 not available on this system: %v", err)
}
defer listener.Close()
requestReceived := make(chan bool, 1)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, agentDataURL) {
t.Errorf("unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
requestReceived <- true
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
})
server := &http.Server{Handler: handler}
go server.Serve(listener)
defer server.Close()
addr := listener.Addr().(*net.TCPAddr)
ipv6Host := fmt.Sprintf("[%s]", addr.IP)
ipv6Port := strconv.Itoa(addr.Port)
agentComm := &agentCommunicator{
host: ipv6Host,
port: ipv6Port,
from: &fromS{EntityID: "12345"},
client: &http.Client{
Timeout: 5 * time.Second,
},
l: defaultLogger,
}
agent := &agentS{
agentComm: agentComm,
snapshot: &SnapshotCollector{
CollectionInterval: snapshotCollectionInterval,
ServiceName: "test-service",
},
logger: defaultLogger,
}
// Send test metrics
testMetrics := acceptor.Metrics{
CgoCall: 100,
Goroutine: 200,
}
err = agent.SendMetrics(testMetrics)
if err != nil {
t.Fatalf("failed to send metrics: %v", err)
}
select {
case <-requestReceived:
t.Logf("IPv6 endpoint support verified: SendMetrics() successfully communicates with IPv6 addresses")
case <-time.After(3 * time.Second):
t.Fatal("timeout waiting for request - IPv6 communication failed")
}
}
// TestAgent_SendProfiles_IPv6Support verifies that the agent can successfully send profile data
// to an IPv6 endpoint. This test validates that the agent's SendProfiles method properly
// handles IPv6 addresses in the format [::1]:port.
func TestAgent_SendProfiles_IPv6Support(t *testing.T) {
listener, err := net.Listen("tcp6", "[::1]:0")
if err != nil {
t.Skipf("IPv6 not available on this system: %v", err)
}
defer listener.Close()
requestReceived := make(chan bool, 1)
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(r.URL.Path, agentProfilesURL) {
t.Errorf("unexpected path: %s", r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
}
requestReceived <- true
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
})
server := &http.Server{Handler: handler}
go server.Serve(listener)
defer server.Close()
addr := listener.Addr().(*net.TCPAddr)
ipv6Host := fmt.Sprintf("[%s]", addr.IP)
ipv6Port := strconv.Itoa(addr.Port)
agentComm := &agentCommunicator{
host: ipv6Host,
port: ipv6Port,
from: &fromS{EntityID: "12345"},
client: &http.Client{
Timeout: 5 * time.Second,
},
l: defaultLogger,
}
agent := &agentS{
agentComm: agentComm,
logger: defaultLogger,
}
// Send test profiles
testProfiles := []autoprofile.Profile{
{
Type: "cpu",
Duration: 1000,
},
}
err = agent.SendProfiles(testProfiles)
if err != nil {
t.Fatalf("failed to send profiles: %v", err)
}
select {
case <-requestReceived:
t.Logf("IPv6 endpoint support verified: SendProfiles() successfully communicates with IPv6 addresses")
case <-time.After(3 * time.Second):
t.Fatal("timeout waiting for request - IPv6 communication failed")
}
}
// TestAgent_IPv4vsIPv6 is a comparative test that verifies the agent works correctly with both
// IPv4 and IPv6 endpoints. This test ensures that the agent can send spans and metrics to both
// address types without any issues, validating cross-compatibility.
func TestAgent_IPv4vsIPv6(t *testing.T) {
tests := []struct {
name string
setupServer func() (string, string, func())
}{
{
name: "IPv4",
setupServer: func() (string, string, func()) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
}))
// Extract host and port from server URL
// server.URL format is "http://127.0.0.1:port"
host := "127.0.0.1"
port := server.URL[strings.LastIndex(server.URL, ":")+1:]
return host, port, server.Close
},
},
{
name: "IPv6",
setupServer: func() (string, string, func()) {
listener, err := net.Listen("tcp6", "[::1]:0")
if err != nil {
t.Skipf("IPv6 not available: %v", err)
}
server := &http.Server{
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
}),
}
go server.Serve(listener)
addr := listener.Addr().(*net.TCPAddr)
host := fmt.Sprintf("[%s]", addr.IP)
port := strconv.Itoa(addr.Port)
return host, port, func() {
server.Close()
listener.Close()
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
host, port, cleanup := tt.setupServer()
defer cleanup()
// Validate host and port format based on test type
if tt.name == "IPv4" {
// IPv4 host should not have brackets
assert.NotContains(t, host, "[", "IPv4 host should not contain brackets")
assert.NotContains(t, host, "]", "IPv4 host should not contain brackets")
assert.Equal(t, "127.0.0.1", host, "IPv4 host should be 127.0.0.1")
} else if tt.name == "IPv6" {
// IPv6 host should have brackets
assert.True(t, strings.HasPrefix(host, "["), "IPv6 host should start with [")
assert.True(t, strings.HasSuffix(host, "]"), "IPv6 host should end with ]")
assert.Contains(t, host, "::1", "IPv6 host should contain ::1")
}
// Validate port is a valid number
portNum, portErr := strconv.Atoi(port)
assert.NoError(t, portErr, "Port should be a valid number")
assert.Greater(t, portNum, 0, "Port should be greater than 0")
assert.LessOrEqual(t, portNum, 65535, "Port should be less than or equal to 65535")
agentComm := &agentCommunicator{
host: host,
port: port,
from: &fromS{EntityID: "12345"},
client: &http.Client{
Timeout: 5 * time.Second,
},
l: defaultLogger,
}
agent := &agentS{
agentComm: agentComm,
snapshot: &SnapshotCollector{
CollectionInterval: snapshotCollectionInterval,
ServiceName: "test-service",
},
logger: defaultLogger,
}
// Test SendSpans
testSpans := []Span{
{
TraceID: 12345,
SpanID: 67890,
Name: "test-operation",
},
}
err := agent.SendSpans(testSpans)
if err != nil {
t.Fatalf("SendSpans failed for %s: %v", tt.name, err)
}
// Test SendMetrics
testMetrics := acceptor.Metrics{
CgoCall: 100,
}
err = agent.SendMetrics(testMetrics)
if err != nil {
t.Fatalf("SendMetrics failed for %s: %v", tt.name, err)
}
t.Logf("%s endpoint works correctly", tt.name)
})
}
}
// TestNoopAgent_Methods verifies that all noopAgent methods return expected zero/nil
// values and do not panic. These are the fallback implementations before sensor init.
func TestNoopAgent_Methods(t *testing.T) {
tests := []struct {
name string
call func(noopAgent) error
wantErr bool
}{
{
name: "SendMetrics returns nil",
call: func(a noopAgent) error { return a.SendMetrics(acceptor.Metrics{}) },
wantErr: false,
},
{
name: "SendEvent returns nil",
call: func(a noopAgent) error { return a.SendEvent(&EventData{}) },
wantErr: false,
},
{
name: "SendSpans returns nil",
call: func(a noopAgent) error { return a.SendSpans(nil) },
wantErr: false,
},
{
name: "SendProfiles returns nil",
call: func(a noopAgent) error { return a.SendProfiles(nil) },
wantErr: false,
},
{
name: "Flush returns nil",
call: func(a noopAgent) error { return a.Flush(context.Background()) },
wantErr: false,
},
}
var a noopAgent
assert.False(t, a.Ready(), "noopAgent.Ready() must always return false")
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := tt.call(a)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
})
}
}
// TestAgentS_Flush verifies that agentS.Flush is a no-op that always returns nil.
func TestAgentS_Flush(t *testing.T) {
agent := &agentS{logger: defaultLogger}
assert.NoError(t, agent.Flush(context.Background()))
}
// TestAgentS_SetLogger verifies that setLogger replaces the agent logger.
func TestAgentS_SetLogger(t *testing.T) {
agent := &agentS{logger: defaultLogger}
newLogger := &testLogger{}
agent.setLogger(newLogger)
assert.Equal(t, newLogger, agent.logger)
}
// TestAgentS_SendMetrics_Error verifies that SendMetrics propagates a connection error
// and triggers a reset when the underlying agentComm cannot reach the host.
func TestAgentS_SendMetrics_Error(t *testing.T) {
agent := newAgent("test-service", "127.0.0.1", 1, defaultLogger)
agent.agentComm = newAgentCommunicator("127.0.0.1", "1", &fromS{EntityID: "123"}, defaultLogger)
assert.Error(t, agent.SendMetrics(acceptor.Metrics{}))
}