Debian Codegraph @

response_test.go

raw
1 package monitoringplugin
2
3 import (
4 "bytes"
5 "github.com/stretchr/testify/assert"
6 "os"
7 "os/exec"
8 "regexp"
9 "strconv"
10 "strings"
11 "testing"
12 )
13
14 func TestOKResponse(t *testing.T) {
15 defaultMessage := "OKTest"
16 if os.Getenv("EXECUTE_PLUGIN") == "1" {
17 r := NewResponse(defaultMessage)
18 r.OutputAndExit()
19 }
20 cmd := exec.Command(os.Args[0], "-test.run=TestOKResponse")
21 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")
22 var outputB bytes.Buffer
23 cmd.Stdout = &outputB
24 err := cmd.Run()
25
26 if err != nil {
27 if exitError, ok := err.(*exec.ExitError); ok {
28 t.Error("OkResponse is expected to return exit status 0, but exited with exit code " + strconv.Itoa(exitError.ExitCode()))
29 } else {
30 t.Error("cmd.Run() Command resulted in an error that can not be converted to exec.ExitEror! error: " + err.Error())
31 }
32 return
33 }
34
35 output := outputB.String()
36 match, err := regexp.MatchString("^OK: "+defaultMessage+"\n$", output)
37 if err != nil {
38 t.Error(err.Error())
39 }
40 if !match {
41 t.Error("ok result output message did not match to the expected regex")
42 }
43
44 return
45 }
46
47 func TestWARNINGResponse(t *testing.T) {
48 failureResponse(t, 1)
49 return
50 }
51
52 func TestCRITICALResponse(t *testing.T) {
53 failureResponse(t, 2)
54 return
55 }
56
57 func TestUNKNOWNResponse(t *testing.T) {
58 failureResponse(t, 3)
59 return
60 }
61
62 func TestStatusHierarchy(t *testing.T) {
63 r := NewResponse("")
64 if r.statusCode != OK {
65 t.Error("status code is supposed to be OK when a new Response is created")
66 }
67
68 r.UpdateStatus(WARNING, "")
69 if r.statusCode != WARNING {
70 t.Error("status code did not update from OK to WARNING after UpdateStatus(WARNING) is called!")
71 }
72
73 r.UpdateStatus(OK, "")
74 if r.statusCode != WARNING {
75 t.Error("status code did change from WARNING to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(OK) was called! The function should not affect the status code, because WARNING is worse than OK")
76 }
77
78 r.UpdateStatus(CRITICAL, "")
79 if r.statusCode != CRITICAL {
80 t.Error("status code did not update from WARNING to CRITICAL after UpdateStatus(WARNING) is called!")
81 }
82
83 r.UpdateStatus(OK, "")
84 if r.statusCode != CRITICAL {
85 t.Error("status code did change from CRITICAL to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(OK) was called! The function should not affect the status code, because CRITICAL is worse than OK")
86 }
87
88 r.UpdateStatus(WARNING, "")
89 if r.statusCode != CRITICAL {
90 t.Error("status code did change from CRITICAL to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(WARNING) was called! The function should not affect the status code, because CRITICAL is worse than WARNING")
91 }
92
93 r.UpdateStatus(UNKNOWN, "")
94 if r.statusCode != CRITICAL {
95 t.Error("status code did change from CRITICAL to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(UNKNOWN) was called! The function should not affect the status code, because CRITICAL is worse than UNKNOWN")
96 }
97
98 r = NewResponse("")
99 r.UpdateStatus(UNKNOWN, "")
100 if r.statusCode != UNKNOWN {
101 t.Error("status code did not update from OK to UNKNOWN after UpdateStatus(UNKNOWN) is called!")
102 }
103
104 r.UpdateStatus(WARNING, "")
105 if r.statusCode != UNKNOWN {
106 t.Error("status code did change from UNKNOWN to " + strconv.Itoa(r.statusCode) + " after UpdateStatus(WARNING) was called! The function should not affect the status code, because UNKNOWN is worse than WARNING")
107 }
108
109 r.UpdateStatus(CRITICAL, "")
110 if r.statusCode != CRITICAL {
111 t.Error("status code is did not change from UNKNOWN to CRITICAL after UpdateStatus(CRITICAL) was called! The function should affect the status code, because CRITICAL is worse than UNKNOWN")
112 }
113 }
114
115 func TestOutputMessages(t *testing.T) {
116 defaultMessage := "default"
117 if os.Getenv("EXECUTE_PLUGIN") == "1" {
118 r := NewResponse(defaultMessage)
119 r.UpdateStatus(0, "message1")
120 r.UpdateStatus(0, "message2")
121 r.UpdateStatus(0, "message3")
122 r.UpdateStatus(0, "message4")
123 r.OutputAndExit()
124 return
125 }
126 if os.Getenv("EXECUTE_PLUGIN") == "2" {
127 r := NewResponse(defaultMessage)
128 r.UpdateStatus(1, "message1")
129 r.UpdateStatus(0, "message2")
130 r.UpdateStatus(0, "message3")
131 r.UpdateStatus(0, "message4")
132 r.SetOutputDelimiter(" / ")
133 r.OutputAndExit()
134 return
135 }
136 cmd := exec.Command(os.Args[0], "-test.run=TestOutputMessages")
137 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")
138 var outputB bytes.Buffer
139 cmd.Stdout = &outputB
140 err := cmd.Run()
141
142 if err != nil {
143 t.Error("an error occurred during cmd.Run(), but the Response was expected to exit with exit code 0")
144 return
145 }
146
147 output := outputB.String()
148
149 match, err := regexp.MatchString("^OK: "+defaultMessage+"\nmessage1\nmessage2\nmessage3\nmessage4\n$", output)
150 if err != nil {
151 t.Error(err.Error())
152 }
153 if !match {
154 t.Error("output did not match to the expected regex")
155 }
156
157 cmd = exec.Command(os.Args[0], "-test.run=TestOutputMessages")
158 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=2")
159 var outputB2 bytes.Buffer
160 cmd.Stdout = &outputB2
161 err = cmd.Run()
162
163 if err != nil {
164 if exitError, ok := err.(*exec.ExitError); ok {
165 if exitError.ExitCode() != 1 {
166 t.Error("the command is expected to return exit status 1, but exited with exit code " + strconv.Itoa(exitError.ExitCode()))
167 }
168 } else {
169 t.Errorf("cmd.Run() Command resulted in an error that can not be converted to exec.ExitEror! error: " + err.Error())
170 }
171 } else {
172 t.Error("the command exited with exitcode 0 but is expected to exit with exitcode 1")
173 }
174
175 output = outputB2.String()
176 match, err = regexp.MatchString("^WARNING: message1 / message2 / message3 / message4\n$", output)
177 if err != nil {
178 t.Error(err.Error())
179 }
180
181 if !match {
182 t.Error("output did not match to the expected regex")
183 }
184 }
185
186 func TestResponse_UpdateStatusIf(t *testing.T) {
187 r := NewResponse("")
188 r.UpdateStatusIf(false, 1, "")
189 assert.True(t, r.statusCode == 0)
190 r.UpdateStatusIf(true, 1, "")
191 assert.True(t, r.statusCode == 1)
192 }
193
194 func TestResponse_UpdateStatusIfNot(t *testing.T) {
195 r := NewResponse("")
196 r.UpdateStatusIfNot(true, 1, "")
197 assert.True(t, r.statusCode == 0)
198 r.UpdateStatusIfNot(false, 1, "")
199 assert.True(t, r.statusCode == 1)
200 }
201
202 func TestString2StatusCode(t *testing.T) {
203 assert.True(t, String2StatusCode("ok") == 0)
204 assert.True(t, String2StatusCode("OK") == 0)
205 assert.True(t, String2StatusCode("Ok") == 0)
206 assert.True(t, String2StatusCode("warning") == 1)
207 assert.True(t, String2StatusCode("WARNING") == 1)
208 assert.True(t, String2StatusCode("Warning") == 1)
209 assert.True(t, String2StatusCode("critical") == 2)
210 assert.True(t, String2StatusCode("CRITICAL") == 2)
211 assert.True(t, String2StatusCode("Critical") == 2)
212 assert.True(t, String2StatusCode("unknown") == 3)
213 assert.True(t, String2StatusCode("UNKNOWN") == 3)
214 assert.True(t, String2StatusCode("Unknown") == 3)
215 }
216
217 func TestOutputPerformanceData(t *testing.T) {
218 p1 := NewPerformanceDataPoint("label1", 10).
219 SetUnit("%").
220 SetMin(0).
221 SetMax(100).
222 SetThresholds(
223 NewThresholds(0, 80, 0, 90))
224 p2 := NewPerformanceDataPoint("label2", 20).
225 SetUnit("%").
226 SetMin(0).
227 SetMax(100).
228 SetThresholds(
229 NewThresholds(0, 80, 0, 90))
230 p3 := NewPerformanceDataPoint("label3", 30).
231 SetUnit("%").
232 SetMin(0).
233 SetMax(100).
234 SetThresholds(
235 NewThresholds(0, 80, 0, 90))
236
237 defaultMessage := "OKTest"
238 if os.Getenv("EXECUTE_PLUGIN") == "1" {
239 r := NewResponse(defaultMessage)
240 err := r.AddPerformanceDataPoint(p1)
241 if err != nil {
242 r.UpdateStatus(3, "error during add performance data point")
243 }
244 err = r.AddPerformanceDataPoint(p2)
245 if err != nil {
246 r.UpdateStatus(3, "error during add performance data point")
247 }
248 err = r.AddPerformanceDataPoint(p3)
249 if err != nil {
250 r.UpdateStatus(3, "error during add performance data point")
251 }
252 r.OutputAndExit()
253 }
254 cmd := exec.Command(os.Args[0], "-test.run=TestOutputPerformanceData")
255 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")
256 var outputB bytes.Buffer
257 cmd.Stdout = &outputB
258 err := cmd.Run()
259 if err != nil {
260 t.Error("cmd.Run() returned an exitcode != 0, but exit code 0 was expected")
261 }
262
263 output := outputB.String()
264 if !strings.HasPrefix(output, "OK: "+defaultMessage+" | ") {
265 t.Error("output did not match the expected regex")
266 }
267 }
268
269 func TestOutputPerformanceDataThresholdsExceeded(t *testing.T) {
270 p1 := NewPerformanceDataPoint("label1", 10).
271 SetUnit("%").
272 SetMin(0).
273 SetMax(100).
274 SetThresholds(
275 NewThresholds(0, 80, 0, 90))
276 p2 := NewPerformanceDataPoint("label2", 20).
277 SetUnit("%").
278 SetMin(0).
279 SetMax(100).
280 SetThresholds(
281 NewThresholds(0, 80, 0, 90))
282 p3 := NewPerformanceDataPoint("label3", 85).
283 SetUnit("%").
284 SetMin(0).
285 SetMax(100).
286 SetThresholds(
287 NewThresholds(0, 80, 0, 90))
288
289 defaultMessage := "OKTest"
290 if os.Getenv("EXECUTE_PLUGIN") == "1" {
291 r := NewResponse(defaultMessage)
292 err := r.AddPerformanceDataPoint(p1)
293 if err != nil {
294 r.UpdateStatus(3, "error during add performance data point")
295 }
296 err = r.AddPerformanceDataPoint(p2)
297 if err != nil {
298 r.UpdateStatus(3, "error during add performance data point")
299 }
300 err = r.AddPerformanceDataPoint(p3)
301 if err != nil {
302 r.UpdateStatus(3, "error during add performance data point")
303 }
304 r.OutputAndExit()
305 }
306 cmd := exec.Command(os.Args[0], "-test.run=TestOutputPerformanceDataThresholdsExceeded")
307 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")
308 var outputB bytes.Buffer
309 cmd.Stdout = &outputB
310 err := cmd.Run()
311 if err == nil {
312 t.Error("cmd.Run() returned an exitcode = 0, but exit code 1 was expected")
313 } else if err.Error() != "exit status 1" {
314 t.Error("cmd.Run() returned an exitcode != 1, but exit code 1 was expected")
315 }
316
317 output := outputB.String()
318 if !strings.HasPrefix(output, "WARNING: label3 is outside of WARNING threshold | ") {
319 t.Error("output did not match the expected regex")
320 }
321 }
322
323 func failureResponse(t *testing.T, exitCode int) {
324 var status string
325 switch exitCode {
326 case 0:
327 t.Error("exitcode in failureResponse function cannot be 0, because it is not meant to be used for a successful cmd")
328 return
329 case 1:
330 status = "WARNING"
331 case 2:
332 status = "CRITICAL"
333 default:
334 status = "UNKNOWN"
335 }
336
337 message := status + "Test"
338 if os.Getenv("EXECUTE_PLUGIN") == "1" {
339 r := NewResponse("")
340 r.UpdateStatus(exitCode, message)
341 r.OutputAndExit()
342 }
343 cmd := exec.Command(os.Args[0], "-test.run=Test"+status+"Response")
344 cmd.Env = append(os.Environ(), "EXECUTE_PLUGIN=1")
345
346 var outputB bytes.Buffer
347 cmd.Stdout = &outputB
348 err := cmd.Run()
349
350 if err != nil {
351 if exitError, ok := err.(*exec.ExitError); ok {
352 if exitError.ExitCode() != exitCode {
353 t.Error(status + " Response is expected to return exit status " + strconv.Itoa(exitCode) + ", but exited with exit code " + strconv.Itoa(exitError.ExitCode()))
354 }
355 } else {
356 t.Errorf("cmd.Run() Command resulted in an error that can not be converted to exec.ExitEror! error: " + err.Error())
357 }
358 } else {
359 t.Error("the command exited with exitcode 0 but is expected to exit with exitcode " + strconv.Itoa(exitCode))
360 }
361
362 output := outputB.String()
363 match, err := regexp.MatchString("^"+status+": "+message+"\n$", output)
364 if err != nil {
365 t.Error(err.Error())
366 }
367 if !match {
368 t.Error(status + " result output message did not match to the expected regex")
369 }
370 return
371 }
372
373 func TestResponse_SortOutputMessagesByStatus(t *testing.T) {
374 r := NewResponse("defaultMessage")
375 r.UpdateStatus(OK, "message1")
376 r.UpdateStatus(WARNING, "message2")
377 r.UpdateStatus(UNKNOWN, "message3")
378 r.UpdateStatus(CRITICAL, "message4")
379 r.UpdateStatus(WARNING, "message5")
380 r.UpdateStatus(CRITICAL, "message6")
381 r.UpdateStatus(UNKNOWN, "message7")
382 r.UpdateStatus(OK, "message8")
383 r.validate()
384 for x, message := range r.outputMessages {
385 for _, m := range r.outputMessages[x:] {
386 assert.True(t, message.Status >= m.Status || message.Status == CRITICAL, "sorting did not work")
387 }
388 }
389 }
390
391 func TestResponse_InvalidCharacter(t *testing.T) {
392 r := NewResponse("checked")
393 r.UpdateStatus(WARNING, "test|")
394 r.validate()
395 res := r.GetInfo()
396 assert.True(t, res.RawOutput == "WARNING: test")
397 }
398
399 func TestResponse_InvalidCharacterReplace(t *testing.T) {
400 r := NewResponse("checked")
401 r.UpdateStatus(OK, "test|2")
402 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplace, "-")
403 assert.NoError(t, err)
404 r.validate()
405 res := r.GetInfo()
406 assert.True(t, res.RawOutput == "OK: checked\ntest-2")
407 }
408
409 func TestResponse_InvalidCharacterReplaceError(t *testing.T) {
410 r := NewResponse("checked")
411 r.UpdateStatus(OK, "test|")
412 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplace, "")
413 assert.Error(t, err)
414 }
415
416 func TestResponse_InvalidCharacterRemoveMessage(t *testing.T) {
417 r := NewResponse("checked")
418 r.UpdateStatus(OK, "test|")
419 err := r.SetInvalidCharacterBehavior(InvalidCharacterRemoveMessage, "")
420 assert.NoError(t, err)
421 r.validate()
422 res := r.GetInfo()
423 assert.True(t, res.RawOutput == "OK: checked")
424 }
425
426 func TestResponse_InvalidCharacterReplaceWithError(t *testing.T) {
427 r := NewResponse("checked")
428 r.UpdateStatus(WARNING, "test|")
429 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithError, "")
430 assert.NoError(t, err)
431 r.validate()
432 res := r.GetInfo()
433 assert.True(t, res.RawOutput == "WARNING: output message contains invalid character")
434 }
435
436 func TestResponse_InvalidCharacterReplaceWithErrorMultipleMessages(t *testing.T) {
437 r := NewResponse("checked")
438 r.UpdateStatus(WARNING, "test|")
439 r.UpdateStatus(WARNING, "test|2")
440 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithError, "")
441 assert.NoError(t, err)
442 r.validate()
443 res := r.GetInfo()
444 assert.True(t, res.RawOutput == "WARNING: output message contains invalid character")
445 }
446
447 func TestResponse_InvalidCharacterReplaceWithErrorAndSetUnknown(t *testing.T) {
448 r := NewResponse("checked")
449 r.UpdateStatus(WARNING, "test|")
450 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithErrorAndSetUNKNOWN, "")
451 assert.NoError(t, err)
452 r.validate()
453 res := r.GetInfo()
454 assert.True(t, res.RawOutput == "UNKNOWN: output message contains invalid character")
455 }
456
457 func TestResponse_InvalidCharacterReplaceWithErrorAndSetUnknownMultipleMessages(t *testing.T) {
458 r := NewResponse("checked")
459 r.UpdateStatus(WARNING, "test|")
460 r.UpdateStatus(WARNING, "test|2")
461 err := r.SetInvalidCharacterBehavior(InvalidCharacterReplaceWithErrorAndSetUNKNOWN, "")
462 assert.NoError(t, err)
463 r.validate()
464 res := r.GetInfo()
465 assert.True(t, res.RawOutput == "UNKNOWN: output message contains invalid character")
466 }
467
468 func TestResponse_InvalidCharacterDefaultMessage(t *testing.T) {
469 r := NewResponse("test|")
470 r.validate()
471 res := r.GetInfo()
472 assert.True(t, res.RawOutput == "OK: test")
473 }