go.undefinedlabs.com/scopeagent@v0.4.2/instrumentation/testing/init.go (about)

     1  package testing
     2  
     3  import (
     4  	"flag"
     5  	"reflect"
     6  	"testing"
     7  
     8  	"go.undefinedlabs.com/scopeagent/instrumentation"
     9  	"go.undefinedlabs.com/scopeagent/reflection"
    10  )
    11  
    12  var (
    13  	parallel int
    14  )
    15  
    16  // Initialize the testing instrumentation
    17  func Init(m *testing.M) {
    18  	flag.Parse()
    19  	fPtr := flag.Lookup("test.parallel")
    20  	if fPtr != nil {
    21  		parallel = (*fPtr).Value.(flag.Getter).Get().(int)
    22  		instrumentation.Logger().Println("parallel flag set to:", parallel)
    23  	}
    24  
    25  	if tPointer, err := reflection.GetFieldPointerOf(m, "tests"); err == nil {
    26  		intTests := (*[]testing.InternalTest)(tPointer)
    27  		tests := make([]testing.InternalTest, 0)
    28  		for _, test := range *intTests {
    29  			funcValue := test.F
    30  			funcPointer := reflect.ValueOf(funcValue).Pointer()
    31  			tests = append(tests, testing.InternalTest{
    32  				Name: test.Name,
    33  				F: func(t *testing.T) { // Creating a new test function as an indirection of the original test
    34  					addAutoInstrumentedTest(t)
    35  					tStruct := StartTestFromCaller(t, funcPointer)
    36  					defer tStruct.end()
    37  					funcValue(t)
    38  				},
    39  			})
    40  		}
    41  		// Replace internal tests with new test indirection
    42  		*intTests = tests
    43  	}
    44  	if bPointer, err := reflection.GetFieldPointerOf(m, "benchmarks"); err == nil {
    45  		intBenchmarks := (*[]testing.InternalBenchmark)(bPointer)
    46  		var benchmarks []testing.InternalBenchmark
    47  		for _, benchmark := range *intBenchmarks {
    48  			funcValue := benchmark.F
    49  			funcPointer := reflect.ValueOf(funcValue).Pointer()
    50  			benchmarks = append(benchmarks, testing.InternalBenchmark{
    51  				Name: benchmark.Name,
    52  				F: func(b *testing.B) { // Indirection of the original benchmark
    53  					startBenchmark(b, funcPointer, funcValue)
    54  				},
    55  			})
    56  		}
    57  		*intBenchmarks = benchmarks
    58  	}
    59  }