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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
#![allow(clippy::float_cmp)]
pub use super::stats::*;
use slog::o;
#[allow(unused_imports)]
use std::io::BufRead;
use std::sync::Mutex;
pub type Buffer = iobuffer::IoBuffer;
pub fn new_test_logger(data: Buffer) -> slog::Logger {
slog::Logger::root(
slog::Fuse::new(Mutex::new(slog_json::Json::default(data))),
o!(),
)
}
pub fn read_json_values(data: &mut Buffer) -> Vec<serde_json::Value> {
let iter = data.lines().map(move |line| {
serde_json::from_slice::<serde_json::Value>(&line).expect("JSON parse error")
});
iter.collect()
}
pub fn log_in_range(min_id: &str, max_id: &str, log: &serde_json::Value) -> bool {
match log["log_id"].as_str() {
Some(log_id) => log_id >= min_id && log_id < max_id,
None => false,
}
}
pub fn logs_in_range(min_id: &str, max_id: &str, data: &mut Buffer) -> Vec<serde_json::Value> {
let mut v = read_json_values(data)
.into_iter()
.filter(|log| log_in_range(min_id, max_id, log))
.collect::<Vec<_>>();
v.sort_by_key(|log| log["log_id"].as_str().map(ToString::to_string));
v
}
pub fn assert_json_matches(actual: &serde_json::Value, expected: &serde_json::Value) {
fn check(
actual: &serde_json::Value,
expected: &serde_json::Value,
left: &serde_json::Value,
right: &serde_json::Value,
path: &str,
) {
if left.is_object() && right.is_object() {
for (key, value) in right.as_object().unwrap().iter() {
let path = format!("{}.{}", path, key);
check(actual, expected, &left[key], value, &path);
}
} else if left.is_array() && right.is_array() {
for (index, value) in right.as_array().unwrap().iter().enumerate() {
let path = format!("{}.{}", path, index);
check(actual, expected, &left[index], value, &path);
}
} else {
assert!(
left == right,
"Mismatch at {}:\nexpected:\n{}\nbut found:\n{}",
path,
expected,
actual
);
}
}
check(actual, expected, actual, expected, "");
}
pub static TEST_LOG_INTERVAL: u64 = 5;
pub fn create_logger_buffer(
stats: StatDefinitions,
) -> (StatisticsLogger<DefaultStatisticsLogFormatter>, Buffer) {
let data = iobuffer::IoBuffer::new();
let logger = new_test_logger(data.clone());
let builder = StatsLoggerBuilder::<DefaultStatisticsLogFormatter>::default();
#[cfg(feature = "interval_logging")]
let builder = builder.with_log_interval(TEST_LOG_INTERVAL);
let logger = builder.with_stats(vec![stats]).fuse(logger);
(logger, data)
}
pub struct ExpectedStat {
pub stat_name: &'static str,
pub tag: Option<&'static str>,
pub value: f64,
pub metric_type: &'static str,
}
pub fn check_expected_stats(logs: &[serde_json::Value], mut expected_stats: Vec<ExpectedStat>) {
for log in logs {
let mut matched = None;
for (id, exp) in expected_stats.iter().enumerate() {
if log["name"] == exp.stat_name
&& (exp.tag.is_none() || log["tags"] == exp.tag.unwrap())
{
assert_eq!(logs[0]["metric_type"], exp.metric_type);
assert_eq!(log["value"].as_f64(), Some(exp.value));
matched = Some(id);
break;
}
}
assert!(matched.is_some());
expected_stats.remove(matched.unwrap());
}
assert_eq!(expected_stats.len(), 0);
}
#[derive(Debug)]
pub struct ExpectedStatSnapshot {
pub name: &'static str,
pub description: &'static str,
pub stat_type: StatType,
pub values: Vec<ExpectedStatSnapshotValue>,
pub buckets: Option<Buckets>,
}
#[derive(Debug)]
pub struct ExpectedStatSnapshotValue {
pub group_values: Vec<String>,
pub value: f64,
pub bucket_limit: Option<BucketLimit>,
}
pub fn check_expected_stat_snapshots(
stats: &[StatSnapshot],
expected_stats: &[ExpectedStatSnapshot],
) {
for stat in expected_stats {
let found_stat = stats.iter().find(|s| s.definition.name() == stat.name);
assert!(found_stat.is_some(), "Failed to find stat {}", stat.name);
let found_stat = found_stat.unwrap();
assert_eq!(found_stat.definition.stype(), stat.stat_type);
assert_eq!(found_stat.definition.description(), stat.description);
assert_eq!(found_stat.definition.buckets(), stat.buckets);
match found_stat.values {
StatSnapshotValues::Counter(ref vals) | StatSnapshotValues::Gauge(ref vals) => {
for value in &stat.values {
let found_value = vals
.iter()
.find(|val| val.group_values == value.group_values);
assert!(
found_value.is_some(),
"Failed to find value with groups {:?} and bucket_limit {:?} for stat {}",
value.group_values,
value.bucket_limit,
stat.name
);
let found_value = found_value.unwrap();
assert_eq!(found_value.group_values, value.group_values);
assert_eq!(found_value.value, value.value);
}
}
StatSnapshotValues::BucketCounter(ref buckets, ref vals) => {
assert_eq!(Some(buckets), stat.buckets.as_ref());
for value in &stat.values {
let found_value = vals.iter().find(|(val, bucket)| {
val.group_values == value.group_values
&& Some(bucket) == value.bucket_limit.as_ref()
});
assert!(
found_value.is_some(),
"Failed to find value with groups {:?} and bucket_limit {:?} for stat {}",
value.group_values,
value.bucket_limit,
stat.name
);
let (found_value, _) = found_value.unwrap();
assert_eq!(found_value.group_values, value.group_values);
assert_eq!(found_value.value, value.value);
}
}
}
}
assert_eq!(stats.len(), expected_stats.len());
}
#[cfg(test)]
mod tests {
use super::*;
use slog::debug;
use std::sync::mpsc;
use std::thread;
#[test]
fn test_partial_write() {
let mut data = iobuffer::IoBuffer::new();
let logger = new_test_logger(data.clone());
let (started_send, started_recv) = mpsc::channel();
let (done_send, done_recv) = mpsc::channel();
let _ = thread::spawn(move || {
started_send.send(()).unwrap();
while done_recv.try_recv().is_err() {
debug!(logger, "Some data";
"alfa" => "alpha",
"bravo" => "beta",
"charlie" => "gamma",
"delta" => "delta",
"echo" => "epsilon");
}
});
started_recv.recv().unwrap();
let _ = read_json_values(&mut data);
done_send.send(()).unwrap();
}
}