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
|
package suture
import (
"fmt"
"testing"
)
const (
JobLimit = 2
)
type IncrementorJob struct {
current int
next chan int
stop chan bool
}
func (i *IncrementorJob) Stop() {
fmt.Println("Stopping the service")
i.stop <- true
}
func (i *IncrementorJob) Serve() {
for {
select {
case i.next <- i.current + 1:
i.current++
if i.current >= JobLimit {
return
}
case <-i.stop:
// We sync here just to guarantee the output of "Stopping the service",
// so this passes the test reliably.
// Most services would simply "return" here.
i.stop <- true
return
}
}
}
func (i *IncrementorJob) Complete() bool {
// fmt.Println("IncrementorJob exited as Complete()")
return i.current >= JobLimit
}
func TestCompleteJob(t *testing.T) {
supervisor := NewSimple("Supervisor")
service := &IncrementorJob{0, make(chan int), make(chan bool)}
supervisor.Add(service)
supervisor.ServeBackground()
fmt.Println("Got:", <-service.next)
fmt.Println("Got:", <-service.next)
<-service.stop
fmt.Println("IncrementorJob exited as Complete()")
supervisor.Stop()
// Output:
// Got: 1
// Got: 2
// Stopping the service
}
|