Skip to content
Myr

integration_tests.rs

This file

Path

tests/integration_tests.rs

1,274 lines · 36.4 KiB · Rust

Last changed by

Alternative performance metrics in the terminal (#986)David Peterbefore adoptionbdbfae9

History of this file

Take it

1mod common;2use common::{hyperfine, hyperfine_raw_command};34use assert_cmd::assert::OutputAssertExt;5use insta_cmd::assert_cmd_snapshot;6use predicates::prelude::*;78/// Platform-specific I/O utility.9/// - On Unix-like systems, defaults to `cat`.10/// - On Windows, uses `findstr` as an alternative.11///   See: <https://superuser.com/questions/853580/real-windows-equivalent-to-cat-stdin>12const STDIN_READ_COMMAND: &str = if cfg!(windows) { "findstr x*" } else { "cat" };1314pub fn hyperfine_debug() -> std::process::Command {15    let mut cmd = hyperfine_raw_command();16    cmd.arg("--debug-mode");17    cmd18}1920fn snapshot_settings() -> insta::Settings {21    let mut settings = insta::Settings::clone_current();22    // Ignore trailing report padding while preserving indentation and internal spacing.23    settings.add_filter(r"(?m)[ \t]+$", "");24    settings25}2627fn json_snapshot_settings() -> insta::Settings {28    let mut settings = snapshot_settings();29    for field in ["hyperfine_version", "start_time", "os", "architecture"] {30        settings.add_filter(31            &format!(r#"("{field}": ")[^"]+(")"#),32            format!(r#"${{1}}[{field}]$2"#),33        );34    }35    settings36}3738#[test]39fn runs_successfully() {40    hyperfine()41        .arg("--runs=2")42        .arg("echo dummy benchmark")43        .assert()44        .success();45}4647#[test]48fn one_run_is_supported() {49    hyperfine()50        .arg("--runs=1")51        .arg("echo dummy benchmark")52        .assert()53        .success();54}5556/// Regression test: hyperfine must not panic when writing to a closed57/// stdout pipe (e.g. `hyperfine ... | head -n 1` or a downstream process58/// that terminates early). A `BrokenPipe` error should result in a quiet59/// exit with code 0 instead of a `println!` panic.60#[test]61fn exits_quietly_when_stdout_is_closed() {62    use std::process::Stdio;6364    for args in [65        vec!["--runs=1", "echo dummy benchmark"],66        vec!["--runs=1", "--export-json=-", "echo dummy benchmark"],67        vec!["--runs=1", "echo dummy benchmark", "echo second benchmark"],68    ] {69        // A pipe whose read end has been closed before hyperfine is even70        // started: every write to it will fail with `BrokenPipe`.71        let (reader, writer) = std::io::pipe().expect("failed to create pipe");72        drop(reader);7374        let output = hyperfine_raw_command()75            .args(&args)76            .stdout(writer)77            .stderr(Stdio::piped())78            .spawn()79            .expect("failed to spawn hyperfine")80            .wait_with_output()81            .expect("failed to wait for hyperfine");82        let stderr = String::from_utf8_lossy(&output.stderr);8384        assert!(85            !stderr.contains("panicked"),86            "hyperfine panicked while writing to a closed pipe:\n{}",87            stderr88        );89        assert!(90            output.status.success(),91            "hyperfine did not exit cleanly; stderr:\n{}",92            stderr93        );94    }95}9697#[test]98fn fails_with_zero_runs() {99    for option in ["--runs", "--min-runs", "--max-runs"] {100        hyperfine()101            .arg(option)102            .arg("0")103            .arg("echo dummy benchmark")104            .assert()105            .code(2)106            .stderr(predicate::str::contains(format!(107                "invalid value '0' for '{option} <NUM>'"108            )));109    }110}111112#[test]113fn min_runs_of_one_still_performs_one_run() {114    let _settings = snapshot_settings().bind_to_scope();115    assert_cmd_snapshot!(hyperfine_debug()116        .arg("--style=basic")117        .arg("--metrics=time_wall_clock")118        .arg("--min-runs=1")119        .arg("--warmup=0")120        .arg("sleep 4"), @"121    success: true122    exit_code: 0123    ----- stdout -----124    Benchmark 1: sleep 4 (1 run)125                   Value126      Wall Time    4.000 s127128129    ----- stderr -----130    ");131}132133#[test]134fn can_run_commands_without_a_shell() {135    hyperfine()136        .arg("--runs=1")137        .arg("--show-output")138        .arg("--shell=none")139        .arg("echo 'hello world' argument2")140        .assert()141        .success()142        .stdout(predicate::str::contains("hello world argument2"));143}144145#[test]146fn fails_with_wrong_number_of_command_name_arguments() {147    hyperfine()148        .arg("--command-name=a")149        .arg("--command-name=b")150        .arg("echo a")151        .assert()152        .failure()153        .stderr(predicate::str::contains("Too many --command-name options"));154}155156#[test]157fn fails_with_wrong_number_of_prepare_options() {158    hyperfine()159        .arg("--runs=1")160        .arg("--prepare=echo a")161        .arg("--prepare=echo b")162        .arg("echo a")163        .arg("echo b")164        .assert()165        .success();166167    hyperfine()168        .arg("--runs=1")169        .arg("--prepare=echo ref")170        .arg("--prepare=echo a")171        .arg("--prepare=echo b")172        .arg("echo ref")173        .arg("echo a")174        .arg("echo b")175        .assert()176        .success();177178    hyperfine()179        .arg("--runs=1")180        .arg("--prepare=echo a")181        .arg("--prepare=echo b")182        .arg("echo a")183        .arg("echo b")184        .arg("echo c")185        .assert()186        .failure()187        .stderr(predicate::str::contains(188            "The '--prepare' option has to be provided",189        ));190191    hyperfine()192        .arg("--runs=1")193        .arg("--prepare=echo a")194        .arg("--prepare=echo b")195        .arg("echo ref")196        .arg("echo a")197        .arg("echo b")198        .assert()199        .failure()200        .stderr(predicate::str::contains(201            "The '--prepare' option has to be provided",202        ));203}204205#[test]206fn fails_with_wrong_number_of_conclude_options() {207    hyperfine()208        .arg("--runs=1")209        .arg("--conclude=echo a")210        .arg("--conclude=echo b")211        .arg("echo a")212        .arg("echo b")213        .assert()214        .success();215216    hyperfine()217        .arg("--runs=1")218        .arg("--conclude=echo ref")219        .arg("--conclude=echo a")220        .arg("--conclude=echo b")221        .arg("echo ref")222        .arg("echo a")223        .arg("echo b")224        .assert()225        .success();226227    hyperfine()228        .arg("--runs=1")229        .arg("--conclude=echo a")230        .arg("--conclude=echo b")231        .arg("echo a")232        .arg("echo b")233        .arg("echo c")234        .assert()235        .failure()236        .stderr(predicate::str::contains(237            "The '--conclude' option has to be provided",238        ));239240    hyperfine()241        .arg("--runs=1")242        .arg("--conclude=echo a")243        .arg("--conclude=echo b")244        .arg("echo ref")245        .arg("echo a")246        .arg("echo b")247        .assert()248        .failure()249        .stderr(predicate::str::contains(250            "The '--conclude' option has to be provided",251        ));252}253254#[test]255fn fails_with_duplicate_parameter_names() {256    hyperfine()257        .arg("--parameter-list")258        .arg("x")259        .arg("1,2,3")260        .arg("--parameter-list")261        .arg("x")262        .arg("a,b,c")263        .arg("echo test")264        .assert()265        .failure()266        .stderr(predicate::str::contains("Duplicate parameter names: x"));267}268269#[test]270fn fails_for_unknown_command() {271    hyperfine()272        .arg("--shell=default")273        .arg("--runs=1")274        .arg("some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")275        .assert()276        .failure()277        .stderr(predicate::str::contains(278            "Command terminated with non-zero exit code",279        ));280}281282#[test]283fn fails_for_unknown_command_without_shell() {284    hyperfine()285        .arg("--shell=none")286        .arg("--runs=1")287        .arg("some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")288        .assert()289        .failure()290        .stderr(predicate::str::contains(291            "Failed to run command 'some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577'",292        ));293}294295#[cfg(unix)]296#[test]297fn fails_for_failing_command_without_shell() {298    hyperfine()299        .arg("--shell=none")300        .arg("--runs=1")301        .arg("false")302        .assert()303        .failure()304        .stderr(predicate::str::contains(305            "Command terminated with non-zero exit code",306        ));307}308309#[test]310fn fails_for_unknown_setup_command() {311    hyperfine()312        .arg("--shell=default")313        .arg("--runs=1")314        .arg("--setup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")315        .arg("echo test")316        .assert()317        .failure()318        .stderr(predicate::str::contains(319            "The setup command terminated with a non-zero exit code.",320        ));321}322323#[test]324fn fails_for_unknown_cleanup_command() {325    hyperfine()326        .arg("--shell=default")327        .arg("--runs=1")328        .arg("--cleanup=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")329        .arg("echo test")330        .assert()331        .failure()332        .stderr(predicate::str::contains(333            "The cleanup command terminated with a non-zero exit code.",334        ));335}336337#[test]338fn fails_for_unknown_prepare_command() {339    hyperfine()340        .arg("--shell=default")341        .arg("--prepare=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")342        .arg("echo test")343        .assert()344        .failure()345        .stderr(predicate::str::contains(346            "The preparation command terminated with a non-zero exit code.",347        ));348}349350#[test]351fn fails_for_unknown_conclude_command() {352    hyperfine()353        .arg("--shell=default")354        .arg("--conclude=some-nonexisting-program-b5d9574198b7e4b12a71fa4747c0a577")355        .arg("echo test")356        .assert()357        .failure()358        .stderr(predicate::str::contains(359            "The conclusion command terminated with a non-zero exit code.",360        ));361}362363#[cfg(unix)]364#[test]365fn can_run_failing_commands_with_ignore_failure_option() {366    hyperfine()367        .arg("false")368        .assert()369        .failure()370        .stderr(predicate::str::contains(371            "Command terminated with non-zero exit code",372        ));373374    hyperfine()375        .arg("--runs=1")376        .arg("--ignore-failure")377        .arg("false")378        .assert()379        .success();380}381382#[cfg(unix)]383#[test]384fn can_ignore_specific_exit_codes() {385    // Test that specifying exit code 1 ignores it386    hyperfine()387        .arg("--shell=default")388        .arg("--runs=1")389        .arg("--ignore-failure=1")390        .arg("exit 1")391        .assert()392        .success();393394    // Test that other exit codes still fail395    hyperfine()396        .arg("--shell=default")397        .arg("--runs=1")398        .arg("--ignore-failure=1")399        .arg("exit 2")400        .assert()401        .failure()402        .stderr(predicate::str::contains(403            "Command terminated with non-zero exit code 2",404        ));405}406407#[cfg(unix)]408#[test]409fn can_ignore_multiple_exit_codes() {410    // Test that all specified exit codes are ignored411    hyperfine()412        .arg("--shell=default")413        .arg("--runs=1")414        .arg("--ignore-failure=1,2,3")415        .arg("exit 1")416        .assert()417        .success();418419    hyperfine()420        .arg("--shell=default")421        .arg("--runs=1")422        .arg("--ignore-failure=1,2,3")423        .arg("exit 2")424        .assert()425        .success();426427    hyperfine()428        .arg("--shell=default")429        .arg("--runs=1")430        .arg("--ignore-failure=1,2,3")431        .arg("exit 3")432        .assert()433        .success();434435    // Test that other exit codes still fail436    hyperfine()437        .arg("--shell=default")438        .arg("--runs=1")439        .arg("--ignore-failure=1,2,3")440        .arg("exit 4")441        .assert()442        .failure()443        .stderr(predicate::str::contains(444            "Command terminated with non-zero exit code 4",445        ));446}447448#[cfg(unix)]449#[test]450fn ignore_failure_with_all_non_zero() {451    // Test explicit "all-non-zero" mode452    hyperfine()453        .arg("--shell=default")454        .arg("--runs=1")455        .arg("--ignore-failure=all-non-zero")456        .arg("exit 5")457        .assert()458        .success();459}460461#[test]462fn shows_output_of_benchmarked_command() {463    hyperfine()464        .arg("--runs=2")465        .arg("--command-name=dummy")466        .arg("--show-output")467        .arg("echo 4fd47015")468        .assert()469        .success()470        .stdout(predicate::str::contains("4fd47015").count(2));471}472473#[test]474fn runs_commands_using_user_defined_shell() {475    hyperfine()476        .arg("--runs=1")477        .arg("--show-output")478        .arg("--shell")479        .arg("echo 'custom_shell' '--shell-arg'")480        .arg("echo benchmark")481        .assert()482        .success()483        .stdout(484            predicate::str::contains("custom_shell --shell-arg -c echo benchmark").or(485                predicate::str::contains("custom_shell --shell-arg /C echo benchmark"),486            ),487        );488}489490#[test]491fn can_pass_input_to_command_from_a_file() {492    hyperfine()493        .arg("--runs=1")494        .arg("--input=example_input_file.txt")495        .arg("--show-output")496        .arg(STDIN_READ_COMMAND)497        .assert()498        .success()499        .stdout(predicate::str::contains("This text is part of a file"));500}501502#[test]503fn fails_if_invalid_stdin_data_file_provided() {504    hyperfine()505        .arg("--runs=1")506        .arg("--input=example_non_existent_file.txt")507        .arg("--show-output")508        .arg(STDIN_READ_COMMAND)509        .assert()510        .failure()511        .stderr(predicate::str::contains(512            "The file 'example_non_existent_file.txt' specified as '--input' does not exist",513        ));514}515516#[test]517fn returns_mean_time_in_correct_unit() {518    hyperfine_debug()519        .arg("sleep 1.234")520        .assert()521        .success()522        .stdout(predicate::str::is_match(r"Wall Time\s+1\.234 s\s+±").unwrap());523524    hyperfine_debug()525        .arg("sleep 0.123")526        .assert()527        .success()528        .stdout(predicate::str::is_match(r"Wall Time\s+123\.0 ms\s+±").unwrap());529530    hyperfine_debug()531        .arg("--metrics=time_wall_clock:ms")532        .arg("sleep 1.234")533        .assert()534        .success()535        .stdout(predicate::str::is_match(r"Wall Time\s+1234\.0 ms\s+±").unwrap());536537    hyperfine_debug()538        .arg("--metrics=time_wall_clock:us")539        .arg("sleep 1.234")540        .assert()541        .success()542        .stdout(predicate::str::is_match(r"Wall Time\s+1234000\.0 µs\s+±").unwrap());543}544545#[test]546fn performs_ten_runs_for_slow_commands() {547    hyperfine_debug()548        .arg("sleep 0.5")549        .assert()550        .success()551        .stdout(predicate::str::contains("10 runs"));552}553554#[test]555fn performs_three_seconds_of_benchmarking_for_fast_commands() {556    hyperfine_debug()557        .arg("sleep 0.01")558        .assert()559        .success()560        .stdout(predicate::str::contains("300 runs"));561}562563#[test]564fn takes_shell_spawning_time_into_account_for_computing_number_of_runs() {565    hyperfine_debug()566        .arg("--shell=sleep 0.02")567        .arg("sleep 0.01")568        .assert()569        .success()570        .stdout(predicate::str::contains("100 runs"));571}572573#[test]574fn takes_preparation_command_into_account_for_computing_number_of_runs() {575    hyperfine_debug()576        .arg("--prepare=sleep 0.02")577        .arg("sleep 0.01")578        .assert()579        .success()580        .stdout(predicate::str::contains("100 runs"));581582    // Shell overhead needs to be added to both the prepare command and the actual command,583    // leading to a total benchmark time of (prepare + shell + cmd + shell = 0.1 s)584    hyperfine_debug()585        .arg("--shell=sleep 0.01")586        .arg("--prepare=sleep 0.03")587        .arg("sleep 0.05")588        .assert()589        .success()590        .stdout(predicate::str::contains("30 runs"));591}592593#[test]594fn takes_conclusion_command_into_account_for_computing_number_of_runs() {595    hyperfine_debug()596        .arg("--conclude=sleep 0.02")597        .arg("sleep 0.01")598        .assert()599        .success()600        .stdout(predicate::str::contains("100 runs"));601602    // Shell overhead needs to be added to both the conclude command and the actual command,603    // leading to a total benchmark time of (cmd + shell + conclude + shell = 0.1 s)604    hyperfine_debug()605        .arg("--shell=sleep 0.01")606        .arg("--conclude=sleep 0.03")607        .arg("sleep 0.05")608        .assert()609        .success()610        .stdout(predicate::str::contains("30 runs"));611}612613#[test]614fn takes_both_preparation_and_conclusion_command_into_account_for_computing_number_of_runs() {615    hyperfine_debug()616        .arg("--prepare=sleep 0.01")617        .arg("--conclude=sleep 0.01")618        .arg("sleep 0.01")619        .assert()620        .success()621        .stdout(predicate::str::contains("100 runs"));622623    // Shell overhead needs to be added to both the prepare, conclude and the actual command,624    // leading to a total benchmark time of (prepare + shell + cmd + shell + conclude + shell = 0.1 s)625    hyperfine_debug()626        .arg("--shell=sleep 0.01")627        .arg("--prepare=sleep 0.01")628        .arg("--conclude=sleep 0.01")629        .arg("sleep 0.05")630        .assert()631        .success()632        .stdout(predicate::str::contains("30 runs"));633}634635#[test]636fn secondary_metrics_include_factors_for_large_changes() {637    // Mock CPU time is zero; secondary wall time still gets ratio annotations.638    let output = hyperfine_debug()639        .args([640            "--metrics=time_cpu,time_wall_clock",641            "--style=basic",642            "--runs=2",643            "sleep 1",644            "sleep 10",645            "sleep 0.1",646        ])647        .output()648        .unwrap();649    assert!(output.status.success(), "{:?}", output);650    let stdout = String::from_utf8(output.stdout).unwrap();651    assert!(stdout.contains("+900.0%"), "{}", stdout);652    assert!(stdout.contains("-90.0%"), "{}", stdout);653    assert!(stdout.contains("+900.0%  (10.0x slower)"), "{}", stdout);654    assert!(stdout.contains("-90.0%  (10.0x faster)"), "{}", stdout);655}656657#[test]658fn shows_multiple_metrics_relative_to_first_command() {659    let _settings = snapshot_settings().bind_to_scope();660    assert_cmd_snapshot!(hyperfine_debug()661        .arg("--style=basic")662        .arg("--metrics=time_wall_clock:ms,time_user:us,memory_peak_resident:MiB")663        .arg("sleep 0.0817")664        .arg("sleep 0.6155")665        .arg("sleep 0.1707"), @"666    success: true667    exit_code: 0668    ----- stdout -----669    Benchmark 1: sleep 0.0817 (36 runs)670                    mean     ±       σ          min     …     max671      Wall Time     81.7 ms  ±     0.0 ms      81.7 ms  …    81.7 ms672      User time      0.0 µs  ±     0.0 µs       0.0 µs  …     0.0 µs673      Memory         0.0 MiB ±     0.0 MiB      0.0 MiB …     0.0 MiB674675    Benchmark 2: sleep 0.6155 (10 runs)676                    mean     ±       σ          min     …     max677      Wall Time    615.5 ms  ±     0.0 ms     615.5 ms  …   615.5 ms          +653.4%  (7.5x slower)678      User time      0.0 µs  ±     0.0 µs       0.0 µs  …     0.0 µs              N/A679      Memory         0.0 MiB ±     0.0 MiB      0.0 MiB …     0.0 MiB             N/A680681    Benchmark 3: sleep 0.1707 (17 runs)682                    mean     ±       σ          min     …     max683      Wall Time    170.7 ms  ±     0.0 ms     170.7 ms  …   170.7 ms          +108.9%  (2.1x slower)684      User time      0.0 µs  ±     0.0 µs       0.0 µs  …     0.0 µs              N/A685      Memory         0.0 MiB ±     0.0 MiB      0.0 MiB …     0.0 MiB             N/A686687688    ----- stderr -----689    ");690}691692#[test]693fn shows_benchmark_comparison_with_same_time() {694    let _settings = snapshot_settings().bind_to_scope();695    assert_cmd_snapshot!(hyperfine_debug()696        .arg("--metrics=time_wall_clock,memory_peak_resident")697        .arg("--style=basic")698        .arg("--command-name=A")699        .arg("--command-name=B")700        .arg("sleep 1.0")701        .arg("sleep 1.0")702        .arg("sleep 2.0")703        .arg("sleep 1000.0"), @"704    success: true705    exit_code: 0706    ----- stdout -----707    Benchmark 1: A (10 runs)708                    mean     ±       σ          min     …     max709      Wall Time    1.000 s   ±   0.000 s      1.000 s   …   1.000 s710      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B711712    Benchmark 2: B (10 runs)713                    mean     ±       σ          min     …     max714      Wall Time    1.000 s   ±   0.000 s      1.000 s   …   1.000 s              0.0%715      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B               N/A716717    Benchmark 3: sleep 2.0 (10 runs)718                    mean     ±       σ          min     …     max719      Wall Time    2.000 s   ±   0.000 s      2.000 s   …   2.000 s           +100.0%  (2.0x slower)720      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B               N/A721722    Benchmark 4: sleep 1000.0 (10 runs)723                     mean     ±       σ           min     …      max724      Wall Time  1000.000 s   ±   0.000 s    1000.000 s   … 1000.000 s         +99900.0%  (1000.0x slower)725      Memory          0.0 B   ±     0.0 B         0.0 B   …      0.0 B               N/A726727728    ----- stderr -----729    ");730}731732#[test]733fn shows_benchmark_comparison_relative_to_reference() {734    let _settings = snapshot_settings().bind_to_scope();735    assert_cmd_snapshot!(hyperfine_debug()736        .arg("--metrics=time_wall_clock,memory_peak_resident")737        .arg("--style=basic")738        .arg("sleep 2.0")739        .arg("sleep 1.0")740        .arg("sleep 3.0"), @"741    success: true742    exit_code: 0743    ----- stdout -----744    Benchmark 1: sleep 2.0 (10 runs)745                    mean     ±       σ          min     …     max746      Wall Time    2.000 s   ±   0.000 s      2.000 s   …   2.000 s747      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B748749    Benchmark 2: sleep 1.0 (10 runs)750                    mean     ±       σ          min     …     max751      Wall Time    1.000 s   ±   0.000 s      1.000 s   …   1.000 s            -50.0%  (2.0x faster)752      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B               N/A753754    Benchmark 3: sleep 3.0 (10 runs)755                    mean     ±       σ          min     …     max756      Wall Time    3.000 s   ±   0.000 s      3.000 s   …   3.000 s            +50.0%  (1.5x slower)757      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B               N/A758759760    ----- stderr -----761    ");762}763764#[test]765fn comparison_and_markup_identify_first_command_as_reference() {766    let _settings = snapshot_settings().bind_to_scope();767    let directory = tempfile::tempdir().unwrap();768    let export_path = directory.path().join("results.md");769    let output = hyperfine_debug()770        .args([771            "--style=basic",772            "--runs=1",773            "--command-name=baseline",774            "--export-markdown",775        ])776        .arg(&export_path)777        .args(["sleep 2", "sleep 1", "sleep 2", "sleep 3"])778        .output()779        .unwrap();780    assert!(output.status.success(), "{:?}", output);781    let stdout = String::from_utf8(output.stdout).unwrap();782    assert!(783        stdout.contains("Benchmark 1: baseline (1 run)"),784        "{}",785        stdout786    );787    assert!(stdout.contains("-50.0%"), "{}", stdout);788    assert!(stdout.contains("0.0%"), "{}", stdout);789    assert!(stdout.contains("+50.0%"), "{}", stdout);790    let markdown = std::fs::read_to_string(export_path).unwrap();791    insta::assert_snapshot!(markdown, @"792    | Command | Mean Wall Time [s] | Change | Factor |793    |:---|---:|---:|:---|794    | `baseline` | 2.000 |  |  |795    | `sleep 1` | 1.000 | -50.0% | (2.0x faster) |796    | `sleep 2` | 2.000 | 0.0% |  |797    | `sleep 3` | 3.000 | +50.0% | (1.5x slower) |798    ");799800    // Equal zero times have no meaningful relative factor.801    let output = hyperfine_debug()802        .args([803            "--style=none",804            "--runs=1",805            "--export-markdown=-",806            "--command-name=baseline",807            "sleep 0",808            "sleep 0",809        ])810        .output()811        .unwrap();812    assert!(output.status.success(), "{:?}", output);813    let markdown = String::from_utf8(output.stdout).unwrap();814    let row = markdown815        .lines()816        .find(|line| line.contains("sleep 0"))817        .unwrap();818    assert!(row.ends_with("| N/A |  |"), "{}", row);819}820821#[test]822fn performs_all_benchmarks_in_parameter_scan() {823    let _settings = snapshot_settings().bind_to_scope();824    assert_cmd_snapshot!(hyperfine_debug()825        .arg("--metrics=time_wall_clock,memory_peak_resident")826        .arg("--style=basic")827        .arg("--parameter-scan")828        .arg("time")829        .arg("30")830        .arg("45")831        .arg("--parameter-step-size")832        .arg("5")833        .arg("sleep {time}"), @"834    success: true835    exit_code: 0836    ----- stdout -----837    Benchmark 1: sleep 30 (10 runs)838                    mean     ±       σ          min     …     max839      Wall Time   30.000 s   ±   0.000 s     30.000 s   …  30.000 s840      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B841842    Benchmark 2: sleep 35 (10 runs)843                    mean     ±       σ          min     …     max844      Wall Time   35.000 s   ±   0.000 s     35.000 s   …  35.000 s            +16.7%845      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B               N/A846847    Benchmark 3: sleep 40 (10 runs)848                    mean     ±       σ          min     …     max849      Wall Time   40.000 s   ±   0.000 s     40.000 s   …  40.000 s            +33.3%  (1.3x slower)850      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B               N/A851852    Benchmark 4: sleep 45 (10 runs)853                    mean     ±       σ          min     …     max854      Wall Time   45.000 s   ±   0.000 s     45.000 s   …  45.000 s            +50.0%  (1.5x slower)855      Memory         0.0 B   ±     0.0 B        0.0 B   …     0.0 B               N/A856857858    ----- stderr -----859    ");860}861862#[test]863fn rejects_negative_parameter_steps() {864    for step in ["-1", "-1.0"] {865        hyperfine()866            .args(["--parameter-scan", "n", "0", "1"])867            .arg(format!("--parameter-step-size={step}"))868            .arg("echo {n}")869            .assert()870            .code(1)871            .stdout(predicate::str::is_empty())872            .stderr(predicate::str::contains(873                "Parameter step size must be positive",874            ));875    }876}877878#[cfg(unix)]879#[test]880fn preserves_input_order_with_parameterized_prepare() {881    let directory = tempfile::tempdir().unwrap();882    let csv_path = directory.path().join("results.csv");883    let json_path = directory.path().join("results.json");884    let output = hyperfine_raw_command()885        .args([886            "--style=basic",887            "--shell=none",888            "--runs=1",889            "-L",890            "delay",891            "0.2,0.4,0.6",892            "--prepare",893            "sleep {delay}",894            "--export-csv",895        ])896        .arg(&csv_path)897        .arg("--export-json")898        .arg(&json_path)899        .arg("echo a")900        .output()901        .unwrap();902    assert!(output.status.success(), "{:?}", output);903    let stdout = String::from_utf8(output.stdout).unwrap();904    assert_eq!(stdout.matches("Benchmark ").count(), 3);905    for (number, delay) in ["0.2", "0.4", "0.6"].iter().enumerate() {906        assert!(907            stdout.contains(&format!(908                "Benchmark {}: echo a (delay = {}) (1 run)",909                number + 1,910                delay911            )),912            "{}",913            stdout914        );915    }916    assert!(917        !stdout918            .split("Benchmark 2")919            .next()920            .unwrap()921            .contains("Change"),922        "{}",923        stdout924    );925    assert!(!stdout.contains("Change vs #1"));926927    let mut csv = csv::Reader::from_path(csv_path).unwrap();928    assert!(csv929        .headers()930        .unwrap()931        .iter()932        .any(|header| header == "parameter_delay"));933    assert_eq!(934        csv.records().collect::<Result<Vec<_>, _>>().unwrap().len(),935        3936    );937    let json: serde_json::Value =938        serde_json::from_slice(&std::fs::read(json_path).unwrap()).unwrap();939    let results = json["results"].as_array().unwrap();940    assert_eq!(results.len(), 3);941    assert_eq!(942        results943            .iter()944            .map(|result| result["parameters"]["delay"]["value"].as_str().unwrap())945            .collect::<Vec<_>>(),946        ["0.2", "0.4", "0.6"]947    );948}949950#[test]951fn rejects_invalid_metric_before_export_or_setup() {952    let directory = tempfile::tempdir().unwrap();953    let export_path = directory.path().join("results.csv");954    let marker_path = directory.path().join("setup-ran");955    std::fs::write(&export_path, "previous contents").unwrap();956957    hyperfine()958        .args([959            "--metrics=memory_peak_resident:ms",960            "-P",961            "secs",962            "2",963            "3",964            "--setup",965        ])966        .arg(format!("echo touched > \"{}\"", marker_path.display()))967        .arg("--export-csv")968        .arg(&export_path)969        .arg("sleep {secs}")970        .assert()971        .failure()972        .stdout(predicate::str::is_empty())973        .stderr(predicate::str::contains(974            "Unit 'ms' is not valid for metric 'memory_peak_resident'",975        ));976    assert_eq!(977        std::fs::read_to_string(export_path).unwrap(),978        "previous contents"979    );980    assert!(!marker_path.exists());981}982983#[cfg(unix)]984#[test]985fn intermediate_markdown_retains_completed_reference() {986    let directory = tempfile::tempdir().unwrap();987    let export_path = directory.path().join("results.md");988    hyperfine()989        .args([990            "--style=none",991            "--shell=none",992            "--runs=1",993            "-L",994            "delay",995            "0.01,0.02,0.03",996            "--prepare",997            "true",998            "--prepare",999            "false",1000            "--prepare",1001            "true",1002            "--export-markdown",1003        ])1004        .arg(&export_path)1005        .arg("sleep {delay}")1006        .assert()1007        .failure();1008    let markdown = std::fs::read_to_string(export_path).unwrap();1009    let row = markdown1010        .lines()1011        .find(|line| line.contains("sleep 0.01"))1012        .unwrap();1013    assert!(row.ends_with("|  |  |"), "{}", row);1014}10151016#[test]1017fn markdown_export_uses_first_parameterized_benchmark_as_reference() {1018    let _settings = snapshot_settings().bind_to_scope();1019    assert_cmd_snapshot!(hyperfine_debug()1020        .args([1021            "--style=none",1022            "--runs=1",1023            "--export-markdown=-",1024            "-P",1025            "x",1026            "1",1027            "3",1028            "--command-name",1029            "case-{x}",1030            "sleep {x}",1031        ]), @"1032    success: true1033    exit_code: 01034    ----- stdout -----10351036    | Command | Mean Wall Time [s] | Change | Factor |1037    |:---|---:|---:|:---|1038    | `case-1` | 1.000 |  |  |1039    | `case-2` | 2.000 | +100.0% | (2.0x slower) |1040    | `case-3` | 3.000 | +200.0% | (3.0x slower) |104110421043    ----- stderr -----1044    ");1045}10461047#[test]1048fn intermediate_results_are_not_exported_to_stdout() {1049    let _settings = snapshot_settings().bind_to_scope();1050    assert_cmd_snapshot!(hyperfine_debug()1051        .arg("--style=none") // To only see the Markdown export on stdout1052        .arg("--export-markdown")1053        .arg("-")1054        .arg("sleep 1")1055        .arg("sleep 2"), @"1056    success: true1057    exit_code: 01058    ----- stdout -----10591060    | Command | Mean Wall Time [s] | Change | Factor |1061    |:---|---:|---:|:---|1062    | `sleep 1` | 1.000 ± 0.000 |  |  |1063    | `sleep 2` | 2.000 ± 0.000 | +100.0% | (2.0x slower) |106410651066    ----- stderr -----1067    ");1068}10691070#[test]1071#[cfg(unix)]1072fn exports_intermediate_results_to_file() {1073    use tempfile::tempdir;10741075    let tempdir = tempdir().unwrap();1076    let export_path = tempdir.path().join("results.md");10771078    hyperfine()1079        .arg("--runs=1")1080        .arg("--export-markdown")1081        .arg(&export_path)1082        .arg("true")1083        .arg("false")1084        .assert()1085        .failure();10861087    let contents = std::fs::read_to_string(export_path).unwrap();1088    assert!(contents.contains("true"));1089}10901091#[test]1092fn invalid_command_options_preserve_export_files() {1093    use tempfile::tempdir;10941095    for (option, values) in [1096        ("--prepare", ["echo first", "echo second"]),1097        ("--conclude", ["echo first", "echo second"]),1098        ("--output", ["null", "pipe"]),1099    ] {1100        let directory = tempdir().unwrap();1101        let existing_export = directory.path().join("previous.json");1102        let new_export = directory.path().join("new.csv");1103        let previous_results =1104            b"{\"results\":[{\"command\":\"previous benchmark\",\"mean\":1.0}]}\n";1105        std::fs::write(&existing_export, previous_results).unwrap();11061107        hyperfine()1108            .arg("--runs=1")1109            .arg("--export-json")1110            .arg(&existing_export)1111            .arg("--export-csv")1112            .arg(&new_export)1113            .args([option, values[0], option, values[1]])1114            .arg("echo benchmark")1115            .assert()1116            .failure()1117            .stderr(predicate::str::contains(format!(1118                "The '{option}' option has to be provided just once or N times"1119            )));11201121        assert_eq!(1122            std::fs::read(&existing_export).unwrap(),1123            previous_results,1124            "{option} validation must preserve previous results"1125        );1126        assert!(1127            !new_export.exists(),1128            "{} validation must not create export files",1129            option1130        );1131    }1132}11331134#[test]1135fn markdown_export_preserves_backticks_and_pipes_in_command_names() {1136    let _settings = snapshot_settings().bind_to_scope();1137    assert_cmd_snapshot!(hyperfine_debug()1138        .arg("--style=none")1139        .arg("--export-markdown=-")1140        .arg("--command-name=echo `uname` | cat")1141        .arg("sleep 1"), @r"1142    success: true1143    exit_code: 01144    ----- stdout -----11451146    | Command | Mean Wall Time [s] | Change | Factor |1147    |:---|---:|---:|:---|1148    | `` echo `uname` \| cat `` | 1.000 ± 0.000 |  |  |114911501151    ----- stderr -----1152    ");1153}11541155#[test]1156fn unused_parameters_are_shown_in_benchmark_name() {1157    hyperfine()1158        .arg("--runs=2")1159        .arg("--parameter-list")1160        .arg("branch")1161        .arg("master,feature")1162        .arg("echo test")1163        .assert()1164        .success()1165        .stdout(1166            predicate::str::contains("echo test (branch = master)")1167                .and(predicate::str::contains("echo test (branch = feature)")),1168        );1169}11701171#[cfg(windows)]1172#[test]1173fn windows_quote_args() {1174    hyperfine()1175        .arg("--shell=default")1176        .arg("more \"example_input_file.txt\"")1177        .assert()1178        .success();1179}11801181#[cfg(windows)]1182#[test]1183fn windows_quote_before_quote_args() {1184    hyperfine()1185        .arg("--shell=default")1186        .arg("dir \"..\\src\\\" \"..\\tests\\\"")1187        .assert()1188        .success();1189}11901191#[test]1192fn hyperfine_iteration_env_var_in_prepare_and_conclude_commands() {1193    let tempdir = tempfile::tempdir().unwrap();1194    let output_path = tempdir.path().join("iteration output.txt");1195    let iteration = if cfg!(windows) {1196        "%HYPERFINE_ITERATION%"1197    } else {1198        "$HYPERFINE_ITERATION"1199    };1200    let command = |phase| format!(r#"echo {phase}:{iteration} >> "iteration output.txt""#);12011202    hyperfine()1203        .arg("--shell=default")1204        .current_dir(tempdir.path())1205        .arg("--runs=2")1206        .arg("--warmup=1")1207        .arg("--prepare")1208        .arg(command("prepare"))1209        .arg(command("benchmark"))1210        .arg("--conclude")1211        .arg(command("conclude"))1212        .assert()1213        .success();12141215    let contents = std::fs::read_to_string(output_path).unwrap();1216    // cmd.exe's echo includes the space before the redirection operator.1217    let lines: Vec<&str> = contents.lines().map(str::trim_end).collect();1218    assert_eq!(1219        lines,1220        [1221            "prepare:warmup-0",1222            "benchmark:warmup-0",1223            "conclude:warmup-0",1224            "prepare:0",1225            "benchmark:0",1226            "conclude:0",1227            "prepare:1",1228            "benchmark:1",1229            "conclude:1",1230        ]1231    );1232}12331234#[test]1235fn json_export_basic() {1236    let _settings = json_snapshot_settings().bind_to_scope();1237    assert_cmd_snapshot!(hyperfine_debug().args([1238        "--style=none",1239        "--export-json=-",1240        "--runs=2",1241        "--warmup=1",1242        "--command-name=one second",1243        "sleep 1",1244        "--command-name=sleep 2",1245        "sleep 2",1246    ]));1247}12481249#[test]1250fn json_export_single_run() {1251    // Make sure that the standard deviation is set to `null`1252    let _settings = json_snapshot_settings().bind_to_scope();1253    assert_cmd_snapshot!(hyperfine_debug().args([1254        "--style=none",1255        "--export-json=-",1256        "--runs=1",1257        "sleep 1",1258    ]));1259}12601261#[test]1262fn json_export_parameterized_with_reference() {1263    let _settings = json_snapshot_settings().bind_to_scope();1264    assert_cmd_snapshot!(hyperfine_debug().args([1265        "--style=none",1266        "--export-json=-",1267        "--runs=2",1268        "-L",1269        "duration",1270        "1,2",1271        "--command-name=sleep for {duration} seconds",1272        "sleep {duration}",1273    ]));1274}