1// SPDX-License-Identifier: AGPL-3.0-or-later
2
3package usecase_test
4
5import (
6 "context"
7 "testing"
8
9 "github.com/stretchr/testify/assert"
10 "github.com/stretchr/testify/mock"
11
12 "bnema.dev/ermite/internal/domain"
13 "bnema.dev/ermite/internal/ports/mocks"
14 "bnema.dev/ermite/internal/usecase"
15)
16
17func TestSettledCountsQueuedPushesAndPullEvents(t *testing.T) {
18 trigger := mocks.NewAutoMergeTrigger(t)
19 u := newCIUnit(t, func(cfg *usecase.CIConfig) { cfg.TriggerQueue = 1; cfg.AutoMerge = trigger })
20 repo := name(t, "proj")
21 trigger.EXPECT().OnRepoChanged(mock.Anything, repo).Return().Times(3)
22 u.store.EXPECT().ListRunners(mock.Anything).Return(nil, nil).Once()
23 ctx := context.Background()
24 settled := func(n int64) bool { return u.ci.Settled(ctx, repo, n) }
25 assert.True(t, settled(1))
26 u.ci.QueuePush(ctx, repo)
27 u.ci.QueuePush(ctx, repo) // dropped: queue capacity is one
28 assert.False(t, settled(1))
29 assert.False(t, settled(2)) // pushes conservatively cover the whole repo
30 u.ci.QueuePull(repo, 1)
31 u.ci.QueuePull(repo, 1) // dropped: no counter leak
32 u.ci.PlanQueuedPush()
33 assert.False(t, settled(1))
34 assert.True(t, settled(2))
35 u.ci.FinishQueuedPull()
36 assert.True(t, settled(1))
37}
38
39func TestSettledWaitsForPushDiscoveryAndReleasesOnError(t *testing.T) {
40 mrs := mocks.NewMergeRequestStore(t)
41 entered, release := make(chan struct{}), make(chan struct{})
42 u := newCIUnit(t, func(cfg *usecase.CIConfig) {
43 cfg.MRs = mrs
44 cfg.Pull = mocks.NewPullGit(t)
45 cfg.PullStage = func(string) { close(entered); <-release }
46 })
47 repo := name(t, "proj")
48 mrs.EXPECT().OpenByTarget(mock.Anything, repo, mock.Anything, mock.Anything).Return(nil, false, nil)
49 mrs.EXPECT().OpenBySource(mock.Anything, repo, mock.Anything, mock.Anything).Return(nil, false, domain.ErrUnavailable)
50 u.store.EXPECT().ListRunners(mock.Anything).Return(nil, nil).Once()
51 done := make(chan struct{})
52 go func() {
53 u.ci.OnPush(context.Background(), repo, []domain.RefUpdate{{Ref: "refs/heads/feat", New: "1111111111111111111111111111111111111111"}}, domain.Root())
54 close(done)
55 }()
56 <-entered
57 u.ci.PlanQueuedPush()
58 assert.False(t, u.ci.Settled(context.Background(), repo, 1))
59 close(release)
60 <-done
61 assert.True(t, u.ci.Settled(context.Background(), repo, 1))
62}
63
64func TestSettledReleasesQueuedPushOnShutdown(t *testing.T) {
65 u := newCIUnit(t, nil)
66 repo := name(t, "proj")
67 u.ci.QueuePush(context.Background(), repo)
68 u.ci.Close(context.Background())
69 assert.True(t, u.ci.Settled(context.Background(), repo, 1))
70 u.ci.QueuePush(context.Background(), repo)
71 assert.True(t, u.ci.Settled(context.Background(), repo, 1))
72}