forked from newrelic/go-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expect_implementation.go
470 lines (431 loc) · 15.2 KB
/
expect_implementation.go
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
// Copyright 2020 New Relic Corporation. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
package newrelic
import (
"encoding/json"
"fmt"
"time"
"github.com/Easypay/go-agent/v3/internal"
)
func validateStringField(v internal.Validator, fieldName, v1, v2 string) {
if v1 != v2 {
v.Error(fieldName, v1, v2)
}
}
type addValidatorField struct {
field interface{}
original internal.Validator
}
func (a addValidatorField) Error(fields ...interface{}) {
fields = append([]interface{}{a.field}, fields...)
a.original.Error(fields...)
}
// extendValidator is used to add more context to a validator.
func extendValidator(v internal.Validator, field interface{}) internal.Validator {
return addValidatorField{
field: field,
original: v,
}
}
// expectTxnMetrics tests that the app contains metrics for a transaction.
func expectTxnMetrics(t internal.Validator, mt *metricTable, want internal.WantTxn) {
var metrics []internal.WantMetric
var scope string
var allWebOther string
if want.IsWeb {
scope = "WebTransaction/Go/" + want.Name
allWebOther = "allWeb"
metrics = []internal.WantMetric{
{Name: "WebTransaction/Go/" + want.Name, Scope: "", Forced: true, Data: nil},
{Name: "WebTransaction", Scope: "", Forced: true, Data: nil},
{Name: "WebTransactionTotalTime/Go/" + want.Name, Scope: "", Forced: false, Data: nil},
{Name: "WebTransactionTotalTime", Scope: "", Forced: true, Data: nil},
{Name: "HttpDispatcher", Scope: "", Forced: true, Data: nil},
{Name: "Apdex", Scope: "", Forced: true, Data: nil},
{Name: "Apdex/Go/" + want.Name, Scope: "", Forced: false, Data: nil},
}
} else {
scope = "OtherTransaction/Go/" + want.Name
allWebOther = "allOther"
metrics = []internal.WantMetric{
{Name: "OtherTransaction/Go/" + want.Name, Scope: "", Forced: true, Data: nil},
{Name: "OtherTransaction/all", Scope: "", Forced: true, Data: nil},
{Name: "OtherTransactionTotalTime/Go/" + want.Name, Scope: "", Forced: false, Data: nil},
{Name: "OtherTransactionTotalTime", Scope: "", Forced: true, Data: nil},
}
}
if want.NumErrors > 0 {
data := []float64{float64(want.NumErrors), 0, 0, 0, 0, 0}
metrics = append(metrics, []internal.WantMetric{
{Name: "Errors/all", Scope: "", Forced: true, Data: data},
{Name: "Errors/" + allWebOther, Scope: "", Forced: true, Data: data},
{Name: "Errors/" + scope, Scope: "", Forced: true, Data: data},
}...)
}
expectMetrics(t, mt, metrics)
}
func expectMetricField(t internal.Validator, id metricID, v1, v2 float64, fieldName string) {
if v1 != v2 {
t.Error("metric fields do not match", id, v1, v2, fieldName)
}
}
// expectMetricsPresent allows testing of metrics without requiring an exact match
func expectMetricsPresent(t internal.Validator, mt *metricTable, expect []internal.WantMetric) {
expectMetricsInternal(t, mt, expect, false)
}
// expectMetrics allows testing of metrics. It passes if mt exactly matches expect.
func expectMetrics(t internal.Validator, mt *metricTable, expect []internal.WantMetric) {
expectMetricsInternal(t, mt, expect, true)
}
func expectMetricsInternal(t internal.Validator, mt *metricTable, expect []internal.WantMetric, exactMatch bool) {
if exactMatch {
if len(mt.metrics) != len(expect) {
t.Error("metric counts do not match expectations", len(mt.metrics), len(expect))
}
}
expectedIds := make(map[metricID]struct{})
for _, e := range expect {
id := metricID{Name: e.Name, Scope: e.Scope}
expectedIds[id] = struct{}{}
m := mt.metrics[id]
if nil == m {
t.Error("unable to find metric", id)
continue
}
if b, ok := e.Forced.(bool); ok {
if b != (forced == m.forced) {
t.Error("metric forced incorrect", b, m.forced, id)
}
}
if nil != e.Data {
expectMetricField(t, id, e.Data[0], m.data.countSatisfied, "countSatisfied")
if len(e.Data) > 1 {
expectMetricField(t, id, e.Data[1], m.data.totalTolerated, "totalTolerated")
expectMetricField(t, id, e.Data[2], m.data.exclusiveFailed, "exclusiveFailed")
expectMetricField(t, id, e.Data[3], m.data.min, "min")
expectMetricField(t, id, e.Data[4], m.data.max, "max")
expectMetricField(t, id, e.Data[5], m.data.sumSquares, "sumSquares")
}
}
}
if exactMatch {
for id := range mt.metrics {
if _, ok := expectedIds[id]; !ok {
t.Error("expected metrics does not contain", id.Name, id.Scope)
}
}
}
}
func expectAttributes(v internal.Validator, exists map[string]interface{}, expect map[string]interface{}) {
// TODO: This params comparison can be made smarter: Alert differences
// based on sub/super set behavior.
if len(exists) != len(expect) {
v.Error("attributes length difference", len(exists), len(expect))
}
for key, val := range expect {
found, ok := exists[key]
if !ok {
v.Error("expected attribute not found: ", key)
continue
}
if val == internal.MatchAnything {
continue
}
v1 := fmt.Sprint(found)
v2 := fmt.Sprint(val)
if v1 != v2 {
v.Error("value difference", fmt.Sprintf("key=%s", key), v1, v2)
}
}
for key, val := range exists {
_, ok := expect[key]
if !ok {
v.Error("unexpected attribute present: ", key, val)
continue
}
}
}
// expectCustomEvents allows testing of custom events. It passes if cs exactly matches expect.
func expectCustomEvents(v internal.Validator, cs *customEvents, expect []internal.WantEvent) {
expectEvents(v, cs.analyticsEvents, expect, nil)
}
func expectEvent(v internal.Validator, e json.Marshaler, expect internal.WantEvent) {
js, err := e.MarshalJSON()
if nil != err {
v.Error("unable to marshal event", err)
return
}
var event []map[string]interface{}
err = json.Unmarshal(js, &event)
if nil != err {
v.Error("unable to parse event json", err)
return
}
intrinsics := event[0]
userAttributes := event[1]
agentAttributes := event[2]
if nil != expect.Intrinsics {
expectAttributes(v, intrinsics, expect.Intrinsics)
}
if nil != expect.UserAttributes {
expectAttributes(v, userAttributes, expect.UserAttributes)
}
if nil != expect.AgentAttributes {
expectAttributes(v, agentAttributes, expect.AgentAttributes)
}
}
func expectEvents(v internal.Validator, events *analyticsEvents, expect []internal.WantEvent, extraAttributes map[string]interface{}) {
if len(events.events) != len(expect) {
v.Error("number of events does not match", len(events.events), len(expect))
return
}
for i, e := range expect {
event, ok := events.events[i].jsonWriter.(json.Marshaler)
if !ok {
v.Error("event does not implement json.Marshaler")
continue
}
if nil != e.Intrinsics {
e.Intrinsics = mergeAttributes(extraAttributes, e.Intrinsics)
}
expectEvent(v, event, e)
}
}
// Second attributes have priority.
func mergeAttributes(a1, a2 map[string]interface{}) map[string]interface{} {
a := make(map[string]interface{})
for k, v := range a1 {
a[k] = v
}
for k, v := range a2 {
a[k] = v
}
return a
}
// expectErrorEvents allows testing of error events. It passes if events exactly matches expect.
func expectErrorEvents(v internal.Validator, events *errorEvents, expect []internal.WantEvent) {
expectEvents(v, events.analyticsEvents, expect, map[string]interface{}{
// The following intrinsics should always be present in
// error events:
"type": "TransactionError",
"timestamp": internal.MatchAnything,
"duration": internal.MatchAnything,
})
}
// expectSpanEvents allows testing of span events. It passes if events exactly matches expect.
func expectSpanEvents(v internal.Validator, events *spanEvents, expect []internal.WantEvent) {
extraAttrs := map[string]interface{}{
// The following intrinsics should always be present in
// span events:
"type": "Span",
"timestamp": internal.MatchAnything,
"duration": internal.MatchAnything,
"traceId": internal.MatchAnything,
"guid": internal.MatchAnything,
"transactionId": internal.MatchAnything,
// All span events are currently sampled.
"sampled": true,
"priority": internal.MatchAnything,
}
expectEvents(v, events.analyticsEvents, expect, extraAttrs)
expectObserverEvents(v, events.analyticsEvents, expect, extraAttrs)
}
// expectTxnEvents allows testing of txn events.
func expectTxnEvents(v internal.Validator, events *txnEvents, expect []internal.WantEvent) {
expectEvents(v, events.analyticsEvents, expect, map[string]interface{}{
// The following intrinsics should always be present in
// txn events:
"type": "Transaction",
"timestamp": internal.MatchAnything,
"duration": internal.MatchAnything,
"totalTime": internal.MatchAnything,
"error": internal.MatchAnything,
})
}
func expectError(v internal.Validator, err *tracedError, expect internal.WantError) {
validateStringField(v, "txnName", expect.TxnName, err.FinalName)
validateStringField(v, "klass", expect.Klass, err.Klass)
validateStringField(v, "msg", expect.Msg, err.Msg)
js, errr := err.MarshalJSON()
if nil != errr {
v.Error("unable to marshal error json", errr)
return
}
var unmarshalled []interface{}
errr = json.Unmarshal(js, &unmarshalled)
if nil != errr {
v.Error("unable to unmarshal error json", errr)
return
}
attributes := unmarshalled[4].(map[string]interface{})
agentAttributes := attributes["agentAttributes"].(map[string]interface{})
userAttributes := attributes["userAttributes"].(map[string]interface{})
if nil != expect.UserAttributes {
expectAttributes(v, userAttributes, expect.UserAttributes)
}
if nil != expect.AgentAttributes {
expectAttributes(v, agentAttributes, expect.AgentAttributes)
}
if stack := attributes["stack_trace"]; nil == stack {
v.Error("missing error stack trace")
}
}
// expectErrors allows testing of errors.
func expectErrors(v internal.Validator, errors harvestErrors, expect []internal.WantError) {
if len(errors) != len(expect) {
v.Error("number of errors mismatch", len(errors), len(expect))
return
}
for i, e := range expect {
expectError(v, errors[i], e)
}
}
func countSegments(node []interface{}) int {
count := 1
children := node[4].([]interface{})
for _, c := range children {
node := c.([]interface{})
count += countSegments(node)
}
return count
}
func expectTraceSegment(v internal.Validator, nodeObj interface{}, expect internal.WantTraceSegment) {
node := nodeObj.([]interface{})
start := int(node[0].(float64))
stop := int(node[1].(float64))
name := node[2].(string)
attributes := node[3].(map[string]interface{})
children := node[4].([]interface{})
validateStringField(v, "segmentName", expect.SegmentName, name)
if nil != expect.RelativeStartMillis {
expectStart, ok := expect.RelativeStartMillis.(int)
if !ok {
v.Error("invalid expect.RelativeStartMillis", expect.RelativeStartMillis)
} else if expectStart != start {
v.Error("segmentStartTime", expect.SegmentName, start, expectStart)
}
}
if nil != expect.RelativeStopMillis {
expectStop, ok := expect.RelativeStopMillis.(int)
if !ok {
v.Error("invalid expect.RelativeStopMillis", expect.RelativeStopMillis)
} else if expectStop != stop {
v.Error("segmentStopTime", expect.SegmentName, stop, expectStop)
}
}
if nil != expect.Attributes {
expectAttributes(v, attributes, expect.Attributes)
}
if len(children) != len(expect.Children) {
v.Error("segmentChildrenCount", expect.SegmentName, len(children), len(expect.Children))
} else {
for idx, child := range children {
expectTraceSegment(v, child, expect.Children[idx])
}
}
}
func expectTxnTrace(v internal.Validator, got interface{}, expect internal.WantTxnTrace) {
unmarshalled := got.([]interface{})
duration := unmarshalled[1].(float64)
name := unmarshalled[2].(string)
var arrayURL string
if nil != unmarshalled[3] {
arrayURL = unmarshalled[3].(string)
}
traceData := unmarshalled[4].([]interface{})
rootNode := traceData[3].([]interface{})
attributes := traceData[4].(map[string]interface{})
userAttributes := attributes["userAttributes"].(map[string]interface{})
agentAttributes := attributes["agentAttributes"].(map[string]interface{})
intrinsics := attributes["intrinsics"].(map[string]interface{})
validateStringField(v, "metric name", expect.MetricName, name)
if d := expect.DurationMillis; nil != d && *d != duration {
v.Error("incorrect trace duration millis", *d, duration)
}
if nil != expect.UserAttributes {
expectAttributes(v, userAttributes, expect.UserAttributes)
}
if nil != expect.AgentAttributes {
expectAttributes(v, agentAttributes, expect.AgentAttributes)
expectURL, _ := expect.AgentAttributes["request.uri"].(string)
if "" != expectURL {
validateStringField(v, "request url in array", expectURL, arrayURL)
}
}
if nil != expect.Intrinsics {
expectAttributes(v, intrinsics, expect.Intrinsics)
}
if expect.Root.SegmentName != "" {
expectTraceSegment(v, rootNode, expect.Root)
} else {
numSegments := countSegments(rootNode)
// The expectation segment count does not include the two root nodes.
numSegments -= 2
if expect.NumSegments != numSegments {
v.Error("wrong number of segments", expect.NumSegments, numSegments)
}
}
}
// expectTxnTraces allows testing of transaction traces.
func expectTxnTraces(v internal.Validator, traces *harvestTraces, want []internal.WantTxnTrace) {
if len(want) != traces.Len() {
v.Error("number of traces do not match", len(want), traces.Len())
return
}
if len(want) == 0 {
return
}
js, err := traces.Data("agentRunID", time.Now())
if nil != err {
v.Error("error creasing harvest traces data", err)
return
}
var unmarshalled []interface{}
err = json.Unmarshal(js, &unmarshalled)
if nil != err {
v.Error("unable to unmarshal error json", err)
return
}
if "agentRunID" != unmarshalled[0].(string) {
v.Error("traces agent run id wrong", unmarshalled[0])
return
}
gotTraces := unmarshalled[1].([]interface{})
if len(gotTraces) != len(want) {
v.Error("number of traces in json does not match", len(gotTraces), len(want))
return
}
for i, expected := range want {
expectTxnTrace(v, gotTraces[i], expected)
}
}
func expectSlowQuery(t internal.Validator, slowQuery *slowQuery, want internal.WantSlowQuery) {
if slowQuery.Count != want.Count {
t.Error("wrong Count field", slowQuery.Count, want.Count)
}
uri, _ := slowQuery.txnEvent.Attrs.GetAgentValue(AttributeRequestURI, destTxnTrace)
validateStringField(t, "MetricName", slowQuery.DatastoreMetric, want.MetricName)
validateStringField(t, "Query", slowQuery.ParameterizedQuery, want.Query)
validateStringField(t, "TxnEvent.FinalName", slowQuery.txnEvent.FinalName, want.TxnName)
validateStringField(t, "request.uri", uri, want.TxnURL)
validateStringField(t, "DatabaseName", slowQuery.DatabaseName, want.DatabaseName)
validateStringField(t, "Host", slowQuery.Host, want.Host)
validateStringField(t, "PortPathOrID", slowQuery.PortPathOrID, want.PortPathOrID)
expectAttributes(t, map[string]interface{}(slowQuery.QueryParameters), want.Params)
}
// expectSlowQueries allows testing of slow queries.
func expectSlowQueries(t internal.Validator, slowQueries *slowQueries, want []internal.WantSlowQuery) {
if len(want) != len(slowQueries.priorityQueue) {
t.Error("wrong number of slow queries",
"expected", len(want), "got", len(slowQueries.priorityQueue))
return
}
for _, s := range want {
idx, ok := slowQueries.lookup[s.Query]
if !ok {
t.Error("unable to find slow query", s.Query)
continue
}
expectSlowQuery(t, slowQueries.priorityQueue[idx], s)
}
}