lens @ 7dd8040d6d948d41f4e3cf632e868c640f09dd5b

 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)
14
15type (
16	mockCounterListProcessor struct {
17		done    bool
18		countTo int
19		counter int
20	}
21
22	mockContextListProcessor struct {
23	}
24)
25
26func TestListProcessorLimit(t *testing.T) {
27	mock := &mockCounterListProcessor{
28		countTo: 10000,
29	}
30	worker := NewWorkerFromListProcessor[int](mock, nil)
31
32	err := worker.Start(context.Background())
33	testkit.TestFatalError(t, "Start", err)
34
35	testkit.TestValue(t, "Start", mock.countTo, mock.counter)
36}
37
38func TestListProcessorContextCancelQuery(t *testing.T) {
39	mock := &mockContextListProcessor{}
40	worker := NewWorkerFromListProcessor[int](mock, nil)
41
42	ctx, cancel := context.WithCancel(context.Background())
43	var wg sync.WaitGroup
44
45	wg.Add(1)
46	go func() {
47		defer wg.Done()
48		err := worker.Start(ctx)
49		if errors.Is(err, context.Canceled) {
50			return
51		}
52		testkit.TestFatalError(t, "Start", err)
53	}()
54
55	cancel()
56	// this rely on timeout to test
57	wg.Wait()
58}
59
60func (m *mockCounterListProcessor) Query(_ context.Context) ([]int, error) {
61	if m.done {
62		return make([]int, 0), nil
63	}
64	values := make([]int, 0, m.countTo)
65	for i := 0; i < m.countTo; i++ {
66		values = append(values, rand.Int())
67	}
68
69	m.done = true
70	return values, nil
71}
72
73func (m *mockCounterListProcessor) Process(_ context.Context, _ int) error {
74	m.counter++
75	return nil
76}
77
78func (m *mockContextListProcessor) Query(_ context.Context) ([]int, error) {
79	// keeps returning the query so it can run in infinity loop
80	values := make([]int, 0, 10)
81	for i := 0; i < 10; i++ {
82		values = append(values, rand.Int())
83	}
84	return values, nil
85}
86
87func (m *mockContextListProcessor) Process(_ context.Context, _ int) error {
88	// do nothing
89	return nil
90}