/
worker.go
73 lines (60 loc) · 2.06 KB
/
worker.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
package testing
import (
"sync"
"time"
"github.com/taskcluster/taskcluster/v28/tools/worker-runner/protocol"
)
// FakeWorker implements a fake worker, in terms of the protocol at least
type FakeWorker struct {
// The protocol with which to communicate with this worker. Use this
// as a protocol for testing worker-runner.
RunnerProtocol *protocol.Protocol
// The protocol representing the worker side; register for messages on
// this to confirm that messages were received
WorkerProtocol *protocol.Protocol
workerTransp *LocalTransport
runnerTransp *LocalTransport
}
// Close down the fake worker. Call this to dispose of resources.
func (wkr *FakeWorker) Close() {
wkr.workerTransp.Close()
wkr.runnerTransp.Close()
}
// Generate a function that can be called to assert that message of the given
// type has or has not been received. This is useful for building assertions.
func (wkr *FakeWorker) MessageReceivedFunc(msgType string, matcher func(msg protocol.Message) bool) func() bool {
received := false
receivedMutex := sync.Mutex{}
wkr.WorkerProtocol.Register(msgType, func(msg protocol.Message) {
if matcher == nil || matcher(msg) {
receivedMutex.Lock()
defer receivedMutex.Unlock()
received = true
}
})
return func() bool {
// allow the receive goroutine time to receive the message
time.Sleep(10 * time.Millisecond)
receivedMutex.Lock()
defer receivedMutex.Unlock()
return received
}
}
// Create a new fake worker with the given capabilities. The worker side
// of this protocol is started, but the runner side is not -- that is up
// to the caller.
func NewFakeWorkerWithCapabilities(capabilities ...string) *FakeWorker {
workerTransp, runnerTransp := NewLocalTransportPair()
workerProto := protocol.NewProtocol(workerTransp)
runnerProto := protocol.NewProtocol(runnerTransp)
for _, capability := range capabilities {
workerProto.AddCapability(capability)
}
workerProto.Start(true)
return &FakeWorker{
RunnerProtocol: runnerProto,
WorkerProtocol: workerProto,
workerTransp: workerTransp,
runnerTransp: runnerTransp,
}
}