vrl 0.32.0

Vector Remap Language
Documentation
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
#![allow(clippy::print_stdout)] // tests
#![allow(clippy::print_stderr)] // tests

use std::path::{MAIN_SEPARATOR, PathBuf};
use std::{collections::BTreeMap, env, str::FromStr, time::Instant};

use chrono::{DateTime, SecondsFormat, Utc};
use nu_ansi_term::Color;

pub use test::Test;

use crate::compiler::{
    CompilationResult, CompileConfig, Function, Program, SecretTarget, TargetValueRef, TimeZone,
    VrlRuntime, compile_with_external,
    runtime::{Runtime, Terminate},
    state::{ExternalEnv, RuntimeState},
    value::VrlValueConvert,
};
use crate::diagnostic::{DiagnosticList, Formatter};
use crate::value::Secrets;
use crate::value::Value;

#[allow(clippy::module_inception)]
mod test;

fn measure_time<F, R>(f: F) -> (R, std::time::Duration)
where
    F: FnOnce() -> R, // F is a closure that takes no argument and returns a value of type R
{
    let start = Instant::now();
    let result = f(); // Execute the closure
    let duration = start.elapsed();
    (result, duration) // Return the result of the closure and the elapsed time
}

pub struct TestConfig {
    pub fail_early: bool,
    pub verbose: bool,
    pub no_diff: bool,
    pub timings: bool,
    pub runtime: VrlRuntime,
    pub timezone: TimeZone,
    pub run_skipped: bool,
}

#[derive(Clone)]
struct FailedTest {
    name: String,
    category: String,
    source_file: String,
    source_line: u32,
}

pub fn test_dir() -> PathBuf {
    PathBuf::from(env::var_os("CARGO_MANIFEST_DIR").unwrap())
}

pub fn test_prefix() -> String {
    let mut prefix = test_dir().join("tests").to_string_lossy().to_string();
    prefix.push(MAIN_SEPARATOR);
    prefix
}

pub fn example_vrl_path() -> PathBuf {
    test_dir().join("tests").join("example.vrl")
}

pub fn get_tests_from_functions(functions: Vec<Box<dyn Function>>) -> Vec<Test> {
    let mut tests = vec![];
    functions.into_iter().for_each(|function| {
        if let Some(closure) = function.closure() {
            closure.inputs.iter().for_each(|input| {
                let test = Test::from_example(
                    format!("{} (closure)", function.identifier()),
                    &input.example,
                );
                tests.push(test);
            });
        }

        function.examples().iter().for_each(|example| {
            let test = Test::from_example(function.identifier(), example);
            tests.push(test)
        })
    });

    tests
}

pub fn run_tests<T>(
    tests: Vec<Test>,
    cfg: &TestConfig,
    functions: &[Box<dyn Function>],
    compile_config_provider: impl Fn() -> (CompileConfig, T),
    finalize_config: impl Fn(T),
) {
    let total_count = tests.len();
    let mut failed_count = 0;
    let mut warnings_count = 0;
    let mut category = "".to_owned();
    let mut failed_tests: Vec<FailedTest> = Vec::new();

    for mut test in tests {
        if category != test.category {
            category.clone_from(&test.category);
            println!("{}", Color::Fixed(3).bold().paint(category.to_string()));
        }

        if let Some(err) = test.error {
            println!("{}", Color::Purple.bold().paint("INVALID"));
            println!("{}", Color::Red.paint(err));
            failed_count += 1;
            continue;
        }

        let mut name = test.name.clone();
        name.truncate(58);

        let dots = if name.len() >= 60 { 0 } else { 60 - name.len() };
        print!("  {}{}", name, Color::Fixed(240).paint(".".repeat(dots)));

        let (mut config, config_metadata) = (compile_config_provider)();
        // Set some read-only paths that can be tested
        for (path, recursive) in &test.read_only_paths {
            config.set_read_only_path(path.clone(), *recursive);
        }

        let (result, compile_duration) = measure_time(|| {
            compile_with_external(&test.source, functions, &ExternalEnv::default(), config)
        });
        let compile_timing_fmt = if cfg.timings {
            format!("comp: {compile_duration:>9.3?}")
        } else {
            String::new()
        };

        let failed = match result {
            Ok(CompilationResult {
                program,
                warnings,
                config: _,
            }) => {
                warnings_count += warnings.len();

                if test.skip && !cfg.run_skipped {
                    println!("{}", Color::Yellow.bold().paint("OK (compile only)"));
                    false
                } else if test.check_diagnostics {
                    process_compilation_diagnostics(&test, cfg, warnings, compile_timing_fmt)
                } else if warnings.is_empty() {
                    let run_start = Instant::now();

                    finalize_config(config_metadata);
                    let result = run_vrl(program, &mut test.object, cfg.timezone, cfg.runtime);
                    let run_end = run_start.elapsed();

                    let timings = {
                        let timings_color = if run_end.as_millis() > 10 { 1 } else { 245 };
                        let timings_fmt = if cfg.timings {
                            format!(" ({compile_timing_fmt}, run: {run_end:>9.3?})")
                        } else {
                            String::new()
                        };
                        Color::Fixed(timings_color).paint(timings_fmt).to_string()
                    };

                    process_result(result, &mut test, cfg, timings)
                } else {
                    println!("{} (diagnostics)", Color::Red.bold().paint("FAILED"));
                    let formatter = Formatter::new(&test.source, warnings);
                    println!("{formatter}");
                    // mark as failure, did not expect any warnings
                    true
                }
            }
            Err(diagnostics) => {
                warnings_count += diagnostics.warnings().len();
                process_compilation_diagnostics(&test, cfg, diagnostics, compile_timing_fmt)
            }
        };
        if failed {
            failed_count += 1;
            failed_tests.push(FailedTest {
                name: test.name.clone(),
                category: test.category.clone(),
                source_file: test.source_file.clone(),
                source_line: test.source_line,
            });
        }
    }

    print_result(total_count, failed_count, warnings_count, failed_tests);
}

