Commit 63beee72 authored by Adrian Sutton's avatar Adrian Sutton

op-challenger: Simplify worker to a single function.

parent 853da7d0
......@@ -5,34 +5,15 @@ import (
"sync"
)
type worker struct {
in <-chan job
out chan<- job
cancel func()
wg sync.WaitGroup
}
func (w *worker) Start(ctx context.Context) {
ctx, cancel := context.WithCancel(ctx)
w.cancel = cancel
w.wg.Add(1)
go w.loop(ctx)
}
func (w *worker) Stop() {
w.cancel()
w.wg.Wait()
}
func (w *worker) loop(ctx context.Context) {
defer w.wg.Done()
func runWorker(ctx context.Context, in <-chan job, out chan<- job, wg *sync.WaitGroup) {
defer wg.Done()
for {
select {
case <-ctx.Done():
return
case j := <-w.in:
case j := <-in:
j.resolved = j.player.ProgressGame(ctx)
w.out <- j
out <- j
}
}
}
......@@ -2,20 +2,21 @@ package scheduler
import (
"context"
"sync"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestShouldProcessJobs(t *testing.T) {
func TestWorkerShouldProcessJobsUntilContextDone(t *testing.T) {
in := make(chan job, 2)
out := make(chan job, 2)
w := &worker{
in: in,
out: out,
}
w.Start(context.Background())
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var wg sync.WaitGroup
go runWorker(ctx, in, out, &wg)
in <- job{
player: &stubPlayer{done: false},
......@@ -29,29 +30,10 @@ func TestShouldProcessJobs(t *testing.T) {
require.Equal(t, result1.resolved, false)
require.Equal(t, result2.resolved, true)
defer w.Stop()
}
func TestWorkerStopsWhenContextDone(t *testing.T) {
in := make(chan job, 2)
out := make(chan job, 2)
w := &worker{
in: in,
out: out,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
w.Start(ctx)
// Make sure the worker is up and running
in <- job{
player: &stubPlayer{done: false},
}
readWithTimeout(t, out)
// Cancel the context which should exit the worker
cancel()
w.wg.Wait()
wg.Wait()
}
type stubPlayer struct {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment