-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain_test.go
More file actions
343 lines (277 loc) · 9.67 KB
/
Copy pathmain_test.go
File metadata and controls
343 lines (277 loc) · 9.67 KB
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
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
package main
import (
"context"
"math"
"net/http"
"os"
"path/filepath"
"testing"
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
)
func TestParseBytesToken(t *testing.T) {
tests := []struct {
name string
input string
expected float64
}{
{"plain integer", "39,889,034,403", 39889034403},
{"kilobytes", "5.5K", 5.5 * 1024},
{"mebibytes", "1.25MiB", 1.25 * 1024 * 1024},
{"gigabytes", "2.5G", 2.5 * 1024 * 1024 * 1024},
{"bytes suffix", "100B", 100},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
got, err := parseBytesToken(tc.input)
if err != nil {
t.Fatalf("parseBytesToken(%q) unexpected error: %v", tc.input, err)
}
if diff := math.Abs(got - tc.expected); diff > 1e-3 {
t.Fatalf("parseBytesToken(%q) diff %f, want %f, got %f", tc.input, diff, tc.expected, got)
}
})
}
}
func TestParseLogLineSentReceived(t *testing.T) {
bytesSentGauge.WithLabelValues("test_job").Set(0)
bytesReceivedGauge.WithLabelValues("test_job").Set(0)
line := "2023/12/22 01:18:25 [2224747] sent 39,889,034,403 bytes received 5,146,208 bytes 70,546,738.48 bytes/sec"
parseLogLine(line, "test_job")
sent := testutil.ToFloat64(bytesSentGauge.WithLabelValues("test_job"))
received := testutil.ToFloat64(bytesReceivedGauge.WithLabelValues("test_job"))
if math.Abs(sent-39889034403) > 1 {
t.Fatalf("sent gauge = %f, want 39889034403", sent)
}
if math.Abs(received-5146208) > 1 {
t.Fatalf("received gauge = %f, want 5146208", received)
}
}
func TestParseLogLineTotalSize(t *testing.T) {
totalSizeGauge.WithLabelValues("test_job").Set(0)
lastRsyncExecutionTime.WithLabelValues("test_job").Set(0)
lastRsyncExecutionTimeValid.WithLabelValues("test_job").Set(0)
before := float64(time.Now().Unix())
line := "2023/12/22 01:18:25 [2224747] total size is 199.5GiB speedup is 4.99"
parseLogLine(line, "test_job")
total := testutil.ToFloat64(totalSizeGauge.WithLabelValues("test_job"))
if math.Abs(total-(199.5*1024*1024*1024)) > 1024 {
t.Fatalf("total size gauge = %f, want approx %f", total, 199.5*1024*1024*1024)
}
lastSync := testutil.ToFloat64(lastRsyncExecutionTime.WithLabelValues("test_job"))
valid := testutil.ToFloat64(lastRsyncExecutionTimeValid.WithLabelValues("test_job"))
after := float64(time.Now().Unix())
if lastSync < before || lastSync > after+1 {
t.Fatalf("last sync timestamp %f outside expected range [%f, %f]", lastSync, before, after+1)
}
if valid != 1 {
t.Fatalf("lastRsyncExecutionTimeValid = %f, want 1", valid)
}
}
func TestParseLogLineTotalSizeInvalid(t *testing.T) {
lastRsyncExecutionTimeValid.WithLabelValues("test_job").Set(1)
line := "2023/12/22 01:18:25 [2224747] total size is invalid_data speedup is 4.99"
parseLogLine(line, "test_job")
valid := testutil.ToFloat64(lastRsyncExecutionTimeValid.WithLabelValues("test_job"))
if valid != 0 {
t.Fatalf("lastRsyncExecutionTimeValid = %f, want 0 after invalid parse", valid)
}
}
func TestParseLogLineExitCodeSuccess(t *testing.T) {
lastRsyncExecutionTime.WithLabelValues("test_job").Set(0)
lastRsyncExecutionTimeValid.WithLabelValues("test_job").Set(0)
lastRsyncExitCode.WithLabelValues("test_job").Set(-1)
before := float64(time.Now().Unix())
parseLogLine("rsync-exit-code: 0", "test_job")
after := float64(time.Now().Unix())
valid := testutil.ToFloat64(lastRsyncExecutionTimeValid.WithLabelValues("test_job"))
if valid != 1 {
t.Fatalf("lastRsyncExecutionTimeValid = %f, want 1 after exit code 0", valid)
}
code := testutil.ToFloat64(lastRsyncExitCode.WithLabelValues("test_job"))
if code != 0 {
t.Fatalf("lastRsyncExitCode = %f, want 0", code)
}
lastSync := testutil.ToFloat64(lastRsyncExecutionTime.WithLabelValues("test_job"))
if lastSync < before || lastSync > after+1 {
t.Fatalf("last sync timestamp %f outside expected range [%f, %f]", lastSync, before, after+1)
}
}
func TestParseLogLineExitCode24(t *testing.T) {
lastRsyncExecutionTimeValid.WithLabelValues("test_job").Set(0)
lastRsyncExitCode.WithLabelValues("test_job").Set(0)
parseLogLine("rsync-exit-code: 24", "test_job")
valid := testutil.ToFloat64(lastRsyncExecutionTimeValid.WithLabelValues("test_job"))
if valid != 1 {
t.Fatalf("lastRsyncExecutionTimeValid = %f, want 1 after exit code 24", valid)
}
code := testutil.ToFloat64(lastRsyncExitCode.WithLabelValues("test_job"))
if code != 24 {
t.Fatalf("lastRsyncExitCode = %f, want 24", code)
}
}
// TestParseLogLineExitCodeFailure reproduces the false-positive case: a job that
// printed "total size is 0" (setting valid=1) but then failed. The trailing
// exit-code sentinel must override valid back to 0.
func TestParseLogLineExitCodeFailure(t *testing.T) {
lastRsyncExecutionTimeValid.WithLabelValues("test_job").Set(1)
lastRsyncExitCode.WithLabelValues("test_job").Set(0)
parseLogLine("rsync-exit-code: 23", "test_job")
valid := testutil.ToFloat64(lastRsyncExecutionTimeValid.WithLabelValues("test_job"))
if valid != 0 {
t.Fatalf("lastRsyncExecutionTimeValid = %f, want 0 after non-zero exit code", valid)
}
code := testutil.ToFloat64(lastRsyncExitCode.WithLabelValues("test_job"))
if code != 23 {
t.Fatalf("lastRsyncExitCode = %f, want 23", code)
}
}
func TestParseBytesTokenNegative(t *testing.T) {
tests := []struct {
name string
input string
}{
{"negative number", "-100"},
{"negative with suffix", "-5K"},
{"negative decimal", "-1.5M"},
}
for _, tc := range tests {
tc := tc
t.Run(tc.name, func(t *testing.T) {
_, err := parseBytesToken(tc.input)
if err == nil {
t.Fatalf("parseBytesToken(%q) expected error for negative value, got nil", tc.input)
}
})
}
}
func TestMultipleJobsIndependent(t *testing.T) {
// Parse stats for job "alpha"
bytesSentGauge.WithLabelValues("alpha").Set(0)
bytesSentGauge.WithLabelValues("beta").Set(0)
parseLogLine("sent 1,000 bytes received 500 bytes 1,500.00 bytes/sec", "alpha")
parseLogLine("sent 9,999 bytes received 8,888 bytes 18,887.00 bytes/sec", "beta")
sentAlpha := testutil.ToFloat64(bytesSentGauge.WithLabelValues("alpha"))
sentBeta := testutil.ToFloat64(bytesSentGauge.WithLabelValues("beta"))
if math.Abs(sentAlpha-1000) > 1 {
t.Fatalf("alpha sent = %f, want 1000", sentAlpha)
}
if math.Abs(sentBeta-9999) > 1 {
t.Fatalf("beta sent = %f, want 9999", sentBeta)
}
// Verify updating one job doesn't affect the other
parseLogLine("sent 2,000 bytes received 100 bytes 2,100.00 bytes/sec", "alpha")
sentAlpha = testutil.ToFloat64(bytesSentGauge.WithLabelValues("alpha"))
sentBeta = testutil.ToFloat64(bytesSentGauge.WithLabelValues("beta"))
if math.Abs(sentAlpha-2000) > 1 {
t.Fatalf("alpha sent after update = %f, want 2000", sentAlpha)
}
if math.Abs(sentBeta-9999) > 1 {
t.Fatalf("beta sent should be unchanged = %f, want 9999", sentBeta)
}
}
func TestJobNameFromPath(t *testing.T) {
tests := []struct {
path string
expected string
}{
{"/logs/gym_to_z2.log", "gym_to_z2"},
{"/logs/rsync.log", "rsync"},
{"crawlspace_to_z2.log", "crawlspace_to_z2"},
{"/some/deep/path/docker_to_shed.log", "docker_to_shed"},
{"noext", "noext"},
}
for _, tc := range tests {
t.Run(tc.path, func(t *testing.T) {
got := jobNameFromPath(tc.path)
if got != tc.expected {
t.Fatalf("jobNameFromPath(%q) = %q, want %q", tc.path, got, tc.expected)
}
})
}
}
func TestScanLogDir(t *testing.T) {
dir := t.TempDir()
// Create some .log files and a non-log file
for _, name := range []string{"gym.log", "shed.log", "notes.txt"} {
if err := os.WriteFile(filepath.Join(dir, name), []byte("test"), 0644); err != nil {
t.Fatal(err)
}
}
// Create a subdirectory named something.log to ensure it's skipped
if err := os.Mkdir(filepath.Join(dir, "subdir.log"), 0755); err != nil {
t.Fatal(err)
}
paths, err := scanLogDir(dir)
if err != nil {
t.Fatalf("scanLogDir error: %v", err)
}
if len(paths) != 2 {
t.Fatalf("expected 2 log files, got %d: %v", len(paths), paths)
}
names := make(map[string]bool)
for _, p := range paths {
names[filepath.Base(p)] = true
}
if !names["gym.log"] || !names["shed.log"] {
t.Fatalf("expected gym.log and shed.log, got %v", names)
}
}
func TestScanLogDirEmpty(t *testing.T) {
dir := t.TempDir()
paths, err := scanLogDir(dir)
if err != nil {
t.Fatalf("scanLogDir error: %v", err)
}
if len(paths) != 0 {
t.Fatalf("expected 0 log files, got %d", len(paths))
}
}
func TestHealthEndpoint(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errCh := make(chan error, 1)
// Use a different port to avoid conflicts
originalPort := port
port = 19150
defer func() { port = originalPort }()
go setupHTTPListener(ctx, errCh)
// Wait for server to start
time.Sleep(100 * time.Millisecond)
resp, err := http.Get("http://localhost:19150/health")
if err != nil {
t.Fatalf("failed to GET /health: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("/health returned status %d, want %d", resp.StatusCode, http.StatusOK)
}
}
func TestReadyEndpoint(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
errCh := make(chan error, 1)
originalPort := port
port = 19151
defer func() { port = originalPort }()
go setupHTTPListener(ctx, errCh)
time.Sleep(100 * time.Millisecond)
resp, err := http.Get("http://localhost:19151/ready")
if err != nil {
t.Fatalf("failed to GET /ready: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Fatalf("/ready returned status %d, want %d", resp.StatusCode, http.StatusOK)
}
}
func BenchmarkParseBytesToken(b *testing.B) {
inputs := []string{"39,889,034,403", "5.5K", "1.25MiB", "2.5G", "100B"}
b.ResetTimer()
for i := 0; i < b.N; i++ {
for _, input := range inputs {
parseBytesToken(input)
}
}
}