|
1 | 1 | package gatego |
2 | 2 |
|
3 | 3 | import ( |
| 4 | + "errors" |
4 | 5 | "net/http" |
5 | 6 | "net/http/httptest" |
6 | 7 | "testing" |
@@ -140,6 +141,67 @@ func TestChecker_Start(t *testing.T) { |
140 | 141 | } |
141 | 142 | } |
142 | 143 |
|
| 144 | +func TestChecker_OnFailure(t *testing.T) { |
| 145 | + tests := []struct { |
| 146 | + name string |
| 147 | + checker Checker |
| 148 | + expectedError bool |
| 149 | + }{ |
| 150 | + { |
| 151 | + name: "on failure command with valid command", |
| 152 | + checker: Checker{ |
| 153 | + Delay: 1 * time.Second, |
| 154 | + Checks: []Check{ |
| 155 | + { |
| 156 | + Name: "test-check-failure", |
| 157 | + Cron: "* * * * *", |
| 158 | + Method: "GET", |
| 159 | + URL: "http://example.com", |
| 160 | + Timeout: 5 * time.Second, |
| 161 | + OnFailure: "echo check '$check_name' failed at $date: $error", |
| 162 | + }, |
| 163 | + }, |
| 164 | + }, |
| 165 | + expectedError: false, |
| 166 | + }, |
| 167 | + { |
| 168 | + name: "on failure command with invalid command", |
| 169 | + checker: Checker{ |
| 170 | + Delay: 1 * time.Second, |
| 171 | + Checks: []Check{ |
| 172 | + { |
| 173 | + Name: "test-check-failure", |
| 174 | + Cron: "* * * * *", |
| 175 | + Method: "GET", |
| 176 | + URL: "http://example.com", |
| 177 | + Timeout: 5 * time.Second, |
| 178 | + OnFailure: "invalidCommand $error", |
| 179 | + }, |
| 180 | + }, |
| 181 | + }, |
| 182 | + expectedError: true, |
| 183 | + }, |
| 184 | + } |
| 185 | + |
| 186 | + for _, tt := range tests { |
| 187 | + t.Run(tt.name, func(t *testing.T) { |
| 188 | + // Simulate a failure scenario by injecting an error |
| 189 | + err := errors.New("Connection timeout") |
| 190 | + err = handleFailure(tt.checker.Checks[0], err) |
| 191 | + |
| 192 | + // Check if an error was returned and if it matches the expected result |
| 193 | + if (err != nil) != tt.expectedError { |
| 194 | + t.Errorf("handleFailure() error = %v, expectedError %v", err, tt.expectedError) |
| 195 | + } |
| 196 | + |
| 197 | + // Clean up scheduler if it was created |
| 198 | + if tt.checker.scheduler != nil { |
| 199 | + tt.checker.scheduler.Stop() |
| 200 | + } |
| 201 | + }) |
| 202 | + } |
| 203 | +} |
| 204 | + |
143 | 205 | // TestCheckWithMockServer tests the Check struct with a mock HTTP server |
144 | 206 | func TestCheckWithMockServer(t *testing.T) { |
145 | 207 | handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
|
0 commit comments