Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Improve HTML export #1381

Merged
merged 1 commit into from
Mar 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
85 changes: 85 additions & 0 deletions packages/hurl/src/report/html/file.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
/*
* Hurl (https://hurl.dev)
* Copyright (C) 2023 Orange
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
use std::io::Write;
use std::path::Path;

use hurl_core::parser;

use crate::report::html::Testcase;
use crate::report::Error;

impl Testcase {
/// Exports a [`Testcase`] to HTML.
///
/// For the moment, it's just an export of this HTML file, with syntax colored.
pub fn write_html(&self, content: &str, dir_path: &Path) -> Result<(), Error> {
let output_file = dir_path.join("store").join(format!("{}.html", self.id));

let parent = output_file.parent().expect("a parent");
std::fs::create_dir_all(parent).unwrap();
let mut file = match std::fs::File::create(&output_file) {
Err(why) => {
return Err(Error {
message: format!("Issue writing to {}: {:?}", output_file.display(), why),
});
}
Ok(file) => file,
};
let hurl_file = parser::parse_hurl_file(content).unwrap();
let file_div = hurl_core::format::format_html(&hurl_file, false);
let lines_div = lines(content);
let file_css = include_str!("resources/file.css");
let status = if self.success {
"<span class=\"success\">Success</span>"
} else {
"<span class=\"failure\">Failure</span>"
};
let hurl_css = hurl_core::format::hurl_css();
let href = format!("{}.html", self.id);
let html = format!(
include_str!("resources/file.html"),
file_css = file_css,
hurl_css = hurl_css,
lines_div = lines_div,
file_div = file_div,
filename = self.filename,
status = status,
href = href,
duration = self.time_in_ms
);
if let Err(why) = file.write_all(html.as_bytes()) {
return Err(Error {
message: format!("Issue writing to {}: {:?}", output_file.display(), why),
});
}
Ok(())
}
}

fn lines(content: &str) -> String {
let mut lines =
content
.lines()
.enumerate()
.fold("<pre><code>".to_string(), |acc, (count, _)| -> String {
let line = count + 1;
acc + format!("<a id=\"l{line}\" href=\"#l{line}\">{line}</a>\n").as_str()
});
lines.push_str("</pre></code>");
lines
}
227 changes: 3 additions & 224 deletions packages/hurl/src/report/html/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,13 @@

//! HTML report

mod file;
mod report;
mod testcase;

use std::io::Write;
use std::path::Path;

use chrono::{DateTime, Local};
pub use report::write_report;
pub use testcase::Testcase;

use crate::report::Error;

/// The test result to be displayed in an HTML page
#[derive(Clone, Debug, PartialEq, Eq)]
struct HTMLResult {
Expand All @@ -50,221 +47,3 @@ impl HTMLResult {
}
}
}

/// Creates and HTML report for this list of [`Testcase`] at `dir_path`/index.html.
///
/// If the report already exists, results are merged.
pub fn write_report(dir_path: &Path, testcases: &[Testcase]) -> Result<(), Error> {
let index_path = dir_path.join("index.html");
let mut results = parse_html(&index_path)?;
for testcase in testcases.iter() {
let html_result = HTMLResult::from(testcase);
results.push(html_result);
}
let now: DateTime<Local> = Local::now();
let s = create_html_index(&now.to_rfc2822(), &results);

let file_path = index_path;
let mut file = match std::fs::File::create(&file_path) {
Err(why) => {
return Err(Error {
message: format!("Issue writing to {}: {:?}", file_path.display(), why),
});
}
Ok(file) => file,
};
if let Err(why) = file.write_all(s.as_bytes()) {
return Err(Error {
message: format!("Issue writing to {}: {:?}", file_path.display(), why),
});
}

let file_path = dir_path.join("report.css");
let mut file = match std::fs::File::create(&file_path) {
Err(why) => {
return Err(Error {
message: format!("Issue writing to {}: {:?}", file_path.display(), why),
});
}
Ok(file) => file,
};
if let Err(why) = file.write_all(include_bytes!("../report.css")) {
return Err(Error {
message: format!("Issue writing to {}: {:?}", file_path.display(), why),
});
}
Ok(())
}

fn parse_html(path: &Path) -> Result<Vec<HTMLResult>, Error> {
if path.exists() {
let s = match std::fs::read_to_string(path) {
Ok(s) => s,
Err(why) => {
return Err(Error {
message: format!("Issue reading {} to string to {:?}", path.display(), why),
});
}
};
Ok(parse_html_report(&s))
} else {
Ok(vec![])
}
}

fn parse_html_report(html: &str) -> Vec<HTMLResult> {
let re = regex::Regex::new(
r#"(?x)
data-duration="(?P<time_in_ms>\d+)"
\s+
data-status="(?P<status>[a-z]+)"
\s+
data-filename="(?P<filename>[A-Za-z0-9_./-]+)"
\s+
data-id="(?P<id>[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})"
"#,
)
.unwrap();
re.captures_iter(html)
.map(|cap| {
let filename = cap["filename"].to_string();
let id = cap["id"].to_string();
let time_in_ms = cap["time_in_ms"].to_string().parse().unwrap();
let success = &cap["status"] == "success";
HTMLResult {
filename,
id,
time_in_ms,
success,
}
})
.collect::<Vec<HTMLResult>>()
}

fn percentage(count: usize, total: usize) -> String {
format!("{:.1}%", (count as f32 * 100.0) / total as f32)
}

fn create_html_index(now: &str, hurl_results: &[HTMLResult]) -> String {
let count_total = hurl_results.len();
let count_failure = hurl_results.iter().filter(|result| !result.success).count();
let count_success = hurl_results.iter().filter(|result| result.success).count();
let percentage_success = percentage(count_success, count_total);
let percentage_failure = percentage(count_failure, count_total);

let rows = hurl_results
.iter()
.map(create_html_table_row)
.collect::<Vec<String>>()
.join("");

format!(
r#"<!DOCTYPE html>
<html>
<head>
<title>Test Report</title>
<link rel="stylesheet" type="text/css" href="report.css">
</head>
<body>
<h2>Test Report</h2>
<div class="summary">
<div class="date">{now}</div>
<div class="count">Executed: {count_total} (100%)</div>
<div class="count">Succeeded: {count_success} ({percentage_success})</div>
<div class="count">Failed: {count_failure} ({percentage_failure})</div>
</div>
<table>
<thead>
<td>File</td>
<td>Status</td>
<td>Duration</td>
</thead>
<tbody>
{rows}
</tbody>
</table>
</body>
</html>
"#
)
}

fn create_html_table_row(result: &HTMLResult) -> String {
let status = if result.success {
"success".to_string()
} else {
"failure".to_string()
};
let duration_in_ms = result.time_in_ms;
let duration_in_s = result.time_in_ms as f64 / 1000.0;
let filename = &result.filename;
let displayed_filename = if filename == "-" {
"(standard input)"
} else {
filename
};
let id = &result.id;

format!(
r#"<tr class="{status}" data-duration="{duration_in_ms}" data-status="{status}" data-filename="{filename}" data-id="{id}">
<td><a href="store/{id}.html">{displayed_filename}</a></td>
<td>{status}</td>
<td>{duration_in_s}</td>
</tr>
"#
)
}

#[cfg(test)]
mod tests {

use super::*;

#[test]
fn test_percentage() {
assert_eq!(percentage(100, 100), "100.0%".to_string());
assert_eq!(percentage(66, 99), "66.7%".to_string());
assert_eq!(percentage(33, 99), "33.3%".to_string());
}

#[test]
fn test_parse_html_report() {
let html = r#"<html>
<body>
<h2>Hurl Report</h2>
<table>
<tbody>
<tr class="success" data-duration="100" data-status="success" data-filename="tests/hello.hurl" data-id="08aad14a-8d10-4ecc-892e-a72703c5b494">
<td><a href="tests/hello.hurl.html">tests/hello.hurl</a></td>
<td>success</td>
<td>0.1s</td>
</tr>
<tr class="failure" data-duration="200" data-status="failure" data-filename="tests/failure.hurl" data-id="a6641ae3-8ce0-4d9f-80c5-3e23e032e055">
<td><a href="tests/failure.hurl.html">tests/failure.hurl</a></td>
<td>failure</td>
<td>0.2s</td>
</tr>
</tbody>
<table>
</body>
</html>"#;

assert_eq!(
parse_html_report(html),
vec![
HTMLResult {
filename: "tests/hello.hurl".to_string(),
id: "08aad14a-8d10-4ecc-892e-a72703c5b494".to_string(),
time_in_ms: 100,
success: true,
},
HTMLResult {
filename: "tests/failure.hurl".to_string(),
id: "a6641ae3-8ce0-4d9f-80c5-3e23e032e055".to_string(),
time_in_ms: 200,
success: false,
}
]
);
}
}
Loading