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
|
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2024 Datadog, Inc.
package gotesting
import (
"fmt"
"os"
"reflect"
"runtime"
"strings"
"sync/atomic"
"testing"
"time"
"ci-visibility-test-github/main/civisibility/integrations"
"ci-visibility-test-github/main/civisibility/utils"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/ext"
)
const (
// testFramework represents the name of the testing framework.
testFramework = "golang.org/pkg/testing"
)
var (
// session represents the CI visibility test session.
session integrations.DdTestSession
// testInfos holds information about the instrumented tests.
testInfos []*testingTInfo
// benchmarkInfos holds information about the instrumented benchmarks.
benchmarkInfos []*testingBInfo
// modulesCounters keeps track of the number of tests per module.
modulesCounters = map[string]*int32{}
// suitesCounters keeps track of the number of tests per suite.
suitesCounters = map[string]*int32{}
)
type (
// commonInfo holds common information about tests and benchmarks.
commonInfo struct {
moduleName string
suiteName string
testName string
}
// testingTInfo holds information specific to tests.
testingTInfo struct {
commonInfo
originalFunc func(*testing.T)
}
// testingBInfo holds information specific to benchmarks.
testingBInfo struct {
commonInfo
originalFunc func(b *testing.B)
}
// M is a wrapper around testing.M to provide instrumentation.
M testing.M
)
// Run initializes CI Visibility, instruments tests and benchmarks, and runs them.
func (ddm *M) Run() int {
integrations.EnsureCiVisibilityInitialization()
defer integrations.ExitCiVisibility()
// Create a new test session for CI visibility.
session = integrations.CreateTestSession()
m := (*testing.M)(ddm)
// Instrument the internal tests for CI visibility.
ddm.instrumentInternalTests(getInternalTestArray(m))
// Instrument the internal benchmarks for CI visibility.
for _, v := range os.Args {
// check if benchmarking is enabled to instrument
if strings.Contains(v, "-bench") || strings.Contains(v, "test.bench") {
ddm.instrumentInternalBenchmarks(getInternalBenchmarkArray(m))
break
}
}
// Run the tests and benchmarks.
var exitCode = m.Run()
// Close the session and return the exit code.
session.Close(exitCode)
return exitCode
}
// instrumentInternalTests instruments the internal tests for CI visibility.
func (ddm *M) instrumentInternalTests(internalTests *[]testing.InternalTest) {
if internalTests != nil {
// Extract info from internal tests
testInfos = make([]*testingTInfo, len(*internalTests))
for idx, test := range *internalTests {
moduleName, suiteName := utils.GetModuleAndSuiteName(reflect.Indirect(reflect.ValueOf(test.F)).Pointer())
testInfo := &testingTInfo{
originalFunc: test.F,
commonInfo: commonInfo{
moduleName: moduleName,
suiteName: suiteName,
testName: test.Name,
},
}
// Initialize module and suite counters if not already present.
if _, ok := modulesCounters[moduleName]; !ok {
var v int32
modulesCounters[moduleName] = &v
}
// Increment the test count in the module.
atomic.AddInt32(modulesCounters[moduleName], 1)
if _, ok := suitesCounters[suiteName]; !ok {
var v int32
suitesCounters[suiteName] = &v
}
// Increment the test count in the suite.
atomic.AddInt32(suitesCounters[suiteName], 1)
testInfos[idx] = testInfo
}
// Create new instrumented internal tests
newTestArray := make([]testing.InternalTest, len(*internalTests))
for idx, testInfo := range testInfos {
newTestArray[idx] = testing.InternalTest{
Name: testInfo.testName,
F: ddm.executeInternalTest(testInfo),
}
}
*internalTests = newTestArray
}
}
// executeInternalTest wraps the original test function to include CI visibility instrumentation.
func (ddm *M) executeInternalTest(testInfo *testingTInfo) func(*testing.T) {
originalFunc := runtime.FuncForPC(reflect.Indirect(reflect.ValueOf(testInfo.originalFunc)).Pointer())
return func(t *testing.T) {
// Create or retrieve the module, suite, and test for CI visibility.
module := session.GetOrCreateModuleWithFramework(testInfo.moduleName, testFramework, runtime.Version())
suite := module.GetOrCreateSuite(testInfo.suiteName)
test := suite.CreateTest(testInfo.testName)
test.SetTestFunc(originalFunc)
setCiVisibilityTest(t, test)
defer func() {
if r := recover(); r != nil {
// Handle panic and set error information.
test.SetErrorInfo("panic", fmt.Sprint(r), utils.GetStacktrace(1))
suite.SetTag(ext.Error, true)
module.SetTag(ext.Error, true)
test.Close(integrations.ResultStatusFail)
checkModuleAndSuite(module, suite)
integrations.ExitCiVisibility()
panic(r)
} else {
// Normal finalization: determine the test result based on its state.
if t.Failed() {
test.SetTag(ext.Error, true)
suite.SetTag(ext.Error, true)
module.SetTag(ext.Error, true)
test.Close(integrations.ResultStatusFail)
} else if t.Skipped() {
test.Close(integrations.ResultStatusSkip)
} else {
test.Close(integrations.ResultStatusPass)
}
checkModuleAndSuite(module, suite)
}
}()
// Execute the original test function.
testInfo.originalFunc(t)
}
}
// instrumentInternalBenchmarks instruments the internal benchmarks for CI visibility.
func (ddm *M) instrumentInternalBenchmarks(internalBenchmarks *[]testing.InternalBenchmark) {
if internalBenchmarks != nil {
// Extract info from internal benchmarks
benchmarkInfos = make([]*testingBInfo, len(*internalBenchmarks))
for idx, benchmark := range *internalBenchmarks {
moduleName, suiteName := utils.GetModuleAndSuiteName(reflect.Indirect(reflect.ValueOf(benchmark.F)).Pointer())
benchmarkInfo := &testingBInfo{
originalFunc: benchmark.F,
commonInfo: commonInfo{
moduleName: moduleName,
suiteName: suiteName,
testName: benchmark.Name,
},
}
// Initialize module and suite counters if not already present.
if _, ok := modulesCounters[moduleName]; !ok {
var v int32
modulesCounters[moduleName] = &v
}
// Increment the test count in the module.
atomic.AddInt32(modulesCounters[moduleName], 1)
if _, ok := suitesCounters[suiteName]; !ok {
var v int32
suitesCounters[suiteName] = &v
}
// Increment the test count in the suite.
atomic.AddInt32(suitesCounters[suiteName], 1)
benchmarkInfos[idx] = benchmarkInfo
}
// Create a new instrumented internal benchmarks
newBenchmarkArray := make([]testing.InternalBenchmark, len(*internalBenchmarks))
for idx, benchmarkInfo := range benchmarkInfos {
newBenchmarkArray[idx] = testing.InternalBenchmark{
Name: benchmarkInfo.testName,
F: ddm.executeInternalBenchmark(benchmarkInfo),
}
}
*internalBenchmarks = newBenchmarkArray
}
}
// executeInternalBenchmark wraps the original benchmark function to include CI visibility instrumentation.
func (ddm *M) executeInternalBenchmark(benchmarkInfo *testingBInfo) func(*testing.B) {
return func(b *testing.B) {
// decrement level
getBenchmarkPrivateFields(b).AddLevel(-1)
startTime := time.Now()
originalFunc := runtime.FuncForPC(reflect.Indirect(reflect.ValueOf(benchmarkInfo.originalFunc)).Pointer())
module := session.GetOrCreateModuleWithFrameworkAndStartTime(benchmarkInfo.moduleName, testFramework, runtime.Version(), startTime)
suite := module.GetOrCreateSuiteWithStartTime(benchmarkInfo.suiteName, startTime)
test := suite.CreateTestWithStartTime(benchmarkInfo.testName, startTime)
test.SetTestFunc(originalFunc)
// Run the original benchmark function.
var iPfOfB *benchmarkPrivateFields
var recoverFunc *func(r any)
b.Run(b.Name(), func(b *testing.B) {
// Stop the timer to perform initialization and replacements.
b.StopTimer()
defer func() {
if r := recover(); r != nil {
// Handle panic if it occurs during benchmark execution.
if recoverFunc != nil {
fn := *recoverFunc
fn(r)
}
panic(r)
}
}()
// Enable allocation reporting.
b.ReportAllocs()
// Retrieve the private fields of the inner testing.B.
iPfOfB = getBenchmarkPrivateFields(b)
// Replace the benchmark function with the original one (this must be executed only once - the first iteration[b.run1]).
*iPfOfB.benchFunc = benchmarkInfo.originalFunc
// Set the CI visibility benchmark.
setCiVisibilityBenchmark(b, test)
// Restart the timer and execute the original benchmark function.
b.ResetTimer()
b.StartTimer()
benchmarkInfo.originalFunc(b)
})
endTime := time.Now()
results := iPfOfB.result
// Set benchmark data for CI visibility.
test.SetBenchmarkData("duration", map[string]any{
"run": results.N,
"mean": results.NsPerOp(),
})
test.SetBenchmarkData("memory_total_operations", map[string]any{
"run": results.N,
"mean": results.AllocsPerOp(),
"statistics.max": results.MemAllocs,
})
test.SetBenchmarkData("mean_heap_allocations", map[string]any{
"run": results.N,
"mean": results.AllocedBytesPerOp(),
})
test.SetBenchmarkData("total_heap_allocations", map[string]any{
"run": results.N,
"mean": iPfOfB.result.MemBytes,
})
if len(results.Extra) > 0 {
mapConverted := map[string]any{}
for k, v := range results.Extra {
mapConverted[k] = v
}
test.SetBenchmarkData("extra", mapConverted)
}
// Define a function to handle panic during benchmark finalization.
panicFunc := func(r any) {
test.SetErrorInfo("panic", fmt.Sprint(r), utils.GetStacktrace(1))
suite.SetTag(ext.Error, true)
module.SetTag(ext.Error, true)
test.Close(integrations.ResultStatusFail)
checkModuleAndSuite(module, suite)
integrations.ExitCiVisibility()
}
recoverFunc = &panicFunc
// Normal finalization: determine the benchmark result based on its state.
if iPfOfB.B.Failed() {
test.SetTag(ext.Error, true)
suite.SetTag(ext.Error, true)
module.SetTag(ext.Error, true)
test.CloseWithFinishTime(integrations.ResultStatusFail, endTime)
} else if iPfOfB.B.Skipped() {
test.CloseWithFinishTime(integrations.ResultStatusSkip, endTime)
} else {
test.CloseWithFinishTime(integrations.ResultStatusPass, endTime)
}
checkModuleAndSuite(module, suite)
}
}
// RunM runs the tests and benchmarks using CI visibility.
func RunM(m *testing.M) int {
return (*M)(m).Run()
}
// checkModuleAndSuite checks and closes the modules and suites if all tests are executed.
func checkModuleAndSuite(module integrations.DdTestModule, suite integrations.DdTestSuite) {
// If all tests in a suite has been executed we can close the suite
if atomic.AddInt32(suitesCounters[suite.Name()], -1) <= 0 {
suite.Close()
}
// If all tests in a module has been executed we can close the module
if atomic.AddInt32(modulesCounters[module.Name()], -1) <= 0 {
module.Close()
}
}
|