1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2024-11-26 16:09:27 -05:00
denoland-deno/cli/tools/test/reporters/common.rs
Yusuke Tanaka 64e8c36805
fix(cli): output more detailed information for steps when using JUnit reporter (#22797)
This patch gets JUnit reporter to output more detailed information for
test steps (subtests).

## Issue with previous implementation

In the previous implementation, the test hierarchy was represented using
several XML tags like the following:

- `<testsuites>` corresponds to the entire test (one execution of `deno
test` has exactly one `<testsuites>` tag)
- `<testsuite>` corresponds to one file, such as `main_test.ts`
- `<testcase>` corresponds to one `Deno.test(...)`
- `<property>` corresponds to one `t.step(...)`

This structure describes the test layers but one problem is that
`<property>` tag is used for any use cases so some tools that can ingest
a JUnit XML file might not be able to interpret `<property>` as
subtests.

## How other tools address it

Some of the testing frameworks in the ecosystem address this issue by
fitting subtests into the `<testcase>` layer. For instance, take a look
at the following Go test file:

```go
package main_test

import "testing"

func TestMain(t *testing.T) {
  t.Run("child 1", func(t *testing.T) {
    // OK
  })

  t.Run("child 2", func(t *testing.T) {
    // Error
    t.Fatal("error")
  })
}
```

Running [gotestsum], we can get the output like this:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<testsuites tests="3" failures="2" errors="0" time="1.013694">
	<testsuite tests="3" failures="2" time="0.510000" name="example/gosumtest" timestamp="2024-03-11T12:26:39+09:00">
		<properties>
			<property name="go.version" value="go1.22.1 darwin/arm64"></property>
		</properties>
		<testcase classname="example/gosumtest" name="TestMain/child_2" time="0.000000">
			<failure message="Failed" type="">=== RUN   TestMain/child_2&#xA;    main_test.go:12: error&#xA;--- FAIL: TestMain/child_2 (0.00s)&#xA;</failure>
		</testcase>
		<testcase classname="example/gosumtest" name="TestMain" time="0.000000">
			<failure message="Failed" type="">=== RUN   TestMain&#xA;--- FAIL: TestMain (0.00s)&#xA;</failure>
		</testcase>
		<testcase classname="example/gosumtest" name="TestMain/child_1" time="0.000000"></testcase>
	</testsuite>
</testsuites>
``` 

This output shows that nested test cases are squashed into the
`<testcase>` layer by treating them as the same layer as their parent,
`TestMain`. We can still distinguish nested ones by their `name`
attributes that look like `TestMain/<subtest_name>`.

As described in #22795, [vitest] solves the issue in the same way as
[gotestsum].

One downside of this would be that one test failure that happens in a
nested test case will end up being counted multiple times, because not
only the subtest but also its wrapping container(s) are considered to be
failures. In fact, in the [gotestsum] output above, `TestMain/child_2`
failed (which is totally expected) while its parent, `TestMain`, was
also counted as failure. As
https://github.com/denoland/deno/pull/20273#discussion_r1307558757
pointed out, there is a test runner that offers flexibility to prevent
this, but I personally don't think the "duplicate failure count" issue
is a big deal.

## How to fix the issue in this patch

This patch fixes the issue with the same approach as [gotestsum] and
[vitest].
More specifically, nested test cases are put into the `<testcase>` level
and their names are now represented as squashed test names concatenated
by `>` (e.g. `parent 2 > child 1 > grandchild 1`). This change also
allows us to put a detailed error message as `<failure>` tag within the
`<testcase>` tag, which should be handled nicely by third-party tools
supporting JUnit XML.

## Extra fix

Also, file paths embedded into XML outputs are changed from absolute
path to relative path, which is helpful when running the test suites in
several different environments like CI.

Resolves #22795

[gotestsum]: https://github.com/gotestyourself/gotestsum
[vitest]: https://vitest.dev/

---------

Co-authored-by: Bartek Iwańczuk <biwanczuk@gmail.com>
2024-03-26 00:08:46 +09:00

225 lines
6.3 KiB
Rust

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
use super::fmt::format_test_error;
use super::fmt::to_relative_path_or_remote_url;
use super::*;
pub(super) fn format_test_step_ancestry(
desc: &TestStepDescription,
tests: &IndexMap<usize, TestDescription>,
test_steps: &IndexMap<usize, TestStepDescription>,
) -> String {
let root;
let mut ancestor_names = vec![];
let mut current_desc = desc;
loop {
if let Some(step_desc) = test_steps.get(&current_desc.parent_id) {
ancestor_names.push(&step_desc.name);
current_desc = step_desc;
} else {
root = tests.get(&current_desc.parent_id).unwrap();
break;
}
}
ancestor_names.reverse();
let mut result = String::new();
result.push_str(&root.name);
result.push_str(" ... ");
for name in ancestor_names {
result.push_str(name);
result.push_str(" ... ");
}
result.push_str(&desc.name);
result
}
pub fn format_test_for_summary(
cwd: &Url,
desc: &TestFailureDescription,
) -> String {
format!(
"{} {}",
&desc.name,
colors::gray(format!(
"=> {}:{}:{}",
to_relative_path_or_remote_url(cwd, &desc.location.file_name),
desc.location.line_number,
desc.location.column_number
))
)
}
pub fn format_test_step_for_summary(
cwd: &Url,
desc: &TestStepDescription,
tests: &IndexMap<usize, TestDescription>,
test_steps: &IndexMap<usize, TestStepDescription>,
) -> String {
let long_name = format_test_step_ancestry(desc, tests, test_steps);
format!(
"{} {}",
long_name,
colors::gray(format!(
"=> {}:{}:{}",
to_relative_path_or_remote_url(cwd, &desc.location.file_name),
desc.location.line_number,
desc.location.column_number
))
)
}
pub(super) fn report_sigint(
writer: &mut dyn std::io::Write,
cwd: &Url,
tests_pending: &HashSet<usize>,
tests: &IndexMap<usize, TestDescription>,
test_steps: &IndexMap<usize, TestStepDescription>,
) {
if tests_pending.is_empty() {
return;
}
let mut formatted_pending = BTreeSet::new();
for id in tests_pending {
if let Some(desc) = tests.get(id) {
formatted_pending.insert(format_test_for_summary(cwd, &desc.into()));
}
if let Some(desc) = test_steps.get(id) {
formatted_pending
.insert(format_test_step_for_summary(cwd, desc, tests, test_steps));
}
}
writeln!(
writer,
"\n{} The following tests were pending:\n",
colors::intense_blue("SIGINT")
)
.unwrap();
for entry in formatted_pending {
writeln!(writer, "{}", entry).unwrap();
}
writeln!(writer).unwrap();
}
pub(super) fn report_summary(
writer: &mut dyn std::io::Write,
cwd: &Url,
summary: &TestSummary,
elapsed: &Duration,
) {
if !summary.failures.is_empty() || !summary.uncaught_errors.is_empty() {
#[allow(clippy::type_complexity)] // Type alias doesn't look better here
let mut failures_by_origin: BTreeMap<
String,
(
Vec<(&TestFailureDescription, &TestFailure)>,
Option<&JsError>,
),
> = BTreeMap::default();
let mut failure_titles = vec![];
for (description, failure) in &summary.failures {
let (failures, _) = failures_by_origin
.entry(description.origin.clone())
.or_default();
failures.push((description, failure));
}
for (origin, js_error) in &summary.uncaught_errors {
let (_, uncaught_error) =
failures_by_origin.entry(origin.clone()).or_default();
let _ = uncaught_error.insert(js_error.as_ref());
}
// note: the trailing whitespace is intentional to get a red background
writeln!(writer, "\n{}\n", colors::white_bold_on_red(" ERRORS ")).unwrap();
for (origin, (failures, uncaught_error)) in failures_by_origin {
for (description, failure) in failures {
if !failure.hide_in_summary() {
let failure_title = format_test_for_summary(cwd, description);
writeln!(writer, "{}", &failure_title).unwrap();
writeln!(writer, "{}: {}", colors::red_bold("error"), failure)
.unwrap();
writeln!(writer).unwrap();
failure_titles.push(failure_title);
}
}
if let Some(js_error) = uncaught_error {
let failure_title = format!(
"{} (uncaught error)",
to_relative_path_or_remote_url(cwd, &origin)
);
writeln!(writer, "{}", &failure_title).unwrap();
writeln!(
writer,
"{}: {}",
colors::red_bold("error"),
format_test_error(js_error)
)
.unwrap();
writeln!(writer, "This error was not caught from a test and caused the test runner to fail on the referenced module.").unwrap();
writeln!(writer, "It most likely originated from a dangling promise, event/timeout handler or top-level code.").unwrap();
writeln!(writer).unwrap();
failure_titles.push(failure_title);
}
}
// note: the trailing whitespace is intentional to get a red background
writeln!(writer, "{}\n", colors::white_bold_on_red(" FAILURES ")).unwrap();
for failure_title in failure_titles {
writeln!(writer, "{failure_title}").unwrap();
}
}
let status = if summary.has_failed() {
colors::red("FAILED").to_string()
} else {
colors::green("ok").to_string()
};
let get_steps_text = |count: usize| -> String {
if count == 0 {
String::new()
} else if count == 1 {
" (1 step)".to_string()
} else {
format!(" ({count} steps)")
}
};
let mut summary_result = String::new();
write!(
summary_result,
"{} passed{} | {} failed{}",
summary.passed,
get_steps_text(summary.passed_steps),
summary.failed,
get_steps_text(summary.failed_steps),
)
.unwrap();
let ignored_steps = get_steps_text(summary.ignored_steps);
if summary.ignored > 0 || !ignored_steps.is_empty() {
write!(
summary_result,
" | {} ignored{}",
summary.ignored, ignored_steps
)
.unwrap()
}
if summary.measured > 0 {
write!(summary_result, " | {} measured", summary.measured,).unwrap();
}
if summary.filtered_out > 0 {
write!(summary_result, " | {} filtered out", summary.filtered_out).unwrap()
};
writeln!(
writer,
"\n{} | {} {}",
status,
summary_result,
colors::gray(format!("({})", display::human_elapsed(elapsed.as_millis()))),
)
.unwrap();
}