servicegroup_test.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package service
  2. import (
  3. "sync"
  4. "testing"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. var (
  8. number = 1
  9. mutex sync.Mutex
  10. done = make(chan struct{})
  11. )
  12. type mockedService struct {
  13. quit chan struct{}
  14. multiplier int
  15. }
  16. func newMockedService(multiplier int) *mockedService {
  17. return &mockedService{
  18. quit: make(chan struct{}),
  19. multiplier: multiplier,
  20. }
  21. }
  22. func (s *mockedService) Start() {
  23. mutex.Lock()
  24. number *= s.multiplier
  25. mutex.Unlock()
  26. done <- struct{}{}
  27. <-s.quit
  28. }
  29. func (s *mockedService) Stop() {
  30. close(s.quit)
  31. }
  32. func TestServiceGroup(t *testing.T) {
  33. multipliers := []int{2, 3, 5, 7}
  34. want := 1
  35. group := NewServiceGroup()
  36. for _, multiplier := range multipliers {
  37. want *= multiplier
  38. service := newMockedService(multiplier)
  39. group.Add(service)
  40. }
  41. go group.Start()
  42. for i := 0; i < len(multipliers); i++ {
  43. <-done
  44. }
  45. group.Stop()
  46. mutex.Lock()
  47. defer mutex.Unlock()
  48. assert.Equal(t, want, number)
  49. }
  50. func TestServiceGroup_WithStart(t *testing.T) {
  51. multipliers := []int{2, 3, 5, 7}
  52. want := 1
  53. var wait sync.WaitGroup
  54. var lock sync.Mutex
  55. wait.Add(len(multipliers))
  56. group := NewServiceGroup()
  57. for _, multiplier := range multipliers {
  58. mul := multiplier
  59. group.Add(WithStart(func() {
  60. lock.Lock()
  61. want *= mul
  62. lock.Unlock()
  63. wait.Done()
  64. }))
  65. }
  66. go group.Start()
  67. wait.Wait()
  68. group.Stop()
  69. lock.Lock()
  70. defer lock.Unlock()
  71. assert.Equal(t, 210, want)
  72. }
  73. func TestServiceGroup_WithStarter(t *testing.T) {
  74. multipliers := []int{2, 3, 5, 7}
  75. want := 1
  76. var wait sync.WaitGroup
  77. var lock sync.Mutex
  78. wait.Add(len(multipliers))
  79. group := NewServiceGroup()
  80. for _, multiplier := range multipliers {
  81. mul := multiplier
  82. group.Add(WithStarter(mockedStarter{
  83. fn: func() {
  84. lock.Lock()
  85. want *= mul
  86. lock.Unlock()
  87. wait.Done()
  88. },
  89. }))
  90. }
  91. go group.Start()
  92. wait.Wait()
  93. group.Stop()
  94. lock.Lock()
  95. defer lock.Unlock()
  96. assert.Equal(t, 210, want)
  97. }
  98. type mockedStarter struct {
  99. fn func()
  100. }
  101. func (s mockedStarter) Start() {
  102. s.fn()
  103. }