Skip to content
Myr

Refactor AsciiDocExporter emitting using the MarkupExporter trait

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Philipp Paulweber · committed by David Peter · parent 546f504 · Browse files · 2 files+186 added−215 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+186 added−215 removed

  • other:+186 added−215 removed

2 files+186 added−215 removed

modified:src/export/asciidoc.rs+159 added-205 removed
1use crate::benchmark::benchmark_result::BenchmarkResult;2use crate::benchmark::relative_speed::{self, BenchmarkResultWithRelativeSpeed};3use crate::output::format::format_duration_value;4use crate::util::units::Unit;1use super::markup::Alignment;2use crate::export::markup::MarkupExporter;36use super::Exporter;78use anyhow::{anyhow, Result};94#[derive(Default)]5pub struct AsciidocExporter {}613impl Exporter for AsciidocExporter {14 fn serialize(&self, results: &[BenchmarkResult], unit: Option<Unit>) -> Result<Vec<u8>> {15 let unit = if let Some(unit) = unit {16 // Use the given unit for all entries.17 unit18 } else if let Some(first_result) = results.first() {19 // Use the first BenchmarkResult entry to determine the unit for all entries.20 format_duration_value(first_result.mean, None).121 } else {22 // Default to `Second`.23 Unit::Second24 };7impl MarkupExporter for AsciidocExporter {8 fn table_header(&self, cell_aligmnents: &[Alignment]) -> String {9 format!(10 "[cols=\"{}\"]\n|===",11 cell_aligmnents12 .iter()13 .map(|a| match a {14 Alignment::Left => "<",15 Alignment::Right => ">",16 })17 .collect::<Vec<&str>>()18 .join(",")19 )20 }2126 if let Some(annotated_results) = relative_speed::compute(results) {27 let mut res: Vec<u8> = Vec::new();28 res.append(&mut table_open());29 res.append(&mut table_startend());30 res.append(&mut table_header(unit));31 for result in annotated_results {32 res.push(b'\n');33 res.append(&mut table_row(&result, unit));34 }35 res.append(&mut table_startend());22 fn table_footer(&self, _cell_aligmnents: &[Alignment]) -> String {23 "|===\n".to_string()24 }2537 Ok(res)38 } else {39 Err(anyhow!(40 "Relative speed comparison is not available for Asciidoctor export."41 ))42 }26 fn table_row(&self, cells: &[&str]) -> String {27 format!("\n| {} \n", cells.join(" \n| "))28 }44}2946fn table_open() -> Vec<u8> {47 "[cols=\"<,>,>,>,>\"]\n".bytes().collect()48}30 fn table_divider(&self, _cell_aligmnents: &[Alignment]) -> String {31 "".to_string()32 }3350fn table_startend() -> Vec<u8> {51 "|===\n".bytes().collect()34 fn command(&self, cmd: &str) -> String {35 format!("`{}`", cmd)36 }37}3854fn table_header(unittype: Unit) -> Vec<u8> {55 let unit_short_name = unittype.short_name();56 format!(57 "| Command \n| Mean [{unit}] \n| Min [{unit}] \n| Max [{unit}] \n| Relative \n",58 unit = unit_short_name59 )60 .into_bytes()61}39/// Check Asciidoc-based data row formatting40#[test]41fn test_asciidoc_exporter_table_data() {42 let exporter = AsciidocExporter::default();43 let data = vec!["a", "b", "c"];4463fn table_row(entry: &BenchmarkResultWithRelativeSpeed, unit: Unit) -> Vec<u8> {64 let result = &entry.result;65 let mean_str = format_duration_value(result.mean, Some(unit)).0;66 let stddev_str = if let Some(stddev) = result.stddev {67 format!(" ± {}", format_duration_value(stddev, Some(unit)).0)68 } else {69 "".into()70 };71 let min_str = format_duration_value(result.min, Some(unit)).0;72 let max_str = format_duration_value(result.max, Some(unit)).0;73 let rel_str = format!("{:.2}", entry.relative_speed);74 let rel_stddev_str = if entry.is_fastest {75 "".into()76 } else if let Some(stddev) = entry.relative_speed_stddev {77 format!(" ± {:.2}", stddev)78 } else {79 "".into()80 };45 let actual = exporter.table_row(&data);46 let expect = "\n| a \n| b \n| c \n";4782 format!(83 "| `{command}` \n\84 | {mean}{stddev} \n\85 | {min} \n\86 | {max} \n\87 | {rel}{rel_stddev} \n",88 command = result.command.replace('|', "\\|"),89 mean = mean_str,90 stddev = stddev_str,91 min = min_str,92 max = max_str,93 rel = rel_str,94 rel_stddev = rel_stddev_str95 )96 .into_bytes()48 assert_eq!(expect, actual);49}5099/// Ensure various options for the header generate correct results51/// Check Asciidoc-based table header formatting52#[test]101fn test_asciidoc_header() {102 let conms: Vec<u8> = "| Command \n| Mean [ms] \n| Min [ms] \n| Max [ms] \n| Relative \n"103 .bytes()104 .collect();105 let cons: Vec<u8> = "| Command \n| Mean [s] \n| Min [s] \n| Max [s] \n| Relative \n"106 .bytes()107 .collect();108 let genms = table_header(Unit::MilliSecond);109 let gens = table_header(Unit::Second);53fn test_asciidoc_exporter_table_header() {54 let exporter = AsciidocExporter::default();55 let cells_alignment = [56 Alignment::Left,57 Alignment::Right,58 Alignment::Right,59 Alignment::Right,60 Alignment::Right,61 ];62111 assert_eq!(conms, genms);112 assert_eq!(cons, gens);63 let actual = exporter.table_header(&cells_alignment);64 let expect = "[cols=\"<,>,>,>,>\"]\n|===";6566 assert_eq!(expect, actual);67}68115/// Ensure each table row is generated properly116#[test]117fn test_asciidoc_table_row() {118 use std::collections::BTreeMap;119120 let timing_result = BenchmarkResultWithRelativeSpeed {121 result: &BenchmarkResult {122 command: String::from("sleep 1"),123 mean: 0.10491992406666667,124 stddev: Some(0.00397851689425097),125 median: 0.10491992406666667,126 user: 0.005182013333333333,127 system: 0.0,128 min: 0.1003342584,129 max: 0.10745223440000001,130 times: Some(vec![0.1003342584, 0.10745223440000001, 0.10697327940000001]),131 exit_codes: vec![Some(0), Some(0), Some(0)],132 parameters: BTreeMap::new(),133 },134 relative_speed: 1.000,135 relative_speed_stddev: Option::from(1.03),136 is_fastest: true,137 };138139 let formatted = String::from_utf8(table_row(&timing_result, Unit::MilliSecond)).unwrap();140141 let formatted_expected = "| `sleep 1` \n\142 | 104.9 ± 4.0 \n\143 | 100.3 \n\144 | 107.5 \n\145 | 1.00 \n";146147 assert_eq!(formatted_expected, formatted);148149 let formatted_seconds = String::from_utf8(table_row(&timing_result, Unit::Second)).unwrap();150 let formatted_expected_seconds = "| `sleep 1` \n\151 | 0.105 ± 0.004 \n\152 | 0.100 \n\153 | 0.107 \n\154 | 1.00 \n";155156 assert_eq!(formatted_expected_seconds, formatted_seconds);69/// Test helper function to create unit-based header and horizontal line70/// independently from the markup functionality for Asciidoc.71#[cfg(test)]72fn cfg_test_table_header(unit_short_name: &str) -> String {73 format!(74 "[cols=\"<,>,>,>,>\"]\n|===\n| Command \n| Mean [{unit}] \n| Min [{unit}] \n| Max [{unit}] \n| Relative \n",75 unit = unit_short_name76 )77}78159/// Ensure commands get properly escaped160#[test]161fn test_asciidoc_table_row_command_escape() {162 use std::collections::BTreeMap;163 let benchmark_result = BenchmarkResultWithRelativeSpeed {164 result: &BenchmarkResult {165 command: String::from("sleep 1|"),166 mean: 0.10491992406666667,167 stddev: Some(0.00397851689425097),168 median: 0.10491992406666667,169 user: 0.005182013333333333,170 system: 0.0,171 min: 0.1003342584,172 max: 0.10745223440000001,173 times: Some(vec![0.1003342584, 0.10745223440000001, 0.10697327940000001]),174 exit_codes: vec![Some(0), Some(0), Some(0)],175 parameters: BTreeMap::new(),176 },177 relative_speed: 1.000,178 relative_speed_stddev: Option::from(1.03),179 is_fastest: true,180 };181 let expected = String::from_utf8(182 format!(183 "| `sleep 1\\|` \n\184 | {} ± {} \n\185 | {} \n\186 | {} \n\187 | {:.2} \n",188 Unit::Second.format(benchmark_result.result.mean),189 Unit::Second.format(benchmark_result.result.stddev.unwrap()),190 Unit::Second.format(benchmark_result.result.min),191 Unit::Second.format(benchmark_result.result.max),192 benchmark_result.relative_speed193 )194 .into_bytes(),195 );196 let generated_seconds = String::from_utf8(table_row(&benchmark_result, Unit::Second));79#[cfg(test)]80use crate::util::units::Unit;81198 assert_eq!(expected, generated_seconds);199}82#[cfg(test)]83use crate::export::BenchmarkResult;8485#[cfg(test)]86use crate::export::Exporter;8788/// Integration test89#[test]203fn test_asciidoc() {90fn test_asciidoc_format_s() {91 use std::collections::BTreeMap;92 let exporter = AsciidocExporter::default();206 // NOTE: results are fabricated, unlike above9394 let results = vec![95 BenchmarkResult {96 command: String::from("FOO=1 BAR=2 command | 1"),97 mean: 1.0,
30 unmodified lines
128 params129 },130 },131 ];245 // NOTE: only testing with s, s/ms is tested elsewhere246 let expected: String = String::from(247 "[cols=\"<,>,>,>,>\"]\n\248 |===\n\249 | Command \n\250 | Mean [s] \n\251 | Min [s] \n\252 | Max [s] \n\253 | Relative \n\254 \n\255 | `FOO=1 BAR=2 command \\| 1` \n\256 | 1.000 ± 2.000 \n\257 | 5.000 \n\258 | 6.000 \n\259 | 1.00 \n\260 \n\261 | `FOO=1 BAR=7 command \\| 2` \n\262 | 11.000 ± 12.000 \n\263 | 15.000 \n\264 | 16.000 \n\265 | 11.00 ± 25.06 \n\266 |===\n\267 ",268 );269 let given =132133 let actual =134 String::from_utf8(exporter.serialize(&results, Some(Unit::Second)).unwrap()).unwrap();135 let expect = format!(136 "{}137| `FOO=1 BAR=2 command \\| 1` 138| 1.000 ± 2.000 139| 5.000 140| 6.000 141| 1.00 142143| `FOO=1 BAR=7 command \\| 2` 144| 11.000 ± 12.000 145| 15.000 146| 16.000 147| 11.00 ± 25.06 148|===149",150 cfg_test_table_header("s")151 );152272 assert_eq!(expected, given);153 assert_eq!(expect, actual);154}155156/// This test demonstrates that the given unit (ms) is used to set157/// the units for all entries.158#[test]159fn test_asciidoc_format_ms() {160 use std::collections::BTreeMap;161 let exporter = AsciidocExporter::default();162163 let results = vec![164 BenchmarkResult {165 command: String::from("FOO=1 BAR=7 command | 2"),166 mean: 0.011,167 stddev: Some(0.012),168 median: 0.011,169 user: 0.013,170 system: 0.014,171 min: 0.015,172 max: 0.016,173 times: Some(vec![0.017, 0.018, 0.019]),174 exit_codes: vec![Some(0), Some(0), Some(0)],175 parameters: {176 let mut params = BTreeMap::new();177 params.insert("foo".into(), "1".into());178 params.insert("bar".into(), "7".into());179 params180 },181 },182 BenchmarkResult {183 command: String::from("FOO=1 BAR=2 command | 1"),184 mean: 1.0,185 stddev: Some(2.0),186 median: 1.0,187 user: 3.0,188 system: 4.0,189 min: 5.0,190 max: 6.0,191 times: Some(vec![7.0, 8.0, 9.0]),192 exit_codes: vec![Some(0), Some(0), Some(0)],193 parameters: {194 let mut params = BTreeMap::new();195 params.insert("foo".into(), "1".into());196 params.insert("bar".into(), "2".into());197 params198 },199 },200 ];201202 let actual = String::from_utf8(203 exporter204 .serialize(&results, Some(Unit::MilliSecond))205 .unwrap(),206 )207 .unwrap();208 let expect = format!(209 "{}210| `FOO=1 BAR=7 command \\| 2` 211| 11.0 ± 12.0 212| 15.0 213| 16.0 214| 1.00 215216| `FOO=1 BAR=2 command \\| 1` 217| 1000.0 ± 2000.0 218| 5000.0 219| 6000.0 220| 90.91 ± 207.11 221|===222",223 cfg_test_table_header("ms")224 );225226 assert_eq!(expect, actual);227}
modified:src/export/markup.rs+27 added-10 removed
13 unmodified lines
14 fn table_results(&self, entries: &[BenchmarkResultWithRelativeSpeed], unit: Unit) -> String {15 // prepare table header strings16 let notation = format!("[{}]", unit.short_name());1718 // emit header19 let mut table = self.table_row(&[18 // prepare table cells alignment19 let cells_alignment = [20 Alignment::Left,21 Alignment::Right,22 Alignment::Right,23 Alignment::Right,24 Alignment::Right,25 ];2627 // emit table header format28 let mut table = self.table_header(&cells_alignment);2930 // emit table header data31 table.push_str(&self.table_row(&[32 "Command",33 &format!("Mean {}", notation),34 &format!("Min {}", notation),35 &format!("Max {}", notation),36 "Relative",25 ]);37 ]));3839 // emit horizontal line28 table.push_str(&self.table_divider(&[29 Alignment::Left,30 Alignment::Right,31 Alignment::Right,32 Alignment::Right,33 Alignment::Right,34 ]));40 table.push_str(&self.table_divider(&cells_alignment));4142 for entry in entries {43 let measurement = &entry.result;44 // prepare data row strings
24 unmodified lines
69 &format!("{}{}", rel_str, rel_stddev_str),70 ]))71 }7273 // emit table footer format74 table.push_str(&self.table_footer(&cells_alignment));7576 table77 }7879 fn table_row(&self, cells: &[&str]) -> String;8081 fn table_divider(&self, cell_aligmnents: &[Alignment]) -> String;8283 fn table_header(&self, _cell_aligmnents: &[Alignment]) -> String {84 "".to_string()85 }8687 fn table_footer(&self, _cell_aligmnents: &[Alignment]) -> String {88 "".to_string()89 }9091 fn command(&self, size: &str) -> String;92}9394fn determine_unit_from_results(results: &[BenchmarkResult]) -> Unit {
195 unmodified lines