File: example_test.go

package info (click to toggle)
golang-github-jonboulle-clockwork 0.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, buster, sid
  • size: 100 kB
  • ctags: 28
  • sloc: makefile: 2
file content (49 lines) | stat: -rw-r--r-- 876 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package clockwork

import (
	"sync"
	"testing"
	"time"
)

// my_func is an example of a time-dependent function, using an
// injected clock
func my_func(clock Clock, i *int) {
	clock.Sleep(3 * time.Second)
	*i += 1
}

// assert_state is an example of a state assertion in a test
func assert_state(t *testing.T, i, j int) {
	if i != j {
		t.Fatalf("i %d, j %d", i, j)
	}
}

// TestMyFunc tests my_func's behaviour with a FakeClock
func TestMyFunc(t *testing.T) {
	var i int
	c := NewFakeClock()

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		my_func(c, &i)
		wg.Done()
	}()

	// Wait until my_func is actually sleeping on the clock
	c.BlockUntil(1)

	// Assert the initial state
	assert_state(t, i, 0)

	// Now advance the clock forward in time
	c.Advance(1 * time.Hour)

	// Wait until the function completes
	wg.Wait()

	// Assert the final state
	assert_state(t, i, 1)
}