test_data_provider.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package testutil
  2. import (
  3. "bytes"
  4. "io"
  5. "os"
  6. "path/filepath"
  7. "testing"
  8. "github.com/stretchr/testify/require"
  9. )
  10. const (
  11. // TestDataFolderName is the name of the testdata directory
  12. TestDataFolderName = "testdata"
  13. )
  14. // TestDataProvider provides access to test data images
  15. type TestDataProvider struct {
  16. path string
  17. t *testing.T
  18. }
  19. // New creates a new TestDataProvider
  20. func NewTestDataProvider(t *testing.T) *TestDataProvider {
  21. // if h, ok := t.(interface{ Helper() }); ok {
  22. // h.Helper()
  23. // }
  24. t.Helper()
  25. path, err := findProjectRoot()
  26. if err != nil {
  27. require.NoError(t, err)
  28. }
  29. return &TestDataProvider{
  30. path: filepath.Join(path, TestDataFolderName),
  31. t: t,
  32. }
  33. }
  34. // findProjectRoot finds the absolute path to the project root by looking for go.mod
  35. func findProjectRoot() (string, error) {
  36. // Start from current working directory
  37. wd, err := os.Getwd()
  38. if err != nil {
  39. return "", err
  40. }
  41. // Walk up the directory tree looking for go.mod
  42. dir := wd
  43. for {
  44. goModPath := filepath.Join(dir, "go.mod")
  45. if _, err := os.Stat(goModPath); err == nil {
  46. // Found go.mod, this is our project root
  47. return dir, nil
  48. }
  49. parent := filepath.Dir(dir)
  50. if parent == dir {
  51. // Reached filesystem root without finding go.mod
  52. break
  53. }
  54. dir = parent
  55. }
  56. return "", os.ErrNotExist
  57. }
  58. // Root returns the absolute path to the testdata directory
  59. func (p *TestDataProvider) Root() string {
  60. return p.path
  61. }
  62. // Path returns the absolute path to a file in the testdata directory
  63. func (p *TestDataProvider) Path(parts ...string) string {
  64. allParts := append([]string{p.path}, parts...)
  65. return filepath.Join(allParts...)
  66. }
  67. // Read reads a test data file and returns it as bytes
  68. func (p *TestDataProvider) Read(name string) []byte {
  69. p.t.Helper()
  70. data, err := os.ReadFile(p.Path(name))
  71. require.NoError(p.t, err)
  72. return data
  73. }
  74. // Data reads a test data file and returns it as imagedata.ImageData
  75. func (p *TestDataProvider) Reader(name string) *bytes.Reader {
  76. return bytes.NewReader(p.Read(name))
  77. }
  78. // FileEqualsToReader compares the contents of a test data file with the contents of the given reader
  79. func (p *TestDataProvider) FileEqualsToReader(name string, reader io.Reader) bool {
  80. expected := p.Reader(name)
  81. return ReadersEqual(p.t, expected, reader)
  82. }