github.com/waldiirawan/apm-agent-go/v2@v2.2.2/testmain_test.go (about) 1 // Licensed to Elasticsearch B.V. under one or more contributor 2 // license agreements. See the NOTICE file distributed with 3 // this work for additional information regarding copyright 4 // ownership. Elasticsearch B.V. licenses this file to you under 5 // the Apache License, Version 2.0 (the "License"); you may 6 // not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // 9 // http://www.apache.org/licenses/LICENSE-2.0 10 // 11 // Unless required by applicable law or agreed to in writing, 12 // software distributed under the License is distributed on an 13 // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 14 // KIND, either express or implied. See the License for the 15 // specific language governing permissions and limitations 16 // under the License. 17 18 package apm_test 19 20 import ( 21 "bytes" 22 "encoding/json" 23 "flag" 24 "os" 25 "os/exec" 26 "testing" 27 28 "github.com/stretchr/testify/assert" 29 "github.com/stretchr/testify/require" 30 31 "github.com/waldiirawan/apm-agent-go/v2/apmtest" 32 "github.com/waldiirawan/apm-agent-go/v2/model" 33 "go.elastic.co/fastjson" 34 ) 35 36 var ( 37 flagDumpMetadata = flag.Bool("dump-metadata", false, "Dump metadata and exit without running any tests") 38 ) 39 40 func TestMain(m *testing.M) { 41 // call flag.Parse() here if TestMain uses flags 42 flag.Parse() 43 if *flagDumpMetadata { 44 dumpMetadata() 45 os.Exit(0) 46 } 47 os.Exit(m.Run()) 48 } 49 50 func getSubprocessMetadata(t *testing.T, env ...string) (*model.System, *model.Process, *model.Service, model.StringMap) { 51 cmd := exec.Command(os.Args[0], "-dump-metadata") 52 cmd.Env = append(os.Environ(), env...) 53 54 var stdout bytes.Buffer 55 cmd.Stdout = &stdout 56 cmd.Stderr = os.Stderr 57 if !assert.NoError(t, cmd.Run()) { 58 t.FailNow() 59 } 60 61 var system model.System 62 var process model.Process 63 var service model.Service 64 var labels model.StringMap 65 66 output := stdout.String() 67 d := json.NewDecoder(&stdout) 68 if !assert.NoError(t, d.Decode(&system)) { 69 t.Logf("output: %q", output) 70 t.FailNow() 71 } 72 require.NoError(t, d.Decode(&process)) 73 require.NoError(t, d.Decode(&service)) 74 require.NoError(t, d.Decode(&labels)) 75 return &system, &process, &service, labels 76 } 77 78 func dumpMetadata() { 79 tracer := apmtest.NewRecordingTracer() 80 defer tracer.Close() 81 82 tracer.StartTransaction("name", "type").End() 83 tracer.Flush(nil) 84 system, process, service, labels := tracer.Metadata() 85 86 var w fastjson.Writer 87 for _, m := range []fastjson.Marshaler{&system, &process, &service, labels} { 88 if err := m.MarshalFastJSON(&w); err != nil { 89 panic(err) 90 } 91 } 92 os.Stdout.Write(w.Bytes()) 93 }