1
0

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