fn process_result(
    result: Result<Value, Terminate>,
    test: &mut Test,
    config: &TestConfig,
    timings: String,
) -> bool {
    match result {
        Ok(got) => {
            let got_value = vrl_value_to_json_value(got);
            let mut failed = false;

            let match_mode = if test.check_type_only {
                MatchMode::TypeOnly
            } else {
                MatchMode::Exact
            };

            let want = test.result.clone();
            let want_value = if want.starts_with("r'") && want.ends_with('\'') {
                match regex::Regex::new(&want[2..want.len() - 1].replace("\\'", "'")) {
                    Ok(regex) => regex.to_string().into(),
                    Err(_) => want.into(),
                }
            } else if want.starts_with("t'") && want.ends_with('\'') {
                match DateTime::<Utc>::from_str(&want[2..want.len() - 1]) {
                    Ok(dt) => dt.to_rfc3339_opts(SecondsFormat::AutoSi, true).into(),
                    Err(_) => want.into(),
                }
            } else if want.starts_with("s'") && want.ends_with('\'') {
                want[2..want.len() - 1].into()
            } else {
                serde_json::from_str::<'_, serde_json::Value>(want.trim()).unwrap_or_else(|err| {
                    eprintln!("{err}");
                    want.into()
                })
            };

            if match_mode.matches(&got_value, &want_value) {
                print!(
                    "{timings}{}",
                    Color::Green.bold().paint(match_mode.ok_label())
                );
            } else {
                print!("{}", Color::Red.bold().paint(match_mode.fail_label()));

                if !config.no_diff {
                    let want = serde_json::to_string_pretty(&want_value).unwrap();
                    let got = serde_json::to_string_pretty(&got_value).unwrap();

                    let diff = prettydiff::diff_lines(&want, &got);
                    println!("  {diff}");
                }

                failed = true;
            }
            println!();

            if config.verbose {
                println!("{got_value:#}");
            }

            if failed && config.fail_early {
                std::process::exit(1)
            }
            failed
        }
        Err(err) => {
            let mut failed = false;
            let got = err.to_string().trim().to_owned();
            let want = test.result.clone().trim().to_owned();

            if (test.result_approx && compare_partial_diagnostic(&got, &want)) || got == want {
                println!("{}{}", Color::Green.bold().paint("OK"), timings);
            } else if matches!(err, Terminate::Abort { .. }) {
                let want =
                    serde_json::from_str::<'_, serde_json::Value>(&want).unwrap_or_else(|err| {
                        eprintln!("{err}");
                        want.into()
                    });

                let got = vrl_value_to_json_value(test.object.clone());
                if got == want {
                    println!("{}{}", Color::Green.bold().paint("OK"), timings);
                } else {
                    println!("{} (abort)", Color::Red.bold().paint("FAILED"));

                    if !config.no_diff {
                        let want = serde_json::to_string_pretty(&want).unwrap();
                        let got = serde_json::to_string_pretty(&got).unwrap();
                        let diff = prettydiff::diff_lines(&want, &got);
                        println!("{diff}");
                    }

                    failed = true;
                }
            } else {
                println!("{} (runtime)", Color::Red.bold().paint("FAILED"));

                if !config.no_diff {
                    let diff = prettydiff::diff_lines(&want, &got);
                    println!("{diff}");
                }

                failed = true;
            }

            if config.verbose {
                println!("{err:#}");
            }

            if failed && config.fail_early {
                std::process::exit(1)
            }
            failed
        }
    }
}

