golden.go 1.5 KB

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