golden.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. "io/ioutil"
  9. "regexp"
  10. "testing"
  11. "github.com/stretchr/testify/assert"
  12. )
  13. var updateRegex = flag.String("update", "", "Update testdata of tests matching the given regex")
  14. // Update returns true if update regex mathces given test name.
  15. func Update(name string) bool {
  16. if updateRegex == nil || *updateRegex == "" {
  17. return false
  18. }
  19. return regexp.MustCompile(*updateRegex).MatchString(name)
  20. }
  21. // AssertGolden compares what's got and what's in the golden file. It updates
  22. // the golden file on-demand.
  23. func AssertGolden(t testing.TB, path string, update bool, got interface{}) {
  24. t.Helper()
  25. data := marshal(t, got)
  26. if update {
  27. if err := ioutil.WriteFile(path, data, 0640); err != nil {
  28. t.Fatalf("update golden file %q: %s", path, err)
  29. }
  30. }
  31. golden, err := ioutil.ReadFile(path)
  32. if err != nil {
  33. t.Fatalf("read golden file %q: %s", path, err)
  34. }
  35. assert.Equal(t, string(golden), string(data))
  36. }
  37. func marshal(t testing.TB, v interface{}) []byte {
  38. t.Helper()
  39. switch v2 := v.(type) {
  40. case string:
  41. return []byte(v2)
  42. case []byte:
  43. return v2
  44. default:
  45. data, err := json.MarshalIndent(v, "", " ")
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. return data
  50. }
  51. }