forked from rtk-ai/rtk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphpunit_cmd.rs
More file actions
394 lines (326 loc) · 12.1 KB
/
Copy pathphpunit_cmd.rs
File metadata and controls
394 lines (326 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
//! PHPUnit output filter.
//!
//! Parses PHPUnit's plain-text runner output and emits a compact summary:
//! aggregate counts from the `Tests: X, Assertions: Y, Failures: Z.` line
//! plus a bounded list of failures with their first two detail lines.
//! Dot-progress lines and headers are stripped entirely.
use super::utils::{php_tool_command, strip_ansi_and_controls};
use crate::core::runner;
use anyhow::Result;
use regex::Regex;
use std::sync::LazyLock;
const MAX_FAILURES_SHOWN: usize = 10;
const MAX_DETAIL_LINES_PER_FAILURE: usize = 2;
// PHPUnit prints each failure heading as "N) Class::method". Anchor to that
// exact shape so detail lines that merely start with a digit and contain ')'
// (e.g. "5 of 10 assertions passed in Foo::bar()") don't split a block.
static FAILURE_HEADING_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d+\) \S").unwrap());
pub fn run(args: &[String], verbose: u8) -> Result<i32> {
let mut cmd = php_tool_command("phpunit");
for arg in args {
cmd.arg(arg);
}
if verbose > 0 {
eprintln!("Running: phpunit {}", args.join(" "));
}
runner::run_filtered(
cmd,
"phpunit",
&args.join(" "),
filter_phpunit_output,
runner::RunOptions::stdout_only().tee("phpunit"),
)
}
pub(crate) fn filter_phpunit_output(output: &str) -> String {
// PHPUnit colorizes its result line and progress with ANSI under
// `--colors=always`; without stripping, the "OK ("/"FAILURES!"/"Tests:"
// anchors below never match and real counts are lost.
let cleaned = strip_ansi_and_controls(output);
let output = cleaned.as_str();
let mut failures: Vec<Vec<String>> = Vec::new();
let mut current: Vec<String> = Vec::new();
let mut in_failures = false;
for line in output.lines() {
let trimmed = line.trim();
if trimmed.starts_with("OK (") {
return format!("PHPUnit: {}", trimmed);
}
if trimmed.starts_with("OK, but") {
return build_success_with_skipped(output);
}
if (trimmed.starts_with("There was") || trimmed.starts_with("There were"))
&& (trimmed.contains("failure") || trimmed.contains("error"))
{
in_failures = true;
continue;
}
if trimmed == "FAILURES!" || trimmed == "ERRORS!" {
if !current.is_empty() {
failures.push(std::mem::take(&mut current));
}
in_failures = false;
continue;
}
if in_failures {
if is_numbered_failure_heading(trimmed) {
if !current.is_empty() {
failures.push(std::mem::take(&mut current));
}
current.push(trimmed.to_string());
} else if !trimmed.is_empty() {
current.push(trimmed.to_string());
}
}
}
if !current.is_empty() {
failures.push(current);
}
if failures.is_empty() {
let counts = parse_counts(output);
if counts.tests > 0 {
return format!(
"PHPUnit: {} tests, {} assertions",
counts.tests, counts.assertions
);
}
return "PHPUnit: ok".to_string();
}
build_phpunit_summary(output, &failures)
}
fn is_numbered_failure_heading(line: &str) -> bool {
FAILURE_HEADING_RE.is_match(line)
}
fn build_success_with_skipped(output: &str) -> String {
let counts = parse_counts(output);
if counts.skipped > 0 {
format!(
"PHPUnit: {} tests, {} assertions, {} skipped",
counts.tests, counts.assertions, counts.skipped
)
} else {
format!(
"PHPUnit: {} tests, {} assertions",
counts.tests, counts.assertions
)
}
}
fn build_phpunit_summary(output: &str, failures: &[Vec<String>]) -> String {
let counts = parse_counts(output);
// PHPUnit separates failures (assertion mismatches) from errors (thrown
// exceptions); report them distinctly rather than lumping under "failures".
let mut result = format!(
"PHPUnit: {} tests, {} assertions, {} failures",
counts.tests, counts.assertions, counts.failures
);
if counts.errors > 0 {
result.push_str(&format!(", {} errors", counts.errors));
}
result.push('\n');
for failure_lines in failures.iter().take(MAX_FAILURES_SHOWN) {
if let Some(first) = failure_lines.first() {
result.push_str(&format!("\n{}\n", first));
}
for detail in failure_lines
.iter()
.skip(1)
.take(MAX_DETAIL_LINES_PER_FAILURE)
{
result.push_str(&format!(" {}\n", detail));
}
}
if failures.len() > MAX_FAILURES_SHOWN {
result.push_str(&format!(
"\n... +{} more failures\n",
failures.len() - MAX_FAILURES_SHOWN
));
}
result.trim().to_string()
}
fn parse_counts(output: &str) -> Counts {
let mut counts = Counts::default();
for line in output.lines() {
let trimmed = line.trim();
if !trimmed.starts_with("Tests:") {
continue;
}
for part in trimmed.split(',') {
let mut it = part.split_whitespace();
let key = it.next().unwrap_or("");
let val = it
.next()
.unwrap_or("")
.trim_end_matches('.')
.parse()
.unwrap_or(0);
match key {
"Tests:" => counts.tests = val,
"Assertions:" => counts.assertions = val,
k if k.starts_with("Failures") => counts.failures += val,
k if k.starts_with("Errors") => counts.errors += val,
k if k.starts_with("Skipped") => counts.skipped = val,
_ => {}
}
}
}
counts
}
#[derive(Default)]
struct Counts {
tests: usize,
assertions: usize,
failures: usize,
errors: usize,
skipped: usize,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_numbered_failure_heading_anchored() {
// Real PHPUnit failure headings match.
assert!(is_numbered_failure_heading("1) App\\Tests\\UserTest::testEmail"));
assert!(is_numbered_failure_heading("12) Foo::bar"));
// Detail lines that merely start with a digit and contain ')' must not.
assert!(!is_numbered_failure_heading(
"5 of 10 assertions passed in Foo::bar()"
));
assert!(!is_numbered_failure_heading("1)")); // no method after ") "
assert!(!is_numbered_failure_heading(
"Failed asserting that Array(3) is identical."
));
}
const REAL_PHPUNIT_FAILURE: &str = r#"PHPUnit 10.5.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.2.27 with Xdebug 3.3.1
Configuration: /var/www/html/phpunit.xml
........................................ 40 / 40 (100%)
.................................................. 80 / 80 (100%)
.F................................................ 100 / 100 (100%)
.......... 110 / 110 (100%)
Time: 00:01:23.456, Memory: 48.00 MB
There was 1 failure:
1) App\Tests\UserTest::testEmailValidation
Failed asserting that false is true.
#0 /var/www/html/src/User.php:142 (App\User::validate)
#1 /var/www/html/tests/UserTest.php:38 (App\Tests\UserTest::testEmailValidation)
FAILURES!
Tests: 110, Assertions: 340, Failures: 1."#;
const REAL_PHPUNIT_SUCCESS: &str = r#"PHPUnit 10.5.0 by Sebastian Bergmann and contributors.
Runtime: PHP 8.2.0
......... 9 / 9 (100%)
Time: 00:00:00.234, Memory: 6.00 MB
OK (9 tests, 20 assertions)"#;
const REAL_PHPUNIT_MULTIPLE_FAILURES: &str = r#"PHPUnit 10.5.0 by Sebastian Bergmann and contributors.
FF....... 9 / 9 (100%)
Time: 00:00:00.234, Memory: 6.00 MB
There were 2 failures:
1) UserTest::testEmail
Failed asserting that false is true.
/home/user/tests/UserTest.php:42
2) OrderTest::testTotal
Failed asserting that 42 matches expected 100.
/home/user/tests/OrderTest.php:17
FAILURES!
Tests: 9, Assertions: 15, Failures: 2."#;
#[test]
fn test_phpunit_success() {
let result = filter_phpunit_output(REAL_PHPUNIT_SUCCESS);
assert!(result.contains("PHPUnit"), "got: {}", result);
assert!(result.contains("OK (9 tests, 20 assertions)"), "got: {}", result);
}
#[test]
fn test_phpunit_failure_captures_test_name() {
let result = filter_phpunit_output(REAL_PHPUNIT_FAILURE);
assert!(
result.contains("UserTest::testEmailValidation"),
"got: {}",
result
);
assert!(
result.contains("Failed asserting that false is true"),
"got: {}",
result
);
}
#[test]
fn test_phpunit_failure_summary_counts() {
let result = filter_phpunit_output(REAL_PHPUNIT_FAILURE);
assert!(result.contains("110 tests"), "got: {}", result);
assert!(result.contains("340 assertions"), "got: {}", result);
assert!(result.contains("1 failures"), "got: {}", result);
}
#[test]
fn test_phpunit_multiple_failures() {
let result = filter_phpunit_output(REAL_PHPUNIT_MULTIPLE_FAILURES);
assert!(result.contains("UserTest::testEmail"), "got: {}", result);
assert!(result.contains("OrderTest::testTotal"), "got: {}", result);
assert!(result.contains("2 failures"), "got: {}", result);
}
#[test]
fn test_phpunit_ok_with_skipped() {
let output = r#"OK, but incomplete, skipped, or risky tests!
Tests: 5, Assertions: 10, Skipped: 2."#;
let result = filter_phpunit_output(output);
assert!(result.contains("5 tests"), "got: {}", result);
assert!(result.contains("2 skipped"), "got: {}", result);
}
#[test]
fn test_phpunit_errors_summary() {
let output = r#"There was 1 error:
1) FooTest::testBar
RuntimeException: boom
ERRORS!
Tests: 1, Assertions: 0, Errors: 1."#;
let result = filter_phpunit_output(output);
assert!(result.contains("FooTest::testBar"), "got: {}", result);
// Errors are now reported distinctly from failures.
assert!(result.contains("0 failures, 1 errors"), "got: {}", result);
}
#[test]
fn test_phpunit_failure_truncation() {
let mut output = String::from("There were 15 failures:\n\n");
for i in 1..=15 {
output.push_str(&format!(
"{}) Suite::test{}\nFailed asserting thing {}.\n\n",
i, i, i
));
}
output.push_str("FAILURES!\nTests: 15, Assertions: 15, Failures: 15.\n");
let result = filter_phpunit_output(&output);
assert!(result.contains("Suite::test1"), "got: {}", result);
assert!(result.contains("Suite::test10"), "got: {}", result);
assert!(!result.contains("Suite::test11"), "got: {}", result);
assert!(result.contains("+5 more failures"), "got: {}", result);
}
#[test]
fn test_phpunit_strips_ansi_colors() {
// --colors=always wraps the result line; anchors must still match.
let colored = "\x1b[30;42mOK\x1b[0m \x1b[32m(9 tests, 20 assertions)\x1b[0m";
let result = filter_phpunit_output(colored);
assert!(
result.contains("OK (9 tests, 20 assertions)"),
"got: {}",
result
);
}
#[test]
fn test_phpunit_empty_ok_fallback() {
let result = filter_phpunit_output("");
assert_eq!(result, "PHPUnit: ok");
}
#[test]
fn test_phpunit_only_summary_line() {
let result = filter_phpunit_output("Tests: 4, Assertions: 4.\n");
assert!(result.contains("4 tests"), "got: {}", result);
}
#[test]
fn test_phpunit_compression() {
let raw_len = REAL_PHPUNIT_FAILURE.len();
let filtered_len = filter_phpunit_output(REAL_PHPUNIT_FAILURE).len();
assert!(
filtered_len < raw_len / 2,
"expected >50% reduction, raw={}, filtered={}",
raw_len,
filtered_len
);
}
}