lens @ 398ae343e6a33fb81f82380b17081b8f9bae328a

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