Skip to content
Myr

command.rs

This file

Path

src/command.rs

688 lines · 22.1 KiB · Rust

Last changed by

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

History of this file

Take it

The walk stopped after 200 commits: lines older than 0f91d0c point at it.

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 1–16why, one step back
1use std::collections::BTreeMap;
2use std::fmt;3use std::str::FromStr;45use crate::parameter::tokenize::tokenize;6use crate::parameter::ParameterValue;7use crate::{8 error::{OptionsError, ParameterScanError},9 parameter::{10 range_step::{Numeric, RangeStep},11 ParameterNameAndValue,12 },13};1415use clap::{parser::ValuesRef, ArgMatches};16

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

line 17why, one step back
17use anyhow::{bail, ensure, Context, Result};

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 18–19why, one step back
18use rust_decimal::Decimal;
19

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

lines 20–21why, one step back
20type Environment = Vec<(String, String)>;
21

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 22–32why, one step back
22/// A command that should be benchmarked.
23#[derive(Debug, Clone, PartialEq, Eq)]24pub struct Command<'a> {25 /// The command name (without parameter substitution)26 name: Option<&'a str>,2728 /// The command that should be executed (without parameter substitution)29 expression: &'a str,3031 /// Zero or more parameter values.32 parameters: Vec<ParameterNameAndValue<'a>>,

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

