Repository navigation
Expand file tree
/
Copy pathservice_github_sync_test.go
More file actions
267 lines (240 loc) · 9.24 KB
/
Copy pathservice_github_sync_test.go
File metadata and controls
267 lines (240 loc) · 9.24 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
package kata
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"path/filepath"
"sync"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
internalconfig "go.kenn.io/kata/internal/config"
"go.kenn.io/kata/internal/db"
"go.kenn.io/kata/internal/githubsync"
)
func TestServiceGitHubSyncConfigDrivesHandlersAndRunner(t *testing.T) {
t.Setenv("KATA_GITHUB_SYNC_ALLOWED_HOSTS", "github.example")
fetcher := &serviceGitHubFetcher{
repositoryCalls: make(chan githubsync.Binding, 2),
}
var resolved internalconfig.GitHubSyncConfig
service, err := newService(context.Background(), Config{
DSN: filepath.Join(t.TempDir(), "service.db"),
Auth: AuthConfig{TrustCallerAuthentication: true},
GitHubSync: GitHubSyncConfig{ //nolint:gosec // TokenEnv is an environment variable name, not a credential.
TokenEnv: " EXAMPLE_GITHUB_TOKEN ",
TokenHost: " GitHub.Example ",
Apps: []GitHubAppConfig{{
Host: " GitHub.Example ", Owner: " example-owner ",
AppID: 123, InstallationID: 456, PrivateKeyPath: " /keys/example.pem ",
}},
},
}, serviceDeps{
gitHubSyncFetcherFactory: func(cfg internalconfig.GitHubSyncConfig) githubsync.Fetcher {
resolved = cfg
return fetcher
},
})
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, service.Close()) })
assert.Equal(t, internalconfig.GitHubSyncConfig{ //nolint:gosec // TokenEnv is an environment variable name, not a credential.
TokenEnv: "EXAMPLE_GITHUB_TOKEN", TokenHost: "github.example",
Apps: []internalconfig.GitHubAppConfig{{
Host: "github.example", Owner: "example-owner", AppID: 123,
InstallationID: 456, PrivateKeyPath: "/keys/example.pem",
}},
}, resolved)
project, err := service.store.CreateProject(context.Background(), "example-project")
require.NoError(t, err)
server := httptest.NewServer(service.Handler())
t.Cleanup(server.Close)
body, err := json.Marshal(map[string]any{
"config": map[string]any{
"host": "github.example", "owner": "example-owner", "repo": "example-repo",
},
})
require.NoError(t, err)
response, err := http.Post(
server.URL+"/api/v1/projects/"+fmt.Sprint(project.ID)+"/issue-sync/github/enable",
"application/json", bytes.NewReader(body),
)
require.NoError(t, err)
defer func() { _ = response.Body.Close() }()
require.Equal(t, http.StatusOK, response.StatusCode)
select {
case call := <-fetcher.repositoryCalls:
assert.Equal(t, githubsync.Binding{
Host: "github.example", Owner: "example-owner", Repo: "example-repo",
}, call)
case <-time.After(2 * time.Second):
require.Fail(t, "configured GitHub fetcher was not used by the HTTP handler")
}
runCtx, cancelRun := context.WithCancel(context.Background())
runDone := make(chan error, 1)
go func() { runDone <- service.Run(runCtx) }()
select {
case call := <-fetcher.repositoryCalls:
assert.Equal(t, githubsync.Binding{
Host: "github.example", Owner: "example-owner", Repo: "example-repo",
}, call)
case <-time.After(2 * time.Second):
require.Fail(t, "configured GitHub fetcher was not used by the background runner")
}
cancelRun()
require.NoError(t, <-runDone)
}
func TestServiceRunProcessesEnabledGitHubSyncBinding(t *testing.T) {
fetcher := &serviceGitHubFetcher{
repositoryCalls: make(chan githubsync.Binding, 1),
}
service, err := newService(context.Background(), Config{
DSN: filepath.Join(t.TempDir(), "service.db"),
Auth: AuthConfig{TrustCallerAuthentication: true},
}, serviceDeps{gitHubSyncFetcher: fetcher})
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, service.Close()) })
project, err := service.store.CreateProject(context.Background(), "example-project")
require.NoError(t, err)
titlePrefix := true
bindingConfig, err := githubsync.EncodeConfig(githubsync.Config{
Host: "github.com", Owner: "example-owner", Repo: "example-repo",
RepoID: 12345, TitlePrefix: &titlePrefix,
})
require.NoError(t, err)
_, err = service.store.UpsertIssueSyncBinding(context.Background(), db.UpsertIssueSyncBindingParams{
ProjectID: project.ID, Provider: "github", SourceKey: "github:R_exampleNode",
RemoteID: "R_exampleNode", DisplayName: "example-owner/example-repo",
Config: bindingConfig, IntervalSeconds: 300,
})
require.NoError(t, err)
runCtx, cancelRun := context.WithCancel(context.Background())
runDone := make(chan error, 1)
go func() { runDone <- service.Run(runCtx) }()
select {
case call := <-fetcher.repositoryCalls:
assert.Equal(t, githubsync.Binding{
Host: "github.com", Owner: "example-owner", Repo: "example-repo",
}, call)
case <-time.After(2 * time.Second):
require.Fail(t, "GitHub sync worker did not process the enabled binding")
}
require.Eventually(t, func() bool {
status, statusErr := service.store.IssueSyncStatusByProject(context.Background(), project.ID)
return statusErr == nil && status.LastSuccessAt != nil
}, 2*time.Second, 10*time.Millisecond)
cancelRun()
select {
case runErr := <-runDone:
require.NoError(t, runErr)
case <-time.After(2 * time.Second):
require.Fail(t, "Run did not stop after cancellation")
}
}
func TestServiceRunShowsGitHubSyncProgressForScheduledRun(t *testing.T) {
ctx := context.Background()
fetcher := &serviceGitHubProgressFetcher{
issuesStarted: make(chan struct{}),
releaseIssues: make(chan struct{}),
}
service, err := newService(ctx, Config{
DSN: filepath.Join(t.TempDir(), "service.db"),
Auth: AuthConfig{TrustCallerAuthentication: true},
}, serviceDeps{gitHubSyncFetcher: fetcher})
require.NoError(t, err)
t.Cleanup(func() { require.NoError(t, service.Close()) })
project, err := service.store.CreateProject(ctx, "example-project")
require.NoError(t, err)
bindingConfig, err := githubsync.EncodeConfig(githubsync.Config{
Host: "github.com", Owner: "example-owner", Repo: "example-repo", RepoID: 12345,
})
require.NoError(t, err)
_, err = service.store.UpsertIssueSyncBinding(ctx, db.UpsertIssueSyncBindingParams{
ProjectID: project.ID, Provider: "github", SourceKey: "github:R_exampleNode",
RemoteID: "R_exampleNode", DisplayName: "example-owner/example-repo",
Config: bindingConfig, IntervalSeconds: 300,
})
require.NoError(t, err)
runCtx, cancelRun := context.WithCancel(ctx)
runDone := make(chan error, 1)
go func() { runDone <- service.Run(runCtx) }()
t.Cleanup(func() {
fetcher.release()
cancelRun()
select {
case runErr := <-runDone:
require.NoError(t, runErr)
case <-time.After(5 * time.Second):
require.FailNow(t, "Run did not stop after cancellation")
}
})
server := httptest.NewServer(service.Handler())
t.Cleanup(server.Close)
select {
case <-fetcher.issuesStarted:
case <-time.After(5 * time.Second):
require.FailNow(t, "scheduled GitHub sync did not reach issue fetch")
}
response, err := http.Get(fmt.Sprintf("%s/api/v1/projects/%d/issue-sync/github/status", server.URL, project.ID))
require.NoError(t, err)
defer func() { _ = response.Body.Close() }()
require.Equal(t, http.StatusOK, response.StatusCode)
var out struct {
Status struct {
State string `json:"state"`
Progress *struct {
Phase string `json:"phase"`
} `json:"progress"`
} `json:"status"`
}
require.NoError(t, json.NewDecoder(response.Body).Decode(&out))
assert.Equal(t, "running", out.Status.State)
require.NotNil(t, out.Status.Progress)
assert.Equal(t, "issues", out.Status.Progress.Phase)
}
type serviceGitHubFetcher struct {
repositoryCalls chan githubsync.Binding
}
func (f *serviceGitHubFetcher) Repository(_ context.Context, host, owner, repo string) (githubsync.Repository, error) {
f.repositoryCalls <- githubsync.Binding{Host: host, Owner: owner, Repo: repo}
return githubsync.Repository{NodeID: "R_exampleNode", ID: 12345, FullName: "example-owner/example-repo"}, nil
}
func (*serviceGitHubFetcher) Issues(context.Context, githubsync.Binding, *time.Time) ([]githubsync.Issue, error) {
return nil, nil
}
func (*serviceGitHubFetcher) Comments(context.Context, githubsync.Binding, int) ([]githubsync.Comment, error) {
return nil, nil
}
func (*serviceGitHubFetcher) ParentData(context.Context, githubsync.Binding, githubsync.ParentRequest) (githubsync.ParentData, error) {
return githubsync.ParentData{Scan: githubsync.ParentScanUnsupported}, nil
}
type serviceGitHubProgressFetcher struct {
issuesStarted chan struct{}
releaseIssues chan struct{}
startedOnce sync.Once
releaseOnce sync.Once
}
func (*serviceGitHubProgressFetcher) Repository(context.Context, string, string, string) (githubsync.Repository, error) {
return githubsync.Repository{NodeID: "R_exampleNode", ID: 12345, FullName: "example-owner/example-repo"}, nil
}
func (f *serviceGitHubProgressFetcher) Issues(ctx context.Context, _ githubsync.Binding, _ *time.Time) ([]githubsync.Issue, error) {
f.startedOnce.Do(func() { close(f.issuesStarted) })
select {
case <-f.releaseIssues:
return nil, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
func (*serviceGitHubProgressFetcher) Comments(context.Context, githubsync.Binding, int) ([]githubsync.Comment, error) {
return nil, nil
}
func (*serviceGitHubProgressFetcher) ParentData(context.Context, githubsync.Binding, githubsync.ParentRequest) (githubsync.ParentData, error) {
return githubsync.ParentData{Scan: githubsync.ParentScanUnsupported}, nil
}
func (f *serviceGitHubProgressFetcher) release() {
f.releaseOnce.Do(func() { close(f.releaseIssues) })
}