golden.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package testutil
  2. import (
  3. "encoding/json"
  4. "flag"
  5. "os"
  6. "path/filepath"
  7. "regexp"
  8. "runtime"
  9. "testing"
  10. "github.com/stretchr/testify/assert"
  11. )
  12. var updateRegex = flag.String("update", "", "Update testdata of tests matching the given regex")
  13. // Update returns true if update regex matches given test name.
  14. func Update(name string) bool {
  15. if updateRegex == nil || *updateRegex == "" {
  16. return false
  17. }
  18. return regexp.MustCompile(*updateRegex).MatchString(name)
  19. }
  20. // AssertGolden compares what's got and what's in the golden file. It updates
  21. // the golden file on-demand. It does nothing when the runtime is "windows".
  22. func AssertGolden(t testing.TB, path string, update bool, got any) {
  23. if runtime.GOOS == "windows" {
  24. t.Skip("Skipping testing on Windows")
  25. return
  26. }
  27. t.Helper()
  28. data := marshal(t, got)
  29. if update {
  30. err := os.MkdirAll(filepath.Dir(path), os.ModePerm)
  31. if err != nil {
  32. t.Fatalf("create directories for golden file %q: %v", path, err)
  33. }
  34. err = os.WriteFile(path, data, 0o640)
  35. if err != nil {
  36. t.Fatalf("update golden file %q: %v", path, err)
  37. }
  38. }
  39. golden, err := os.ReadFile(path)
  40. if err != nil {
  41. t.Fatalf("read golden file %q: %v", path, err)
  42. }
  43. assert.Equal(t, string(golden), string(data))
  44. }
  45. func marshal(t testing.TB, v any) []byte {
  46. t.Helper()
  47. switch v2 := v.(type) {
  48. case string:
  49. return []byte(v2)
  50. case []byte:
  51. return v2
  52. default:
  53. data, err := json.MarshalIndent(v, "", " ")
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. return data
  58. }
  59. }