golden.go 1.6 KB

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