forked from kardianos/service
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathservice_test.go
82 lines (72 loc) · 1.37 KB
/
service_test.go
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
74
75
76
77
78
79
80
81
82
// Copyright 2015 Daniel Theophanes.
// Use of this source code is governed by a zlib-style
// license that can be found in the LICENSE file.
package baobab
import (
"context"
"sync"
"testing"
"time"
)
func TestRunInterrupt(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
p := &program{}
sc := &Config{
Name: "go_baobab_test",
}
s, err := New(p, sc)
if err != nil {
t.Fatalf("New err: %s", err)
}
go func() {
<-time.After(1 * time.Second)
interruptProcess(t)
}()
stopped := make(chan struct{})
go func() {
timer := time.NewTimer(200 * time.Millisecond)
defer timer.Stop()
for {
select {
case <-timer.C:
p.mu.RLock()
if p.numStopped != 0 {
p.mu.RUnlock()
close(stopped)
return
}
p.mu.RUnlock()
timer.Reset(200 * time.Millisecond)
case <-ctx.Done():
return
}
}
}()
if err = s.Run(); err != nil {
t.Fatalf("Run() err: %s", err)
}
select {
case <-ctx.Done():
t.Fatalf("Run() hasn't been stopped")
case <-stopped:
// Success case - the program stopped.
}
}
type program struct {
numStopped int
mu sync.RWMutex
}
func (p *program) Start(s Service) error {
go p.run()
return nil
}
func (p *program) run() {
// Do work here
}
func (p *program) Stop(s Service) error {
p.mu.Lock()
defer p.mu.Unlock()
p.numStopped++
return nil
}