aboutsummaryrefslogtreecommitdiff
path: root/pkg/worker/list_processor_test.go
blob: 21489e82685e62ed1e6f85d04f5209dbc59d7feb (plain)
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//go:build unit

package worker

import (
	"context"
	"errors"
	"log/slog"
	"math/rand"
	"sync"
	"testing"

	"git.sr.ht/~gabrielgio/img/pkg/testkit"
)

type (
	mockCounterListProcessor struct {
		done    bool
		countTo int
		counter int
	}

	mockContextListProcessor struct {
	}
)

func TestListProcessorLimit(t *testing.T) {
	var (
		log       = slog.Default()
		scheduler = NewScheduler(1)
		mock      = &mockCounterListProcessor{countTo: 10000}
	)

	worker := NewTaskFromBatchProcessor[int](mock, scheduler, log.With("context", "testing"))

	err := worker.Start(context.Background())
	testkit.TestFatalError(t, "Start", err)

	testkit.TestValue(t, "Start", mock.countTo, mock.counter)
}

func TestListProcessorContextCancelQuery(t *testing.T) {
	var (
		log       = slog.Default()
		scheduler = NewScheduler(1)
		mock      = &mockContextListProcessor{}
	)

	worker := NewTaskFromBatchProcessor[int](mock, scheduler, log.With("context", "testing"))

	ctx, cancel := context.WithCancel(context.Background())
	var wg sync.WaitGroup

	wg.Add(1)
	go func() {
		defer wg.Done()
		err := worker.Start(ctx)
		if errors.Is(err, context.Canceled) {
			return
		}
		testkit.TestFatalError(t, "Start", err)
	}()

	cancel()
	// this rely on timeout to test
	wg.Wait()
}

func (m *mockCounterListProcessor) Query(_ context.Context) ([]int, error) {
	if m.done {
		return make([]int, 0), nil
	}
	values := make([]int, 0, m.countTo)
	for i := 0; i < m.countTo; i++ {
		values = append(values, rand.Int())
	}

	m.done = true
	return values, nil
}

func (m *mockCounterListProcessor) Process(_ context.Context, _ int) error {
	m.counter++
	return nil
}

func (m *mockContextListProcessor) Query(_ context.Context) ([]int, error) {
	// keeps returning the query so it can run in infinity loop
	values := make([]int, 0, 10)
	for i := 0; i < 10; i++ {
		values = append(values, rand.Int())
	}
	return values, nil
}

func (m *mockContextListProcessor) Process(_ context.Context, _ int) error {
	// do nothing
	return nil
}