lazy_obj.go 688 B

12345678910111213141516171819202122232425262728293031323334
  1. package testutil
  2. import (
  3. "github.com/stretchr/testify/require"
  4. )
  5. // LazyObj is a function that returns an object of type T.
  6. type LazyObj[T any] func() T
  7. // LazyObjInit is a function that initializes and returns an object of type T and an error if any.
  8. type LazyObjInit[T any] func() (T, error)
  9. // NewLazyObj creates a new LazyObj that initializes the object on the first call.
  10. func NewLazyObj[T any](t require.TestingT, init LazyObjInit[T]) LazyObj[T] {
  11. if h, ok := t.(interface{ Helper() }); ok {
  12. h.Helper()
  13. }
  14. var obj *T
  15. return func() T {
  16. if obj != nil {
  17. return *obj
  18. }
  19. o, err := init()
  20. if err != nil {
  21. require.NoError(t, err)
  22. }
  23. obj = &o
  24. return o
  25. }
  26. }