fn process_compilation_diagnostics(
    test: &Test,
    cfg: &TestConfig,
    diagnostics: DiagnosticList,
    compile_timing_fmt: String,
) -> bool {
    let mut failed = false;

    let mut formatter = Formatter::new(&test.source, diagnostics);

    let got = formatter.to_string();
    let got = got.trim();

    let want = test.result.clone();
    let want = want.trim();

    if (test.result_approx && compare_partial_diagnostic(got, want)) || got == want {
        let timings = {
            let timings_fmt = if cfg.timings {
                format!(" ({compile_timing_fmt})")
            } else {
                String::new()
            };
            Color::Fixed(245).paint(timings_fmt).to_string()
        };
        println!("{}{timings}", Color::Green.bold().paint("OK"));
    } else {
        println!("{} (compilation)", Color::Red.bold().paint("FAILED"));

        if !cfg.no_diff {
            let diff = prettydiff::diff_lines(want, got);
            println!("{diff}");
        }

        // Always print diagnostics when test fails
        formatter.enable_colors(true);
        println!("{formatter:#}");

        failed = true;
    }

    if cfg.verbose && !failed {
        // In verbose mode, print diagnostics even for passing tests
        formatter.enable_colors(true);
        println!("{formatter:#}");
    }

    if failed && cfg.fail_early {
        std::process::exit(1)
    }
    failed
}

fn print_result(
    total_count: usize,
    failed_count: usize,
    warnings_count: usize,
    failed_tests: Vec<FailedTest>,
) {
    let code = i32::from(failed_count > 0);

    println!("\n");

    let passed_count = total_count - failed_count;
    if failed_count > 0 {
        println!(
            "Overall result: {}\n\n  Number failed: {}\n  Number passed: {}",
            Color::Red.bold().paint("FAILED"),
            Color::Red.bold().paint(failed_count.to_string()),
            Color::Green.bold().paint(passed_count.to_string())
        );
    } else {
        println!(
            "Overall result: {}\n  Number passed: {}",
            Color::Green.bold().paint("SUCCESS"),
            Color::Green.bold().paint(passed_count.to_string())
        );
    }
    println!(
        "  Number warnings: {}",
        Color::Yellow.bold().paint(warnings_count.to_string())
    );

    if !failed_tests.is_empty() {
        println!("\n{}", Color::Red.bold().paint("Failed tests:"));
        for test in failed_tests {
            println!(
                "  {} - {}:{}",
                Color::Yellow.paint(format!("{}/{}", test.category, test.name)),
                test.source_file,
                test.source_line
            );
        }
    }

    std::process::exit(code)
}

fn compare_partial_diagnostic(got: &str, want: &str) -> bool {
    got.lines()
        .filter(|line| line.trim().starts_with("error[E"))
        .zip(want.trim().lines())
        .all(|(got, want)| got.contains(want))
}

fn vrl_value_to_json_value(value: Value) -> serde_json::Value {
    use serde_json::Value::*;

    match value {
        v @ Value::Bytes(_) => String(v.try_bytes_utf8_lossy().unwrap().into_owned()),
        Value::Integer(v) => v.into(),
        Value::Float(v) => v.into_inner().into(),
        Value::Boolean(v) => v.into(),
        Value::Object(v) => v
            .into_iter()
            .map(|(k, v)| (k, vrl_value_to_json_value(v)))
            .collect::<serde_json::Value>(),
        Value::Array(v) => v
            .into_iter()
            .map(vrl_value_to_json_value)
            .collect::<serde_json::Value>(),
        Value::Timestamp(v) => v.to_rfc3339_opts(SecondsFormat::AutoSi, true).into(),
        Value::Regex(v) => v.to_string().into(),
        Value::Null => Null,
    }
}

enum MatchMode {
    Exact,
    TypeOnly,
}

impl MatchMode {
    fn matches(&self, got: &serde_json::Value, want: &serde_json::Value) -> bool {
        match self {
            MatchMode::Exact => got == want,
            MatchMode::TypeOnly => std::mem::discriminant(got) == std::mem::discriminant(want),
        }
    }

    fn ok_label(&self) -> &'static str {
        match self {
            MatchMode::Exact => "OK",
            MatchMode::TypeOnly => "OK (type match)",
        }
    }

    fn fail_label(&self) -> &'static str {
        match self {
            MatchMode::Exact => "FAILED (expectation)",
            MatchMode::TypeOnly => "FAILED (type mismatch)",
        }
    }
}

fn run_vrl(
    program: Program,
    test_object: &mut Value,
    timezone: TimeZone,
    vrl_runtime: VrlRuntime,
) -> Result<Value, Terminate> {
    let mut metadata = Value::from(BTreeMap::new());
    let mut target = TargetValueRef {
        value: test_object,
        metadata: &mut metadata,
        secrets: &mut Secrets::new(),
    };

    // Insert a dummy secret for examples to use
    target.insert_secret("my_secret", "secret value");
    target.insert_secret("datadog_api_key", "secret value");

    match vrl_runtime {
        VrlRuntime::Ast => {
            // test_enrichment.finish_load();
            let mut runtime = Runtime::new(RuntimeState::default());
            runtime.resolve(&mut target, &program, &timezone)
        }
    }
}