-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patheventloop_test.go
More file actions
73 lines (65 loc) · 1.65 KB
/
eventloop_test.go
File metadata and controls
73 lines (65 loc) · 1.65 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"fmt"
"math/rand"
"os"
"testing"
"time"
)
func TestEventLoop(t *testing.T) {
var countEvent int
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
startServerCmd := func(ctx context.Context) Msg {
countEvent++
fmt.Println("> server starting")
return "SERVER_STARTED"
}
loadConfigCmd := func(ctx context.Context) Msg {
fmt.Println("> pretend load config")
s := rand.NewSource(time.Now().UnixNano())
r := rand.New(s)
if r.Intn(2) == 0 {
fmt.Println("> config failed")
return "CONFIG_LOAD_FAILED"
}
fmt.Println("> config ok")
return "CONFIG_LOAD_OK"
}
fileWaitForUpdateCmd := func(ctx context.Context) Msg {
fmt.Println("> waiting for a file update")
fmt.Println("> -------------------------")
return "FILE_UPDATED"
}
fileUpdateCmd := func(ctx context.Context) Msg {
fmt.Println("> pretend receive file update")
fmt.Println("> pretend stopping server if running")
return "FILE_UPDATED"
}
el, err := NewEventLoop(
[]LabelledCmd{
LabelledCmd{"CONFIG_LOAD_OK", startServerCmd},
LabelledCmd{"CONFIG_LOAD_FAILED", fileWaitForUpdateCmd},
LabelledCmd{"FILE_UPDATED", loadConfigCmd},
LabelledCmd{"SERVER_STARTED", fileWaitForUpdateCmd},
},
fileUpdateCmd,
fileWaitForUpdateCmd,
)
// update server started to exit on 4th "server restart"
el.cmdMap["SERVER_STARTED"] = func(ctx context.Context) Msg {
countEvent++
if countEvent > 3 {
cancel()
}
fmt.Println("> waiting for a file update")
fmt.Println("> -------------------------")
return "FILE_UPDATED"
}
if err != nil {
fmt.Println("new event loop error", err)
os.Exit(1)
}
el.Run(ctx)
}