1//go:build unit
2
3package worker
4
5import (
6 "context"
7 "errors"
8 "math/rand"
9 "sync"
10 "testing"
11
12 "git.sr.ht/~gabrielgio/img/pkg/testkit"
13 "github.com/sirupsen/logrus"
14)
15
16type (
17 mockCounterListProcessor struct {
18 done bool
19 countTo int
20 counter int
21 }
22
23 mockContextListProcessor struct {
24 }
25)
26
27func TestListProcessorLimit(t *testing.T) {
28 var (
29 log = logrus.New()
30 scheduler = NewScheduler(1)
31 mock = &mockCounterListProcessor{countTo: 10000}
32 )
33
34 worker := NewWorkerFromBatchProcessor[int](mock, scheduler, log.WithField("context", "testing"))
35
36 err := worker.Start(context.Background())
37 testkit.TestFatalError(t, "Start", err)
38
39 testkit.TestValue(t, "Start", mock.countTo, mock.counter)
40}
41
42func TestListProcessorContextCancelQuery(t *testing.T) {
43 var (
44 log = logrus.New()
45 scheduler = NewScheduler(1)
46 mock = &mockContextListProcessor{}
47 )
48
49 worker := NewWorkerFromBatchProcessor[int](mock, scheduler, log.WithField("context", "testing"))
50
51 ctx, cancel := context.WithCancel(context.Background())
52 var wg sync.WaitGroup
53
54 wg.Add(1)
55 go func() {
56 defer wg.Done()
57 err := worker.Start(ctx)
58 if errors.Is(err, context.Canceled) {
59 return
60 }
61 testkit.TestFatalError(t, "Start", err)
62 }()
63
64 cancel()
65 // this rely on timeout to test
66 wg.Wait()
67}
68
69func (m *mockCounterListProcessor) Query(_ context.Context) ([]int, error) {
70 if m.done {
71 return make([]int, 0), nil
72 }
73 values := make([]int, 0, m.countTo)
74 for i := 0; i < m.countTo; i++ {
75 values = append(values, rand.Int())
76 }
77
78 m.done = true
79 return values, nil
80}
81
82func (m *mockCounterListProcessor) Process(_ context.Context, _ int) error {
83 m.counter++
84 return nil
85}
86
87func (m *mockContextListProcessor) Query(_ context.Context) ([]int, error) {
88 // keeps returning the query so it can run in infinity loop
89 values := make([]int, 0, 10)
90 for i := 0; i < 10; i++ {
91 values = append(values, rand.Int())
92 }
93 return values, nil
94}
95
96func (m *mockContextListProcessor) Process(_ context.Context, _ int) error {
97 // do nothing
98 return nil
99}