state_test.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. package frankenphp
  2. import (
  3. "testing"
  4. "time"
  5. "github.com/stretchr/testify/assert"
  6. )
  7. func Test2GoroutinesYieldToEachOtherViaStates(t *testing.T) {
  8. threadState := &threadState{currentState: stateBooting}
  9. go func() {
  10. threadState.waitFor(stateInactive)
  11. assert.True(t, threadState.is(stateInactive))
  12. threadState.set(stateReady)
  13. }()
  14. threadState.set(stateInactive)
  15. threadState.waitFor(stateReady)
  16. assert.True(t, threadState.is(stateReady))
  17. }
  18. func TestStateShouldHaveCorrectAmountOfSubscribers(t *testing.T) {
  19. threadState := &threadState{currentState: stateBooting}
  20. // 3 subscribers waiting for different states
  21. go threadState.waitFor(stateInactive)
  22. go threadState.waitFor(stateInactive, stateShuttingDown)
  23. go threadState.waitFor(stateShuttingDown)
  24. assertNumberOfSubscribers(t, threadState, 3)
  25. threadState.set(stateInactive)
  26. assertNumberOfSubscribers(t, threadState, 1)
  27. assert.True(t, threadState.compareAndSwap(stateInactive, stateShuttingDown))
  28. assertNumberOfSubscribers(t, threadState, 0)
  29. }
  30. func assertNumberOfSubscribers(t *testing.T, threadState *threadState, expected int) {
  31. maxWaits := 10_000 // wait for 1 second max
  32. for i := 0; i < maxWaits; i++ {
  33. time.Sleep(100 * time.Microsecond)
  34. threadState.mu.RLock()
  35. if len(threadState.subscribers) == expected {
  36. threadState.mu.RUnlock()
  37. break
  38. }
  39. threadState.mu.RUnlock()
  40. }
  41. threadState.mu.RLock()
  42. assert.Len(t, threadState.subscribers, expected)
  43. threadState.mu.RUnlock()
  44. }