-
Notifications
You must be signed in to change notification settings - Fork 69
/
main.go
302 lines (237 loc) · 9.53 KB
/
main.go
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
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
/*
Copyright 2022 TriggerMesh Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package googlecloudsourcerepositories
import (
"context"
"encoding/json"
"time"
. "github.com/onsi/ginkgo/v2" //nolint:stylecheck
. "github.com/onsi/gomega" //nolint:stylecheck
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
clientset "k8s.io/client-go/kubernetes"
duckv1 "knative.dev/pkg/apis/duck/v1"
"google.golang.org/api/option"
"google.golang.org/api/sourcerepo/v1"
cloudevents "github.com/cloudevents/sdk-go/v2"
"github.com/triggermesh/triggermesh/test/e2e/framework"
"github.com/triggermesh/triggermesh/test/e2e/framework/apps"
"github.com/triggermesh/triggermesh/test/e2e/framework/bridges"
"github.com/triggermesh/triggermesh/test/e2e/framework/ducktypes"
e2egcloud "github.com/triggermesh/triggermesh/test/e2e/framework/gcloud"
e2erepo "github.com/triggermesh/triggermesh/test/e2e/framework/gcloud/repositories"
)
/* This test suite requires:
- A Google Cloud Service Account key in JSON format, exported in the environment as GCLOUD_SERVICEACCOUNT_KEY
- The name of the Google Cloud project exported in the environment as GCLOUD_PROJECT
*/
var sourceAPIVersion = schema.GroupVersion{
Group: "sources.triggermesh.io",
Version: "v1alpha1",
}
const (
sourceKind = "GoogleCloudSourceRepositoriesSource"
sourceResource = "googlecloudsourcerepositoriessources"
)
var _ = Describe("Google Cloud Source Repositories source", func() {
f := framework.New("googlecloudsourcerepositoriessource")
var ns string
var srcClient dynamic.ResourceInterface
var repoName string
var repoURL string
var serviceaccountKey string
var sink *duckv1.Destination
BeforeEach(func() {
ns = f.UniqueName
gvr := sourceAPIVersion.WithResource(sourceResource)
srcClient = f.DynamicClient.Resource(gvr).Namespace(ns)
})
Context("a source subscribes to notifications from a repository", func() {
var repoClient *sourcerepo.Service
var src *unstructured.Unstructured
var err error
BeforeEach(func() {
serviceaccountKey = e2egcloud.ServiceAccountKeyFromEnv()
gcloudProject := e2egcloud.ProjectNameFromEnv()
repoClient, err = sourcerepo.NewService(context.Background(), option.WithCredentialsJSON([]byte(serviceaccountKey)))
Expect(err).ToNot(HaveOccurred())
By("creating an event sink", func() {
sink = bridges.CreateEventDisplaySink(f.KubeClient, ns)
})
By("creating a source repository", func() {
repo := e2erepo.CreateRepository(repoClient, gcloudProject, f)
repoName = repo.Name
repoURL = repo.Url
DeferCleanup(func() {
By("deleting the source repository "+repoName, func() {
e2erepo.DeleteRepository(repoClient, repoName)
})
})
})
By("creating a GoogleCloudSourceRepositoriesSource object", func() {
src, err = createSource(srcClient, ns, "test-", sink,
withRepository(repoName),
withPublishServiceAccount(emailFromServiceAccountKey(serviceaccountKey)),
withServiceAccountKey(serviceaccountKey),
)
Expect(err).ToNot(HaveOccurred())
ducktypes.WaitUntilReady(f.DynamicClient, src)
})
})
When("an event occurs in the repository", func() {
BeforeEach(func() {
e2erepo.InitRepoAndCommit(repoURL)
})
Specify("the source generates an event", func() {
const receiveTimeout = 150 * time.Second
const pollInterval = 500 * time.Millisecond
var receivedEvents []cloudevents.Event
readReceivedEvents := readReceivedEvents(f.KubeClient, ns, sink.Ref.Name, &receivedEvents)
Eventually(readReceivedEvents, receiveTimeout, pollInterval).ShouldNot(BeEmpty())
Expect(receivedEvents).To(HaveLen(1))
e := receivedEvents[0]
Expect(e.Type()).To(Equal("com.google.cloud.sourcerepo.notification"))
Expect(e.Source()).To(Equal(repoName))
Expect(e.Extensions()["pubsubmsgeventtype"]).To(Equal("RefUpdate"))
})
})
})
When("a client creates a source object with invalid specs", func() {
// Those tests do not require a real repository or sink
BeforeEach(func() {
repoName = "projects/fake-project/repos/fake-repo"
serviceaccountKey = "fake-creds"
sink = &duckv1.Destination{
Ref: &duckv1.KReference{
APIVersion: "fake/v1",
Kind: "Fake",
Name: "fake",
},
}
})
// Here we use
// "Specify: the API server rejects ..., By: setting an invalid ..."
// instead of
// "When: it sets an invalid ..., Specify: the API server rejects ..."
// to avoid creating a namespace for each spec, due to their simplicity.
Specify("the API server rejects the creation of that object", func() {
By("setting an invalid repository", func() {
const invalidRepoName = "projects/fake-project/repos//"
_, err := createSource(srcClient, ns, "test-invalid-repository-", sink,
withRepository(invalidRepoName),
withServiceAccountKey(serviceaccountKey),
)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("spec.repository: Invalid value: "))
})
By("omitting the repository", func() {
_, err := createSource(srcClient, ns, "test-norepo-", sink,
withServiceAccountKey(serviceaccountKey),
)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring("spec.repository: Required value"))
})
By("setting an invalid publish service account", func() {
const invalidServiceAccountEmail = "not-an-email"
_, err := createSource(srcClient, ns, "test-invalid-sa-", sink,
withRepository(repoName),
withPublishServiceAccount(invalidServiceAccountEmail),
withServiceAccountKey(serviceaccountKey),
)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring(
"spec.publishServiceAccount in body must be of type email: "))
})
By("setting empty credentials", func() {
_, err := createSource(srcClient, ns, "test-nocreds-", sink,
withRepository(repoName),
withServiceAccountKey(""),
)
Expect(err).To(HaveOccurred())
Expect(err.Error()).To(ContainSubstring(
`"spec.auth.serviceAccountKey" must validate one and only one schema (oneOf).`))
})
})
})
})
// createSource creates a GoogleCloudSourceRepositoriesSource object initialized with the given options.
func createSource(srcClient dynamic.ResourceInterface, namespace, namePrefix string,
sink *duckv1.Destination, opts ...sourceOption) (*unstructured.Unstructured, error) {
src := &unstructured.Unstructured{}
src.SetAPIVersion(sourceAPIVersion.String())
src.SetKind(sourceKind)
src.SetNamespace(namespace)
src.SetGenerateName(namePrefix)
if err := unstructured.SetNestedMap(src.Object, ducktypes.DestinationToMap(sink), "spec", "sink"); err != nil {
framework.FailfWithOffset(2, "Failed to set spec.sink field: %s", err)
}
for _, opt := range opts {
opt(src)
}
return srcClient.Create(context.Background(), src, metav1.CreateOptions{})
}
type sourceOption func(*unstructured.Unstructured)
func withRepository(repo string) sourceOption {
return func(src *unstructured.Unstructured) {
if err := unstructured.SetNestedField(src.Object, repo, "spec", "repository"); err != nil {
framework.FailfWithOffset(3, "Failed to set spec.repository field: %s", err)
}
}
}
func withPublishServiceAccount(saEmail string) sourceOption {
return func(src *unstructured.Unstructured) {
if err := unstructured.SetNestedField(src.Object, saEmail, "spec", "publishServiceAccount"); err != nil {
framework.FailfWithOffset(3, "Failed to set spec.publishServiceAccount field: %s", err)
}
}
}
func withServiceAccountKey(key string) sourceOption {
svcAccKeyMap := make(map[string]interface{})
if key != "" {
svcAccKeyMap = map[string]interface{}{"value": key}
}
return func(src *unstructured.Unstructured) {
if err := unstructured.SetNestedMap(src.Object, svcAccKeyMap, "spec", "auth", "serviceAccountKey"); err != nil {
framework.FailfWithOffset(3, "Failed to set spec.auth.serviceAccountKey field: %s", err)
}
}
}
// readReceivedEvents returns a function that reads CloudEvents received by the
// event-display application and stores the result as the value of the given
// `receivedEvents` variable.
// The returned function signature satisfies the contract expected by
// gomega.Eventually: no argument and one or more return values.
func readReceivedEvents(c clientset.Interface, namespace, eventDisplayDeplName string,
receivedEvents *[]cloudevents.Event) func() []cloudevents.Event {
return func() []cloudevents.Event {
ev := bridges.ReceivedEventDisplayEvents(
apps.GetLogs(c, namespace, eventDisplayDeplName),
)
*receivedEvents = ev
return ev
}
}
// emailFromServiceAccountKey returns the value of the client_email attribute
// from the given service account key JSON.
func emailFromServiceAccountKey(saKeyJSON string) string {
type serviceAccountKey struct {
ClientEmail string `json:"client_email"`
}
saKey := &serviceAccountKey{}
if err := json.Unmarshal([]byte(saKeyJSON), saKey); err != nil {
framework.FailfWithOffset(2, "Failed to deserialize service account key from JSON: %s", err)
}
return saKey.ClientEmail
}