2
0

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