github.com/anthropics/anthropic-sdk-go@v1.70.1/internal/testutil/golden.go (about)

     1  package testutil
     2  
     3  import (
     4  	"os"
     5  	"path/filepath"
     6  	"testing"
     7  )
     8  
     9  // CompareGolden compares the given string with the golden file at path.
    10  // If UPDATE_GOLDEN=1, it overwrites the file with the provided contents.
    11  func CompareGolden(t *testing.T, goldenRelPath string, got []byte) {
    12  	t.Helper()
    13  	goldenPath := filepath.FromSlash(goldenRelPath)
    14  
    15  	if os.Getenv("UPDATE_GOLDEN") == "1" {
    16  		if err := os.MkdirAll(filepath.Dir(goldenPath), 0o755); err != nil {
    17  			t.Fatalf("creating golden dir: %v", err)
    18  		}
    19  		if err := os.WriteFile(goldenPath, got, 0o644); err != nil {
    20  			t.Fatalf("writing golden: %v", err)
    21  		}
    22  		return
    23  	}
    24  
    25  	want, err := os.ReadFile(goldenPath)
    26  	if err != nil {
    27  		t.Fatalf("reading golden: %v", err)
    28  	}
    29  	if string(want) != string(got) {
    30  		t.Fatalf("golden mismatch for %s\nwant:\n%s\n----\ngot:\n%s", goldenRelPath, string(want), string(got))
    31  	}
    32  }