lines 33–35why, one step back
33
34 /// Environment overrides, before parameter substitution.35 environment: Environment,

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 36–43why, one step back
36}
3738impl<'a> Command<'a> {39 pub fn new(name: Option<&'a str>, expression: &'a str) -> Command<'a> {40 Command {41 name,42 expression,43 parameters: Vec::new(),

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

line 44why, one step back
44 environment: Vec::new(),

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 45–56why, one step back
45 }
46 }4748 pub fn new_parametrized(49 name: Option<&'a str>,50 expression: &'a str,51 parameters: impl IntoIterator<Item = ParameterNameAndValue<'a>>,52 ) -> Command<'a> {53 Command {54 name,55 expression,56 parameters: parameters.into_iter().collect(),

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

line 57why, one step back
57 environment: Vec::new(),

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 58–61why, one step back
58 }
59 }6061 pub fn get_name(&self) -> String {

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

lines 62–76why, one step back
62 match self.name {
63 Some(name) => self.replace_parameters_in(name),64 None => {65 let environment = self66 .get_environment()67 .map(|(name, value)| format!("{name}={}", shell_words::quote(&value)))68 .collect::<Vec<_>>()69 .join(" ");70 if environment.is_empty() {71 self.get_command_line()72 } else {73 format!("{environment} {}", self.get_command_line())74 }75 }76 }

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 77–79why, one step back
77 }
7879 pub fn get_name_with_unused_parameters(&self) -> String {

refactor: Optimize code based on cargo clippy suggestionsone230sixbefore adoptionc092135

lines 80–82why, one step back
80 let parameters = self
81 .get_unused_parameters()82 .fold(String::new(), |output, (parameter, value)| {

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 83why, one step back
83 output + &format!("{parameter} = {value}, ")

refactor: Optimize code based on cargo clippy suggestionsone230sixbefore adoptionc092135

line 84why, one step back
84 });

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 85–88why, one step back
85 let parameters = parameters.trim_end_matches(", ");
86 let parameters = if parameters.is_empty() {87 "".into()88 } else {

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 89why, one step back
89 format!(" ({parameters})")

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 90–101why, one step back
90 };
9192 format!("{}{}", self.get_name(), parameters)93 }9495 pub fn get_command_line(&self) -> String {96 self.replace_parameters_in(self.expression)97 }9899 pub fn get_command(&self) -> Result<std::process::Command> {100 let command_line = self.get_command_line();101 let mut tokens = shell_words::split(&command_line)

style: simplify string interpolationHamir Mahalbefore adoptionef12632

line 102why, one step back
102 .with_context(|| format!("Failed to parse command '{command_line}'"))?

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 103–107why, one step back
103 .into_iter();
104105 if let Some(program_name) = tokens.next() {106 let mut command_builder = std::process::Command::new(program_name);107 command_builder.args(tokens);

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

line 108why, one step back
108 command_builder.envs(self.get_environment());

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 109–118why, one step back
109 Ok(command_builder)
110 } else {111 bail!("Can not execute empty command")112 }113 }114115 pub fn get_parameters(&self) -> &[(&'a str, ParameterValue)] {116 &self.parameters117 }118

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

lines 119–129why, one step back
119 pub fn get_environment(&self) -> impl Iterator<Item = (&str, String)> {
120 self.environment121 .iter()122 .map(move |(name, value)| (name.as_str(), self.replace_parameters_in(value)))123 }124125 pub fn with_environment_from(mut self, command: &Command<'_>) -> Self {126 self.environment = command.environment.clone();127 self128 }129

Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9

line 130why, one step back
130 pub fn is_parameter_unused(&self, parameter: &str) -> bool {

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

lines 131–136why, one step back
131 let placeholder = format!("{{{parameter}}}");
132 !self.expression.contains(&placeholder)133 && !self134 .environment135 .iter()136 .any(|(_, value)| value.contains(&placeholder))

Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9

lines 137–138why, one step back
137 }
138

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 139–141why, one step back
139 pub fn get_unused_parameters(&self) -> impl Iterator<Item = &(&'a str, ParameterValue)> {
140 self.parameters141 .iter()

Merge pull request #963 from sharkdp/codex/measurement-helpersDavid Peterbefore adoptionf16b6b9

line 142why, one step back
142 .filter(move |(parameter, _)| self.is_parameter_unused(parameter))

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 143–148why, one step back
143 }
144145 fn replace_parameters_in(&self, original: &str) -> String {146 let mut result = String::new();147 let mut replacements = BTreeMap::<String, String>::new();148 for (param_name, param_value) in &self.parameters {

fix: formatting in `src/command.rs`Hamir Mahalbefore adoption981db9d

line 149why, one step back
149 replacements.insert(format!("{{{param_name}}}"), param_value.to_string());

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 150–174why, one step back
150 }
151 let mut remaining = original;152 // Manually replace consecutive occurrences to avoid double-replacing: e.g.,153 //154 // hyperfine -L foo 'a,{bar}' -L bar 'baz,quux' 'echo {foo} {bar}'155 //156 // should not ever run 'echo baz baz'. See `test_get_command_line_nonoverlapping`.157 'outer: while let Some(head) = remaining.chars().next() {158 for (k, v) in &replacements {159 if remaining.starts_with(k.as_str()) {160 result.push_str(v);161 remaining = &remaining[k.len()..];162 continue 'outer;163 }164 }165 result.push(head);166 remaining = &remaining[head.len_utf8()..];167 }168 result169 }170}171172/// A collection of commands that should be benchmarked173pub struct Commands<'a>(Vec<Command<'a>>);174

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

lines 175–204why, one step back
175fn parse_environment(value: &str) -> Result<Environment> {
176 let mut environment = Environment::new();177 for assignment in shell_words::split(value).context("Failed to parse '--env' assignments")? {178 let (name, value) = assignment.split_once('=').with_context(|| {179 format!(180 "Invalid value '{assignment}' for '--env': expected an assignment like NAME=value or NAME=\"quoted value\"."181 )182 })?;183 ensure!(184 !name.is_empty()185 && name.bytes().enumerate().all(|(index, byte)| {186 byte == b'_'187 || byte.is_ascii_alphabetic()188 || (index > 0 && byte.is_ascii_digit())189 }),190 "Invalid environment variable name '{name}' in '--env'"191 );192 // Keep only the last assignment, including case variants on Windows.193 environment.retain(|(key, _)| {194 if cfg!(windows) {195 !key.eq_ignore_ascii_case(name)196 } else {197 key != name198 }199 });200 environment.push((name.to_owned(), value.to_owned()));201 }202 Ok(environment)203}204

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

line 205why, one step back
205impl<'a> Commands<'a> {

fix build warning proposalDavid Carlierbefore adoptionf096c26

line 206why, one step back
206 pub fn from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands<'a>> {

Add --env for benchmark environment overridesDavid Peterbefore adoption6dddb02

lines 207–226why, one step back
207 let mut commands = Self::build_from_cli_arguments(matches)?;
208 if let Some(values) = matches.get_many::<String>("env") {209 let environments = values210 .map(|value| parse_environment(value))211 .collect::<Result<Vec<_>>>()?;212 let num_commands = commands.num_commands();213 ensure!(214 environments.len() == 1 || environments.len() == num_commands,215 "The '--env' option has to be provided just once or N times, where N={num_commands} is the \216 number of benchmark commands."217 );218 for (index, command) in commands.0.iter_mut().enumerate() {219 command.environment =220 environments[if environments.len() == 1 { 0 } else { index }].clone();221 }222 }223 Ok(commands)224 }225226 fn build_from_cli_arguments(matches: &'a ArgMatches) -> Result<Commands<'a>> {

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 227–249why, one step back
227 let command_names = matches.get_many::<String>("command-name");
228 let command_strings = matches229 .get_many::<String>("command")230 .unwrap_or_default()231 .map(|v| v.as_str())232 .collect::<Vec<_>>();233234 if let Some(args) = matches.get_many::<String>("parameter-scan") {235 let step_size = matches236 .get_one::<String>("parameter-step-size")237 .map(|s| s.as_str());238 Ok(Self(Self::get_parameter_scan_commands(239 command_names,240 command_strings,241 args,242 step_size,243 )?))244 } else if let Some(args) = matches.get_many::<String>("parameter-list") {245 let command_names = command_names.map_or(vec![], |names| {246 names.map(|v| v.as_str()).collect::<Vec<_>>()247 });248 let args: Vec<_> = args.map(|v| v.as_str()).collect::<Vec<_>>();249 let param_names_and_values: Vec<(&str, Vec<String>)> = args

Dependency and MSRV update (#934)David Peterbefore adoption4d073e0

lines 250–252why, one step back
250 .as_chunks::<2>()
251 .0252 .iter()

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 253–262why, one step back
253 .map(|pair| {
254 let name = pair[0];255 let list_str = pair[1];256 (name, tokenize(list_str))257 })258 .collect();259 {260 let duplicates =261 Self::find_duplicates(param_names_and_values.iter().map(|(name, _)| *name));262 if !duplicates.is_empty() {

Dependency and MSRV update (#934)David Peterbefore adoption4d073e0

line 263why, one step back
263 bail!("Duplicate parameter names: {}", duplicates.join(", "));

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 264–344why, one step back
264 }
265 }266267 let dimensions: Vec<usize> = std::iter::once(command_strings.len())268 .chain(269 param_names_and_values270 .iter()271 .map(|(_, values)| values.len()),272 )273 .collect();274 let param_space_size = dimensions.iter().product();275 if param_space_size == 0 {276 return Ok(Self(Vec::new()));277 }278279 // `--command-name` should appear exactly once or exactly B times,280 // where B is the total number of benchmarks.281 let command_name_count = command_names.len();282 if command_name_count > 1 && command_name_count != param_space_size {283 return Err(OptionsError::UnexpectedCommandNameCount(284 command_name_count,285 param_space_size,286 )287 .into());288 }289290 let mut i = 0;291 let mut commands = Vec::with_capacity(param_space_size);292 let mut index = vec![0usize; dimensions.len()];293 'outer: loop {294 let name = command_names295 .get(i)296 .or_else(|| command_names.first())297 .copied();298 i += 1;299300 let (command_index, params_indices) = index.split_first().unwrap();301 let parameters: Vec<_> = param_names_and_values302 .iter()303 .zip(params_indices)304 .map(|((name, values), i)| (*name, ParameterValue::Text(values[*i].clone())))305 .collect();306 commands.push(Command::new_parametrized(307 name,308 command_strings[*command_index],309 parameters,310 ));311312 // Increment index, exiting loop on overflow.313 for (i, n) in index.iter_mut().zip(dimensions.iter()) {314 *i += 1;315 if *i < *n {316 continue 'outer;317 } else {318 *i = 0;319 }320 }321 break 'outer;322 }323324 Ok(Self(commands))325 } else {326 let command_names = command_names.map_or(vec![], |names| {327 names.map(|v| v.as_str()).collect::<Vec<_>>()328 });329 if command_names.len() > command_strings.len() {330 return Err(OptionsError::TooManyCommandNames(command_strings.len()).into());331 }332333 let mut commands = Vec::with_capacity(command_strings.len());334 for (i, s) in command_strings.iter().enumerate() {335 commands.push(Command::new(command_names.get(i).copied(), s));336 }337 Ok(Self(commands))338 }339 }340341 pub fn iter(&self) -> impl Iterator<Item = &Command<'a>> {342 self.0.iter()343 }344

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

lines 345–346why, one step back
345 pub fn num_commands(&self) -> usize {
346 self.0.len()

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 347–388why, one step back
347 }
348349 /// Finds all the strings that appear multiple times in the input iterator, returning them in350 /// sorted order. If no string appears more than once, the result is an empty vector.351 fn find_duplicates<'b, I: IntoIterator<Item = &'b str>>(i: I) -> Vec<&'b str> {352 let mut counts = BTreeMap::<&'b str, usize>::new();353 for s in i {354 *counts.entry(s).or_default() += 1;355 }356 counts357 .into_iter()358 .filter_map(|(k, n)| if n > 1 { Some(k) } else { None })359 .collect()360 }361362 fn build_parameter_scan_commands<'b, T: Numeric>(363 param_name: &'b str,364 param_min: T,365 param_max: T,366 step: T,367 command_names: Vec<&'b str>,368 command_strings: Vec<&'b str>,369 ) -> Result<Vec<Command<'b>>, ParameterScanError> {370 let param_range = RangeStep::new(param_min, param_max, step)?;371 let command_name_count = command_names.len();372373 let mut i = 0;374 let mut commands = vec![];375 for value in param_range {376 for cmd in &command_strings {377 let name = command_names378 .get(i)379 .or_else(|| command_names.first())380 .copied();381 commands.push(Command::new_parametrized(382 name,383 cmd,384 vec![(param_name, ParameterValue::Numeric(value.into()))],385 ));386 i += 1;387 }388 }

Fixed bug on naming individual commands with parameter scanTeodoro Freundbefore adoption835fc43

lines 389–399why, one step back
389
390 // `--command-name` should appear exactly once or exactly B times,391 // where B is the total number of benchmarks.392 let command_count = commands.len();393 if command_name_count > 1 && command_name_count != command_count {394 return Err(ParameterScanError::UnexpectedCommandNameCount(395 command_name_count,396 command_count,397 ));398 }399

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 400–477why, one step back
400 Ok(commands)
401 }402403 fn get_parameter_scan_commands<'b>(404 command_names: Option<ValuesRef<'b, String>>,405 command_strings: Vec<&'b str>,406 mut vals: ValuesRef<'b, String>,407 step: Option<&str>,408 ) -> Result<Vec<Command<'b>>, ParameterScanError> {409 let command_names = command_names.map_or(vec![], |names| {410 names.map(|v| v.as_str()).collect::<Vec<_>>()411 });412 let param_name = vals.next().unwrap().as_str();413 let param_min = vals.next().unwrap().as_str();414 let param_max = vals.next().unwrap().as_str();415416 // attempt to parse as integers417 if let (Ok(param_min), Ok(param_max), Ok(step)) = (418 param_min.parse::<i32>(),419 param_max.parse::<i32>(),420 step.unwrap_or("1").parse::<i32>(),421 ) {422 return Self::build_parameter_scan_commands(423 param_name,424 param_min,425 param_max,426 step,427 command_names,428 command_strings,429 );430 }431432 // try parsing them as decimals433 let param_min = Decimal::from_str(param_min)?;434 let param_max = Decimal::from_str(param_max)?;435436 if step.is_none() {437 return Err(ParameterScanError::StepRequired);438 }439440 let step = Decimal::from_str(step.unwrap())?;441 Self::build_parameter_scan_commands(442 param_name,443 param_min,444 param_max,445 step,446 command_names,447 command_strings,448 )449 }450}451452#[test]453fn test_get_command_line_nonoverlapping() {454 let cmd = Command::new_parametrized(455 None,456 "echo {foo} {bar}",457 vec![458 ("foo", ParameterValue::Text("{bar} baz".into())),459 ("bar", ParameterValue::Text("quux".into())),460 ],461 );462 assert_eq!(cmd.get_command_line(), "echo {bar} baz quux");463}464465#[test]466fn test_get_parameterized_command_name() {467 let cmd = Command::new_parametrized(468 Some("name-{bar}-{foo}"),469 "echo {foo} {bar}",470 vec![471 ("foo", ParameterValue::Text("baz".into())),472 ("bar", ParameterValue::Text("quux".into())),473 ],474 );475 assert_eq!(cmd.get_name(), "name-quux-baz");476}477

apply clippy advices on executor/commands lifetimes.David Carlierbefore adoption2899deb

line 478why, one step back
478impl fmt::Display for Command<'_> {

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 479–563why, one step back
479 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
480 write!(f, "{}", self.get_command_line())481 }482}483484#[test]485fn test_build_commands_cross_product() {486 use crate::cli::get_cli_arguments;487488 let matches = get_cli_arguments(vec![489 "hyperfine",490 "-L",491 "par1",492 "a,b",493 "-L",494 "par2",495 "z,y",496 "echo {par1} {par2}",497 "printf '%s\n' {par1} {par2}",498 ]);499 let result = Commands::from_cli_arguments(&matches).unwrap().0;500501 // Iteration order: command list first, then parameters in listed order (here, "par1" before502 // "par2", which is distinct from their sorted order), with parameter values in listed order.503 let pv = |s: &str| ParameterValue::Text(s.to_string());504 let cmd = |cmd: usize, par1: &str, par2: &str| {505 let expression = ["echo {par1} {par2}", "printf '%s\n' {par1} {par2}"][cmd];506 let params = vec![("par1", pv(par1)), ("par2", pv(par2))];507 Command::new_parametrized(None, expression, params)508 };509 let expected = vec![510 cmd(0, "a", "z"),511 cmd(1, "a", "z"),512 cmd(0, "b", "z"),513 cmd(1, "b", "z"),514 cmd(0, "a", "y"),515 cmd(1, "a", "y"),516 cmd(0, "b", "y"),517 cmd(1, "b", "y"),518 ];519 assert_eq!(result, expected);520}521522#[test]523fn test_build_parameter_list_commands() {524 use crate::cli::get_cli_arguments;525526 let matches = get_cli_arguments(vec![527 "hyperfine",528 "echo {foo}",529 "--parameter-list",530 "foo",531 "1,2",532 "--command-name",533 "name-{foo}",534 ]);535 let commands = Commands::from_cli_arguments(&matches).unwrap().0;536 assert_eq!(commands.len(), 2);537 assert_eq!(commands[0].get_name(), "name-1");538 assert_eq!(commands[1].get_name(), "name-2");539 assert_eq!(commands[0].get_command_line(), "echo 1");540 assert_eq!(commands[1].get_command_line(), "echo 2");541}542543#[test]544fn test_build_parameter_scan_commands() {545 use crate::cli::get_cli_arguments;546 let matches = get_cli_arguments(vec![547 "hyperfine",548 "echo {val}",549 "--parameter-scan",550 "val",551 "1",552 "2",553 "--parameter-step-size",554 "1",555 "--command-name",556 "name-{val}",557 ]);558 let commands = Commands::from_cli_arguments(&matches).unwrap().0;559 assert_eq!(commands.len(), 2);560 assert_eq!(commands[0].get_name(), "name-1");561 assert_eq!(commands[1].get_name(), "name-2");562 assert_eq!(commands[0].get_command_line(), "echo 1");563 assert_eq!(commands[1].get_command_line(), "echo 2");

Fixed bug on naming individual commands with parameter scanTeodoro Freundbefore adoption835fc43

lines 564–597why, one step back
564}
565566#[test]567fn test_build_parameter_scan_commands_named() {568 use crate::cli::get_cli_arguments;569 let matches = get_cli_arguments(vec![570 "hyperfine",571 "echo {val}",572 "sleep {val}",573 "--parameter-scan",574 "val",575 "1",576 "2",577 "--parameter-step-size",578 "1",579 "--command-name",580 "echo-1",581 "--command-name",582 "sleep-1",583 "--command-name",584 "echo-2",585 "--command-name",586 "sleep-2",587 ]);588 let commands = Commands::from_cli_arguments(&matches).unwrap().0;589 assert_eq!(commands.len(), 4);590 assert_eq!(commands[0].get_name(), "echo-1");591 assert_eq!(commands[0].get_command_line(), "echo 1");592 assert_eq!(commands[1].get_name(), "sleep-1");593 assert_eq!(commands[1].get_command_line(), "sleep 1");594 assert_eq!(commands[2].get_name(), "echo-2");595 assert_eq!(commands[2].get_command_line(), "echo 2");596 assert_eq!(commands[3].get_name(), "sleep-2");597 assert_eq!(commands[3].get_command_line(), "sleep 2");

Bump serde from 1.0.174 to 1.0.179dependabot[bot]before adoption0f91d0c

lines 598–688why, one step back
598}
599600#[test]601fn test_parameter_scan_commands_int() {602 let commands = Commands::build_parameter_scan_commands(603 "val",604 1i32,605 7i32,606 3i32,607 vec![],608 vec!["echo {val}"],609 )610 .unwrap();611 assert_eq!(commands.len(), 3);612 assert_eq!(commands[2].get_name(), "echo 7");613 assert_eq!(commands[2].get_command_line(), "echo 7");614}615616#[test]617fn test_parameter_scan_commands_decimal() {618 let param_min = Decimal::from_str("0").unwrap();619 let param_max = Decimal::from_str("1").unwrap();620 let step = Decimal::from_str("0.33").unwrap();621622 let commands = Commands::build_parameter_scan_commands(623 "val",624 param_min,625 param_max,626 step,627 vec![],628 vec!["echo {val}"],629 )630 .unwrap();631 assert_eq!(commands.len(), 4);632 assert_eq!(commands[3].get_name(), "echo 0.99");633 assert_eq!(commands[3].get_command_line(), "echo 0.99");634}635636#[test]637fn test_parameter_scan_commands_names() {638 let commands = Commands::build_parameter_scan_commands(639 "val",640 1i32,641 3i32,642 1i32,643 vec!["name-{val}"],644 vec!["echo {val}"],645 )646 .unwrap();647 assert_eq!(commands.len(), 3);648 let command_names = commands649 .iter()650 .map(|c| c.get_name())651 .collect::<Vec<String>>();652 assert_eq!(command_names, vec!["name-1", "name-2", "name-3"]);653}654655#[test]656fn test_get_specified_command_names() {657 let commands = Commands::build_parameter_scan_commands(658 "val",659 1i32,660 3i32,661 1i32,662 vec!["name-a", "name-b", "name-c"],663 vec!["echo {val}"],664 )665 .unwrap();666 assert_eq!(commands.len(), 3);667 let command_names = commands668 .iter()669 .map(|c| c.get_name())670 .collect::<Vec<String>>();671 assert_eq!(command_names, vec!["name-a", "name-b", "name-c"]);672}673674#[test]675fn test_different_command_name_count_with_parameters() {676 let result = Commands::build_parameter_scan_commands(677 "val",678 1i32,679 3i32,680 1i32,681 vec!["name-1", "name-2"],682 vec!["echo {val}"],683 );684 assert!(matches!(685 result.unwrap_err(),686 ParameterScanError::UnexpectedCommandNameCount(2, 3)687 ));688}