|
9 | 9 | "github.com/stretchr/testify/require" |
10 | 10 |
|
11 | 11 | "github.com/influxdata/telegraf" |
| 12 | + "github.com/influxdata/telegraf/config" |
12 | 13 | "github.com/influxdata/telegraf/plugins/outputs/health" |
13 | 14 | "github.com/influxdata/telegraf/testutil" |
14 | 15 | ) |
@@ -214,3 +215,86 @@ func TestInitServiceAddress(t *testing.T) { |
214 | 215 | }) |
215 | 216 | } |
216 | 217 | } |
| 218 | + |
| 219 | +func TestTimeBetweenMetrics(t *testing.T) { |
| 220 | + now := time.Now() |
| 221 | + past := time.Time{}.AddDate(2002, 0, 0) |
| 222 | + tests := []struct { |
| 223 | + name string |
| 224 | + maxTimeBetweenMetrics config.Duration |
| 225 | + metrics []telegraf.Metric |
| 226 | + expectedCode int |
| 227 | + }{ |
| 228 | + { |
| 229 | + name: "healthy when disabled and old metric", |
| 230 | + maxTimeBetweenMetrics: config.Duration(0), |
| 231 | + metrics: []telegraf.Metric{ |
| 232 | + testutil.MustMetric( |
| 233 | + "cpu", |
| 234 | + map[string]string{}, |
| 235 | + map[string]any{ |
| 236 | + "time_idle": 42, |
| 237 | + }, |
| 238 | + past), |
| 239 | + }, |
| 240 | + expectedCode: 200, |
| 241 | + }, |
| 242 | + { |
| 243 | + name: "healthy when enabled and recent metric", |
| 244 | + maxTimeBetweenMetrics: config.Duration(5 * time.Second), |
| 245 | + metrics: []telegraf.Metric{ |
| 246 | + testutil.MustMetric( |
| 247 | + "cpu", |
| 248 | + map[string]string{}, |
| 249 | + map[string]any{ |
| 250 | + "time_idle": 42, |
| 251 | + }, |
| 252 | + now), |
| 253 | + }, |
| 254 | + expectedCode: 200, |
| 255 | + }, |
| 256 | + { |
| 257 | + name: "unhealthy when enabled and old metric", |
| 258 | + maxTimeBetweenMetrics: config.Duration(1 * time.Nanosecond), |
| 259 | + metrics: []telegraf.Metric{ |
| 260 | + testutil.MustMetric( |
| 261 | + "cpu", |
| 262 | + map[string]string{}, |
| 263 | + map[string]any{ |
| 264 | + "time_idle": 42, |
| 265 | + }, |
| 266 | + past), |
| 267 | + }, |
| 268 | + expectedCode: 503, |
| 269 | + }, |
| 270 | + } |
| 271 | + |
| 272 | + for _, tt := range tests { |
| 273 | + t.Run(tt.name, func(t *testing.T) { |
| 274 | + dut := health.NewHealth() |
| 275 | + dut.ServiceAddress = "tcp://127.0.0.1:0" |
| 276 | + dut.Log = testutil.Logger{} |
| 277 | + dut.MaxTimeBetweenMetrics = tt.maxTimeBetweenMetrics |
| 278 | + |
| 279 | + err := dut.Init() |
| 280 | + require.NoError(t, err) |
| 281 | + |
| 282 | + err = dut.Connect() |
| 283 | + require.NoError(t, err) |
| 284 | + |
| 285 | + err = dut.Write(tt.metrics) |
| 286 | + require.NoError(t, err) |
| 287 | + |
| 288 | + resp, err := http.Get(dut.Origin()) |
| 289 | + require.NoError(t, err) |
| 290 | + defer resp.Body.Close() |
| 291 | + require.Equal(t, tt.expectedCode, resp.StatusCode) |
| 292 | + |
| 293 | + _, err = io.ReadAll(resp.Body) |
| 294 | + require.NoError(t, err) |
| 295 | + |
| 296 | + err = dut.Close() |
| 297 | + require.NoError(t, err) |
| 298 | + }) |
| 299 | + } |
| 300 | +} |
0 commit comments