lasy_suite.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. package testutil
  2. import (
  3. "context"
  4. "github.com/stretchr/testify/suite"
  5. )
  6. // LazySuite is a test suite that automatically resets [LazyObj] instances.
  7. // It uses [LazySuite.AfterTest] to perform the reset after each test,
  8. // so if you also use this function in your test suite, don't forget to call
  9. // [LazySuite.AfterTest] or [LazySuite.ResetLazyObjects] explicitly.
  10. type LazySuite struct {
  11. suite.Suite
  12. resets []context.CancelFunc
  13. }
  14. // Lazy returns the LazySuite instance itself.
  15. // Needed to implement [LazySuiteFrom].
  16. func (s *LazySuite) Lazy() *LazySuite {
  17. return s
  18. }
  19. // AfterTest is called by testify after each test.
  20. // If you also use this function in your test suite, don't forget to call
  21. // [LazySuite.AfterTest] or [LazySuite.ResetLazyObjects] explicitly.
  22. func (s *LazySuite) AfterTest(_, _ string) {
  23. // Reset lazy objects after each test
  24. s.ResetLazyObjects()
  25. }
  26. // ResetLazyObjects resets all lazy objects created with [NewLazySuiteObj]
  27. func (s *LazySuite) ResetLazyObjects() {
  28. for _, reset := range s.resets {
  29. reset()
  30. }
  31. }
  32. type LazySuiteFrom interface {
  33. Lazy() *LazySuite
  34. }
  35. // NewLazySuiteObj creates a new [LazyObj] instance and registers its cleanup function
  36. // to a provided [LazySuite].
  37. func NewLazySuiteObj[T any](
  38. s LazySuiteFrom,
  39. newFn LazyObjNew[T],
  40. dropFn ...LazyObjDrop[T],
  41. ) (LazyObj[T], context.CancelFunc) {
  42. // Get the [LazySuite] instance
  43. lazy := s.Lazy()
  44. // Create the [LazyObj] instance
  45. obj, cancel := newLazyObj(lazy, newFn, dropFn...)
  46. // Add cleanup function to the resets list
  47. lazy.resets = append(lazy.resets, cancel)
  48. return obj, cancel
  49. }