example_test.go 876 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. package clockwork
  2. import (
  3. "sync"
  4. "testing"
  5. "time"
  6. )
  7. // my_func is an example of a time-dependent function, using an
  8. // injected clock
  9. func my_func(clock Clock, i *int) {
  10. clock.Sleep(3 * time.Second)
  11. *i += 1
  12. }
  13. // assert_state is an example of a state assertion in a test
  14. func assert_state(t *testing.T, i, j int) {
  15. if i != j {
  16. t.Fatalf("i %d, j %d", i, j)
  17. }
  18. }
  19. // TestMyFunc tests my_func's behaviour with a FakeClock
  20. func TestMyFunc(t *testing.T) {
  21. var i int
  22. c := NewFakeClock()
  23. var wg sync.WaitGroup
  24. wg.Add(1)
  25. go func() {
  26. my_func(c, &i)
  27. wg.Done()
  28. }()
  29. // Wait until my_func is actually sleeping on the clock
  30. c.BlockUntil(1)
  31. // Assert the initial state
  32. assert_state(t, i, 0)
  33. // Now advance the clock forward in time
  34. c.Advance(1 * time.Hour)
  35. // Wait until the function completes
  36. wg.Wait()
  37. // Assert the final state
  38. assert_state(t, i, 1)
  39. }