Debian Codegraph @

pkg/services/incident/opsgenie/opsgenie_test.go

raw
1 package opsgenie
2
3 import (
4 "bytes"
5 "crypto/tls"
6 "fmt"
7 "io"
8 "log"
9 "net"
10 "net/http"
11 "net/http/httptest"
12 "net/url"
13 "testing"
14
15 "github.com/onsi/ginkgo/v2"
16 "github.com/onsi/gomega"
17
18 "github.com/nicholas-fedor/shoutrrr/pkg/types"
19 )
20
21 const (
22 mockAPIKey = "eb243592-faa2-4ba2-a551q-1afdf565c889"
23 mockHost = "api.opsgenie.com"
24 )
25
26 var _ = ginkgo.Describe("the OpsGenie service", func() {
27 var (
28 // a simulated http server to mock out OpsGenie itself
29 mockServer *httptest.Server
30 // the host of our mock server
31 mockHost string
32 // function to check if the http request received by the mock server is as expected
33 checkRequest func(body string, header http.Header)
34 // the shoutrrr OpsGenie service
35 service *Service
36 // just a mock logger
37 mockLogger *log.Logger
38 )
39
40 ginkgo.BeforeEach(func() {
41 // Initialize a mock http server
42 httpHandler := func(_ http.ResponseWriter, r *http.Request) {
43 body, err := io.ReadAll(r.Body)
44 gomega.Expect(err).ToNot(gomega.HaveOccurred())
45
46 defer func() { _ = r.Body.Close() }()
47
48 checkRequest(string(body), r.Header)
49 }
50 mockServer = httptest.NewTLSServer(http.HandlerFunc(httpHandler))
51
52 // Our mock server doesn't have a valid cert
53 http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{
54 InsecureSkipVerify: true,
55 }
56
57 // Determine the host of our mock http server
58 mockServerURL, err := url.Parse(mockServer.URL)
59 gomega.Expect(err).ToNot(gomega.HaveOccurred())
60
61 mockHost = mockServerURL.Host
62
63 // Initialize a mock logger
64 var buf bytes.Buffer
65
66 mockLogger = log.New(&buf, "", 0)
67 })
68
69 ginkgo.AfterEach(func() {
70 mockServer.Close()
71 })
72
73 ginkgo.Context("without query parameters", func() {
74 ginkgo.BeforeEach(func() {
75 // Initialize service
76 serviceURL, err := url.Parse(fmt.Sprintf("opsgenie://%s/%s", mockHost, mockAPIKey))
77 gomega.Expect(err).ToNot(gomega.HaveOccurred())
78
79 service = &Service{}
80 err = service.Initialize(serviceURL, mockLogger)
81 gomega.Expect(err).ToNot(gomega.HaveOccurred())
82 })
83
84 ginkgo.When("sending a simple alert", func() {
85 ginkgo.It("should send a request to our mock OpsGenie server", func() {
86 checkRequest = func(body string, header http.Header) {
87 gomega.Expect(header["Authorization"][0]).
88 To(gomega.Equal("GenieKey " + mockAPIKey))
89 gomega.Expect(header["Content-Type"][0]).To(gomega.Equal("application/json"))
90 gomega.Expect(body).To(gomega.Equal(`{"message":"hello world"}`))
91 }
92
93 err := service.Send("hello world", &types.Params{})
94 gomega.Expect(err).ToNot(gomega.HaveOccurred())
95 })
96 })
97
98 ginkgo.When("sending an alert with runtime parameters", func() {
99 ginkgo.It(
100 "should send a request to our mock OpsGenie server with all fields populated from runtime parameters",
101 func() {
102 checkRequest = func(body string, header http.Header) {
103 gomega.Expect(header["Authorization"][0]).
104 To(gomega.Equal("GenieKey " + mockAPIKey))
105 gomega.Expect(header["Content-Type"][0]).
106 To(gomega.Equal("application/json"))
107 gomega.Expect(body).To(gomega.Equal(`{"` +
108 `message":"An example alert message",` +
109 `"alias":"Life is too short for no alias",` +
110 `"description":"Every alert needs a description",` +
111 `"responders":[{"type":"team","id":"4513b7ea-3b91-438f-b7e4-e3e54af9147c"},{"type":"team","name":"NOC"},{"type":"user","username":"Donald"},{"type":"user","id":"696f0759-3b0f-4a15-b8c8-19d3dfca33f2"}],` +
112 `"visibleTo":[{"type":"team","name":"rocket"}],` +
113 `"actions":["action1","action2"],` +
114 `"tags":["tag1","tag2"],` +
115 `"details":{"key1":"value1","key2":"value2"},` +
116 `"entity":"An example entity",` +
117 `"source":"The source",` +
118 `"priority":"P1",` +
119 `"user":"Dracula",` +
120 `"note":"Here is a note"` +
121 `}`))
122 }
123
124 err := service.Send("An example alert message", &types.Params{
125 "alias": "Life is too short for no alias",
126 "description": "Every alert needs a description",
127 "responders": "team:4513b7ea-3b91-438f-b7e4-e3e54af9147c,team:NOC,user:Donald,user:696f0759-3b0f-4a15-b8c8-19d3dfca33f2",
128 "visibleTo": "team:rocket",
129 "actions": "action1,action2",
130 "tags": "tag1,tag2",
131 "details": "key1:value1,key2:value2",
132 "entity": "An example entity",
133 "source": "The source",
134 "priority": "P1",
135 "user": "Dracula",
136 "note": "Here is a note",
137 })
138 gomega.Expect(err).ToNot(gomega.HaveOccurred())
139 },
140 )
141 })
142 })
143
144 ginkgo.Context("with query parameters", func() {
145 ginkgo.BeforeEach(func() {
146 // Initialize service
147 serviceURL, err := url.Parse(
148 fmt.Sprintf(
149 `opsgenie://%s/%s?alias=query-alias&description=query-description&responders=team:query_team&visibleTo=user:query_user&actions=queryAction1,queryAction2&tags=queryTag1,queryTag2&details=queryKey1:queryValue1,queryKey2:queryValue2&entity=query-entity&source=query-source&priority=P2&user=query-user&note=query-note`,
150 mockHost,
151 mockAPIKey,
152 ),
153 )
154 gomega.Expect(err).ToNot(gomega.HaveOccurred())
155
156 service = &Service{}
157 err = service.Initialize(serviceURL, mockLogger)
158 gomega.Expect(err).ToNot(gomega.HaveOccurred())
159 })
160
161 ginkgo.When("sending a simple alert", func() {
162 ginkgo.It(
163 "should send a request to our mock OpsGenie server with all fields populated from query parameters",
164 func() {
165 checkRequest = func(body string, header http.Header) {
166 gomega.Expect(header["Authorization"][0]).
167 To(gomega.Equal("GenieKey " + mockAPIKey))
168 gomega.Expect(header["Content-Type"][0]).
169 To(gomega.Equal("application/json"))
170 gomega.Expect(body).To(gomega.Equal(`{` +
171 `"message":"An example alert message",` +
172 `"alias":"query-alias",` +
173 `"description":"query-description",` +
174 `"responders":[{"type":"team","name":"query_team"}],` +
175 `"visibleTo":[{"type":"user","username":"query_user"}],` +
176 `"actions":["queryAction1","queryAction2"],` +
177 `"tags":["queryTag1","queryTag2"],` +
178 `"details":{"queryKey1":"queryValue1","queryKey2":"queryValue2"},` +
179 `"entity":"query-entity",` +
180 `"source":"query-source",` +
181 `"priority":"P2",` +
182 `"user":"query-user",` +
183 `"note":"query-note"` +
184 `}`))
185 }
186
187 err := service.Send("An example alert message", &types.Params{})
188 gomega.Expect(err).ToNot(gomega.HaveOccurred())
189 },
190 )
191 })
192
193 ginkgo.When("sending two alerts", func() {
194 ginkgo.It("should not mix-up the runtime parameters and the query parameters", func() {
195 // Internally the opsgenie service copies runtime parameters into the config struct
196 // before generating the alert payload. This test ensures that none of the parameters
197 // from alert 1 remain in the config struct when sending alert 2
198 // In short: This tests if we clone the config struct
199 checkRequest = func(body string, header http.Header) {
200 gomega.Expect(header["Authorization"][0]).
201 To(gomega.Equal("GenieKey " + mockAPIKey))
202 gomega.Expect(header["Content-Type"][0]).To(gomega.Equal("application/json"))
203 gomega.Expect(body).To(gomega.Equal(`{"` +
204 `message":"1",` +
205 `"alias":"1",` +
206 `"description":"1",` +
207 `"responders":[{"type":"team","name":"1"}],` +
208 `"visibleTo":[{"type":"team","name":"1"}],` +
209 `"actions":["action1","action2"],` +
210 `"tags":["tag1","tag2"],` +
211 `"details":{"key1":"value1","key2":"value2"},` +
212 `"entity":"1",` +
213 `"source":"1",` +
214 `"priority":"P1",` +
215 `"user":"1",` +
216 `"note":"1"` +
217 `}`))
218 }
219
220 err := service.Send("1", &types.Params{
221 "alias": "1",
222 "description": "1",
223 "responders": "team:1",
224 "visibleTo": "team:1",
225 "actions": "action1,action2",
226 "tags": "tag1,tag2",
227 "details": "key1:value1,key2:value2",
228 "entity": "1",
229 "source": "1",
230 "priority": "P1",
231 "user": "1",
232 "note": "1",
233 })
234 gomega.Expect(err).ToNot(gomega.HaveOccurred())
235
236 checkRequest = func(body string, header http.Header) {
237 gomega.Expect(header["Authorization"][0]).
238 To(gomega.Equal("GenieKey " + mockAPIKey))
239 gomega.Expect(header["Content-Type"][0]).To(gomega.Equal("application/json"))
240 gomega.Expect(body).To(gomega.Equal(`{` +
241 `"message":"2",` +
242 `"alias":"query-alias",` +
243 `"description":"query-description",` +
244 `"responders":[{"type":"team","name":"query_team"}],` +
245 `"visibleTo":[{"type":"user","username":"query_user"}],` +
246 `"actions":["queryAction1","queryAction2"],` +
247 `"tags":["queryTag1","queryTag2"],` +
248 `"details":{"queryKey1":"queryValue1","queryKey2":"queryValue2"},` +
249 `"entity":"query-entity",` +
250 `"source":"query-source",` +
251 `"priority":"P2",` +
252 `"user":"query-user",` +
253 `"note":"query-note"` +
254 `}`))
255 }
256
257 err = service.Send("2", nil)
258 gomega.Expect(err).ToNot(gomega.HaveOccurred())
259 })
260 })
261 })
262
263 ginkgo.It("should return the correct service ID", func() {
264 service := &Service{}
265 gomega.Expect(service.GetID()).To(gomega.Equal("opsgenie"))
266 })
267 })
268
269 var _ = ginkgo.Describe("the OpsGenie Config struct", func() {
270 ginkgo.When("generating a config from a simple URL", func() {
271 ginkgo.It("should populate the config with host and apikey", func() {
272 url, err := url.Parse(fmt.Sprintf("opsgenie://%s/%s", mockHost, mockAPIKey))
273 gomega.Expect(err).ToNot(gomega.HaveOccurred())
274
275 config := Config{}
276 err = config.SetURL(url)
277 gomega.Expect(err).ToNot(gomega.HaveOccurred())
278
279 gomega.Expect(config.APIKey).To(gomega.Equal(mockAPIKey))
280 gomega.Expect(config.Host).To(gomega.Equal(mockHost))
281 gomega.Expect(config.Port).To(gomega.Equal(uint16(443)))
282 })
283 })
284
285 ginkgo.When("generating a config from a url with port", func() {
286 ginkgo.It("should populate the port field", func() {
287 url, err := url.Parse(
288 fmt.Sprintf("opsgenie://%s/%s", net.JoinHostPort(mockHost, "12345"), mockAPIKey),
289 )
290 gomega.Expect(err).ToNot(gomega.HaveOccurred())
291
292 config := Config{}
293 err = config.SetURL(url)
294 gomega.Expect(err).ToNot(gomega.HaveOccurred())
295
296 gomega.Expect(config.Port).To(gomega.Equal(uint16(12345)))
297 })
298 })
299
300 ginkgo.When("generating a config from a url with query parameters", func() {
301 ginkgo.It("should populate the config fields with the query parameter values", func() {
302 queryParams := `alias=Life+is+too+short+for+no+alias&description=Every+alert+needs+a+description&actions=An+action&tags=tag1,tag2&details=key:value,key2:value2&entity=An+example+entity&source=The+source&priority=P1&user=Dracula&note=Here+is+a+note&responders=user:Test,team:NOC&visibleTo=user:A+User`
303 url, err := url.Parse(
304 fmt.Sprintf(
305 "opsgenie://%s/%s?%s",
306 net.JoinHostPort(mockHost, "12345"),
307 mockAPIKey,
308 queryParams,
309 ),
310 )
311 gomega.Expect(err).ToNot(gomega.HaveOccurred())
312
313 config := Config{}
314 err = config.SetURL(url)
315 gomega.Expect(err).ToNot(gomega.HaveOccurred())
316
317 gomega.Expect(config.Alias).To(gomega.Equal("Life is too short for no alias"))
318 gomega.Expect(config.Description).To(gomega.Equal("Every alert needs a description"))
319 gomega.Expect(config.Responders).To(gomega.Equal([]Entity{
320 {Type: "user", Username: "Test"},
321 {Type: "team", Name: "NOC"},
322 }))
323 gomega.Expect(config.VisibleTo).To(gomega.Equal([]Entity{
324 {Type: "user", Username: "A User"},
325 }))
326 gomega.Expect(config.Actions).To(gomega.Equal([]string{"An action"}))
327 gomega.Expect(config.Tags).To(gomega.Equal([]string{"tag1", "tag2"}))
328 gomega.Expect(config.Details).
329 To(gomega.Equal(map[string]string{"key": "value", "key2": "value2"}))
330 gomega.Expect(config.Entity).To(gomega.Equal("An example entity"))
331 gomega.Expect(config.Source).To(gomega.Equal("The source"))
332 gomega.Expect(config.Priority).To(gomega.Equal("P1"))
333 gomega.Expect(config.User).To(gomega.Equal("Dracula"))
334 gomega.Expect(config.Note).To(gomega.Equal("Here is a note"))
335 })
336 })
337
338 ginkgo.When("generating a config from a url with differently escaped spaces", func() {
339 ginkgo.It("should parse the escaped spaces correctly", func() {
340 // Use: '%20', '+' and a normal space
341 queryParams := `alias=Life is+too%20short+for+no+alias`
342 url, err := url.Parse(
343 fmt.Sprintf(
344 "opsgenie://%s/%s?%s",
345 net.JoinHostPort(mockHost, "12345"),
346 mockAPIKey,
347 queryParams,
348 ),
349 )
350 gomega.Expect(err).ToNot(gomega.HaveOccurred())
351
352 config := Config{}
353 err = config.SetURL(url)
354 gomega.Expect(err).ToNot(gomega.HaveOccurred())
355
356 gomega.Expect(config.Alias).To(gomega.Equal("Life is too short for no alias"))
357 })
358 })
359
360 ginkgo.When("generating a url from a simple config", func() {
361 ginkgo.It("should generate a url", func() {
362 config := Config{
363 Host: "api.opsgenie.com",
364 APIKey: "eb243592-faa2-4ba2-a551q-1afdf565c889",
365 }
366
367 url := config.GetURL()
368
369 gomega.Expect(url.String()).
370 To(gomega.Equal("opsgenie://api.opsgenie.com/eb243592-faa2-4ba2-a551q-1afdf565c889"))
371 })
372 })
373
374 ginkgo.When("generating a url from a config with a port", func() {
375 ginkgo.It("should generate a url with port", func() {
376 config := Config{
377 Host: "api.opsgenie.com",
378 APIKey: "eb243592-faa2-4ba2-a551q-1afdf565c889",
379 Port: 12345,
380 }
381
382 url := config.GetURL()
383
384 gomega.Expect(url.String()).
385 To(gomega.Equal("opsgenie://api.opsgenie.com:12345/eb243592-faa2-4ba2-a551q-1afdf565c889"))
386 })
387 })
388
389 ginkgo.When("generating a url from a config with all optional config fields", func() {
390 ginkgo.It("should generate a url with query parameters", func() {
391 config := Config{
392 Host: "api.opsgenie.com",
393 APIKey: "eb243592-faa2-4ba2-a551q-1afdf565c889",
394 Alias: "Life is too short for no alias",
395 Description: "Every alert needs a description",
396 Responders: []Entity{
397 {Type: "user", Username: "Test"},
398 {Type: "team", Name: "NOC"},
399 {Type: "team", ID: "4513b7ea-3b91-438f-b7e4-e3e54af9147c"},
400 },
401 VisibleTo: []Entity{
402 {Type: "user", Username: "A User"},
403 },
404 Actions: []string{"action1", "action2"},
405 Tags: []string{"tag1", "tag2"},
406 Details: map[string]string{"key": "value"},
407 Entity: "An example entity",
408 Source: "The source",
409 Priority: "P1",
410 User: "Dracula",
411 Note: "Here is a note",
412 }
413
414 url := config.GetURL()
415 gomega.Expect(url.String()).
416 To(gomega.Equal(`opsgenie://api.opsgenie.com/eb243592-faa2-4ba2-a551q-1afdf565c889?actions=action1%2Caction2&alias=Life+is+too+short+for+no+alias&description=Every+alert+needs+a+description&details=key%3Avalue&entity=An+example+entity&note=Here+is+a+note&priority=P1&responders=user%3ATest%2Cteam%3ANOC%2Cteam%3A4513b7ea-3b91-438f-b7e4-e3e54af9147c&source=The+source&tags=tag1%2Ctag2&user=Dracula&visibleto=user%3AA+User`))
417 })
418 })
419 })
420
421 func TestOpsGenie(t *testing.T) {
422 t.Parallel()
423 gomega.RegisterFailHandler(ginkgo.Fail)
424 ginkgo.RunSpecs(t, "Shoutrrr OpsGenie Suite")
425 }