golden.go 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. return
  27. }
  28. t.Helper()
  29. data := marshal(t, got)
  30. if update {
  31. if err := ioutil.WriteFile(path, data, 0640); err != nil {
  32. t.Fatalf("update golden file %q: %s", path, err)
  33. }
  34. }
  35. golden, err := ioutil.ReadFile(path)
  36. if err != nil {
  37. t.Fatalf("read golden file %q: %s", path, err)
  38. }
  39. assert.Equal(t, string(golden), string(data))
  40. }
  41. func marshal(t testing.TB, v interface{}) []byte {
  42. t.Helper()
  43. switch v2 := v.(type) {
  44. case string:
  45. return []byte(v2)
  46. case []byte:
  47. return v2
  48. default:
  49. data, err := json.MarshalIndent(v, "", " ")
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. return data
  54. }
  55. }