github.com/grafana/pyroscope@v1.18.0/operations/pyroscope/alloy_test.go (about) 1 package pyroscope 2 3 import ( 4 "bytes" 5 "errors" 6 "fmt" 7 "io" 8 "os" 9 "testing" 10 11 "github.com/google/go-cmp/cmp" 12 "github.com/grafana/alloy/syntax/diag" 13 "github.com/grafana/alloy/syntax/parser" 14 "github.com/grafana/alloy/syntax/printer" 15 "github.com/stretchr/testify/require" 16 "gopkg.in/yaml.v3" 17 ) 18 19 // Test_FormatAgentRiverConfig tests that the river config generated by helm is formatted correctly 20 func Test_FormatAgentRiverConfig(t *testing.T) { 21 fdata, err := os.Open("helm/pyroscope/rendered/single-binary.yaml") 22 require.NoError(t, err) 23 defer fdata.Close() 24 25 values := map[string]interface{}{} 26 configString := `` 27 dec := yaml.NewDecoder(fdata) 28 for dec.Decode(&values) == nil { 29 if values["metadata"].(map[string]interface{})["name"] == "alloy-config-pyroscope" { 30 configString = values["data"].(map[string]interface{})["config.alloy"].(string) 31 break 32 } 33 } 34 fileName := fmt.Sprintf("%s/config.alloy", t.TempDir()) 35 require.NoError(t, os.WriteFile(fileName, []byte(configString), 0o644)) 36 fi, err := os.Stat(fileName) 37 require.NoError(t, err) 38 f, err := os.Open(fileName) 39 require.NoError(t, err) 40 defer f.Close() 41 42 err = format(fileName, fi, f, true) 43 var diags diag.Diagnostics 44 if errors.As(err, &diags) { 45 for _, diag := range diags { 46 fmt.Fprintln(os.Stderr, diag) 47 } 48 t.Error("encountered errors during formatting") 49 } 50 fmtData, err := os.ReadFile(fileName) 51 require.NoError(t, err) 52 if diff := cmp.Diff(string(fmtData), configString); diff != "" { 53 t.Errorf("Grafana Agent Helm River config file is not formatted mismatch (-want +got):\n%s", diff) 54 t.Log("You need to fixes formatting issues in operations/pyroscope/helm/pyroscope/templates/configmap-agent.yaml and run make helm/check.") 55 } 56 } 57 58 func format(filename string, fi os.FileInfo, r io.Reader, write bool) error { 59 bb, err := io.ReadAll(r) 60 if err != nil { 61 return err 62 } 63 64 f, err := parser.ParseFile(filename, bb) 65 if err != nil { 66 return err 67 } 68 69 var buf bytes.Buffer 70 if err := printer.Fprint(&buf, f); err != nil { 71 return err 72 } 73 74 // Add a newline at the end of the file. 75 _, _ = buf.Write([]byte{'\n'}) 76 77 if !write { 78 _, err := io.Copy(os.Stdout, &buf) 79 return err 80 } 81 82 wf, err := os.OpenFile(filename, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, fi.Mode().Perm()) 83 if err != nil { 84 return err 85 } 86 defer wf.Close() 87 88 _, err = io.Copy(wf, &buf) 89 return err 90 }