Skip to content

Commit 661cd3b

Browse files
committed
fix(phpunit-report): don't report empty logs as passed, keep the summary below 1 MiB
- An empty TeamCity log is shown as without results instead of passed. PHPUnit leaves the log empty both when no test matched and when it stopped while loading the tests, so it can't be read as ended early. - The failure rows stop at 512 KiB, because GitHub drops a step summary larger than 1 MiB. The summary then points to the new reports-url input, which the Nx integration workflow sets to the uploaded reports. - Without any log, the summary says to see the job log instead of claiming that no suite ran: PHPUnit writes no log when its bootstrap fails.
1 parent b0ea84e commit 661cd3b

6 files changed

Lines changed: 175 additions & 43 deletions

File tree

‎.github/workflows/nx-integration-tests.yml‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -157,14 +157,8 @@ jobs:
157157
# after the module finished, so a cancelled or timed-out job shows nothing.
158158
nx affected --target=test:integration --head=HEAD --base=remotes/origin/${{ inputs.pr_base }} --parallel=1 --output-style=stream-without-prefixes
159159
160-
- name: Summarize Integration Test Results
161-
if: always()
162-
uses: mage-os/github-actions/phpunit-report@main
163-
with:
164-
path: main/phpunit-output/teamcity
165-
title: Integration tests
166-
167160
- name: Upload Integration Test Reports
161+
id: upload-reports
168162
if: always()
169163
uses: actions/upload-artifact@v4
170164
with:
@@ -173,3 +167,12 @@ jobs:
173167
path: main/phpunit-output/
174168
if-no-files-found: ignore
175169
retention-days: 14
170+
171+
- name: Summarize Integration Test Results
172+
if: always()
173+
uses: mage-os/github-actions/phpunit-report@main
174+
with:
175+
path: main/phpunit-output/teamcity
176+
title: Integration tests
177+
# The summary links the reports when it leaves failures out
178+
reports-url: ${{ steps.upload-reports.outputs.artifact-url }}

‎phpunit-report/README.md‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,33 @@ The action only reports; it never fails the job. Run it with `if: always()` afte
1010

1111
See the [action.yml](./action.yml)
1212

13-
| Input | Description | Required | Default |
14-
|-------|---------------------------------------------------------------------------------------------------|----------|-------------------|
15-
| path | Directory with one TeamCity log per suite, named `<suite>.log`. The file name is the suite's name. | true | |
16-
| title | Heading of the summary | false | 'PHPUnit results' |
13+
| Input | Description | Required | Default |
14+
|-------------|----------------------------------------------------------------------------------------------------------------------------------|----------|-------------------|
15+
| path | Directory with one TeamCity log per suite, named `<suite>.log`. The file name is the suite's name. | true | |
16+
| title | Heading of the summary | false | 'PHPUnit results' |
17+
| reports-url | Link to the full test reports, such as the `artifact-url` output of `actions/upload-artifact`. Shown when failures are left out. | false | '' |
1718

1819
## Usage
1920

2021
```yml
2122
- name: Run tests
2223
run: vendor/bin/phpunit --log-teamcity phpunit-output/teamcity/Unit.log
2324

25+
- name: Upload test reports
26+
id: reports
27+
if: always()
28+
uses: actions/upload-artifact@v4
29+
with:
30+
name: test-reports
31+
path: phpunit-output/
32+
2433
- name: Summarize test results
2534
if: always()
2635
uses: mage-os/github-actions/phpunit-report@main
2736
with:
2837
path: phpunit-output/teamcity
2938
title: Unit tests
39+
reports-url: ${{ steps.reports.outputs.artifact-url }}
3040
```
3141
3242
The summary starts with a headline, then lists the failed tests of each failing suite, then a table of all suites (collapsed when there are more than 10):
@@ -59,6 +69,10 @@ The summary starts with a headline, then lists the failed tests of each failing
5969

6070
The first failures also get error annotations, which point at the test or fixture file when the stack trace names one.
6171

72+
A suite lists at most 100 failures, and the summary stops listing them at 512 KiB: GitHub drops a step summary larger than 1 MiB. The summary then points to the `reports-url`.
73+
74+
A suite with an empty log is shown as without results, not as passed. PHPUnit leaves the log empty when no test matched, and when it stopped while loading the tests, for example on a syntax error. When its bootstrap fails, PHPUnit writes no log at all, so that suite is missing from the summary. The job log shows what happened in both cases.
75+
6276
## Development
6377

6478
The script needs only Python 3, which GitHub-hosted runners provide. Run its tests with:

‎phpunit-report/action.yml‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,10 @@ inputs:
1010
description: "Heading of the summary"
1111
required: false
1212
default: "PHPUnit results"
13+
reports-url:
14+
description: "Link to the full test reports, such as the artifact-url output of actions/upload-artifact. The summary points to it when it leaves failures out."
15+
required: false
16+
default: ""
1317

1418
runs:
1519
using: "composite"
@@ -19,7 +23,8 @@ runs:
1923
env:
2024
REPORT_PATH: ${{ inputs.path }}
2125
REPORT_TITLE: ${{ inputs.title }}
22-
run: python3 "${GITHUB_ACTION_PATH}/report.py" "${REPORT_PATH}" "${REPORT_TITLE}"
26+
REPORTS_URL: ${{ inputs.reports-url }}
27+
run: python3 "${GITHUB_ACTION_PATH}/report.py" "${REPORT_PATH}" "${REPORT_TITLE}" "${REPORTS_URL}"
2328

2429
branding:
2530
icon: "check-square"

‎phpunit-report/report.py‎

Lines changed: 70 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,15 @@
11
#!/usr/bin/env python3
22
"""Summarize PHPUnit TeamCity logs for a GitHub Actions job.
33
4-
Usage: report.py <directory with *.log files> [title]
4+
Usage: report.py <directory with *.log files> [title] [reports url]
55
66
Each *.log file is the TeamCity log (phpunit --log-teamcity) of one suite, named after it. PHPUnit writes that log
77
while the tests run, so it also lists the failures of a run that PHPUnit aborted, which the JUnit log, written at
88
the end, does not.
99
1010
The Markdown summary goes to $GITHUB_STEP_SUMMARY, or to stdout when that is not set. Error annotations for the
1111
first failures go to stdout as workflow commands. Exits 0: reporting never fails the job, the test step does.
12+
The reports url, if given, is where the summary sends readers for the failures it leaves out.
1213
"""
1314

1415
import glob
@@ -17,6 +18,9 @@
1718
import sys
1819

1920
MAX_ROWS_PER_SUITE = 100
21+
# GitHub drops a step summary larger than 1 MiB. The failure rows get at most half of that, the rest of the summary
22+
# takes a few hundred bytes per suite.
23+
MAX_FAILURE_BYTES = 512 * 1024
2024
MAX_EXPANDED_SUITES = 3
2125
MAX_TABLE_ROWS = 10
2226
MAX_ANNOTATIONS = 10
@@ -114,64 +118,102 @@ def broken(suite):
114118
return suite["ended_early"] or suite["failed_tests"] > 0
115119

116120

121+
def no_results(suite):
122+
"""An empty log: either no test matched, or PHPUnit stopped while loading the tests, say on a syntax error.
123+
124+
PHPUnit only writes to the log once the first suite starts, so the log alone can't tell the two apart.
125+
"""
126+
return suite["planned"] is None and not broken(suite)
127+
128+
117129
def result(suite):
118130
if suite["ended_early"]:
119131
return ":warning: ended early (PHPUnit aborted or the job stopped), see the job log"
120132
if suite["failed_tests"]:
121133
return ":x: failed"
134+
if no_results(suite):
135+
return ":grey_question: no results (no test ran, or PHPUnit stopped before the first one), see the job log"
122136
if suite["planned"] == 0:
123137
return ":heavy_minus_sign: no tests"
124138
return ":white_check_mark: passed"
125139

126140

127141
def headline(suites):
128142
failing = [suite for suite in suites if broken(suite)]
129-
if not failing:
130-
return ":white_check_mark: {} passed: {}, {} skipped.".format(
143+
without_results = sum(1 for suite in suites if no_results(suite))
144+
if failing:
145+
line = ":x: {} of {} failed: {}".format(
146+
len(failing),
131147
plural(len(suites), "suite"),
132-
plural(sum(suite["planned"] or 0 for suite in suites), "test"),
133-
sum(suite["skipped"] for suite in suites),
148+
plural(sum(suite["failed_tests"] for suite in failing), "failed test"),
134149
)
135-
line = ":x: {} of {} failed: {}".format(
136-
len(failing),
137-
plural(len(suites), "suite"),
138-
plural(sum(suite["failed_tests"] for suite in failing), "failed test"),
139-
)
140-
ended_early = sum(1 for suite in failing if suite["ended_early"])
141-
if ended_early:
142-
line += ", {} ended early".format(plural(ended_early, "suite"))
150+
ended_early = sum(1 for suite in failing if suite["ended_early"])
151+
if ended_early:
152+
line += ", {} ended early".format(plural(ended_early, "suite"))
153+
else:
154+
tests = plural(sum(suite["planned"] or 0 for suite in suites), "test")
155+
skipped = sum(suite["skipped"] for suite in suites)
156+
if without_results:
157+
line = ":grey_question: {} of {} passed: {}, {} skipped".format(
158+
len(suites) - without_results, plural(len(suites), "suite"), tests, skipped
159+
)
160+
else:
161+
line = ":white_check_mark: {} passed: {}, {} skipped".format(plural(len(suites), "suite"), tests, skipped)
162+
if without_results:
163+
line += ", {} without results".format(plural(without_results, "suite"))
143164
return line + "."
144165

145166

146-
def failure_details(suite, expanded):
167+
def failure_rows(failing):
168+
"""The table rows of each failing suite, in order, as many as fit in MAX_FAILURE_BYTES."""
169+
left = MAX_FAILURE_BYTES
170+
tables = []
171+
for suite in failing:
172+
rows = []
173+
for failure in suite["failures"][:MAX_ROWS_PER_SUITE]:
174+
row = "| `{}` | {} |".format(cell(failure["test"]).replace("`", "'"), cell(failure["message"]))
175+
left -= len(row.encode("utf-8")) + 1
176+
if left < 0:
177+
break
178+
rows.append(row)
179+
tables.append(rows)
180+
return tables
181+
182+
183+
def failure_details(suite, rows, expanded):
147184
problems = [plural(suite["failed_tests"], "failed test")] if suite["failed_tests"] else []
148185
if suite["ended_early"]:
149186
problems.append("ended early")
150187
summary = "<b>{}</b>: {}".format(suite["name"], ", ".join(problems))
151188
lines = ["", "<details{}><summary>{}</summary>".format(" open" if expanded else "", summary), ""]
152189
if suite["ended_early"]:
153190
lines += ["PHPUnit stopped before the suite finished. The job log shows why.", ""]
154-
if suite["failures"]:
155-
lines += ["| Test | Message |", "|---|---|"]
156-
for failure in suite["failures"][:MAX_ROWS_PER_SUITE]:
157-
lines.append("| `{}` | {} |".format(cell(failure["test"]).replace("`", "'"), cell(failure["message"])))
158-
hidden = len(suite["failures"]) - MAX_ROWS_PER_SUITE
159-
if hidden > 0:
160-
lines.append("| … | and {} more |".format(hidden))
191+
left_out = len(suite["failures"]) - len(rows)
192+
if rows:
193+
lines += ["| Test | Message |", "|---|---|"] + rows
194+
if left_out:
195+
lines.append("| … | and {} more |".format(left_out))
161196
lines.append("")
197+
elif left_out:
198+
lines += ["{} not listed: the summary reached its size limit.".format(plural(left_out, "failure")), ""]
162199
return lines + ["</details>"]
163200

164201

165-
def markdown(suites, title, directory):
202+
def markdown(suites, title, directory, reports_url=""):
166203
lines = ["## " + title, ""]
167204
if not suites:
168-
lines.append("No PHPUnit TeamCity logs in `{}`: no suite ran.".format(directory))
205+
# PHPUnit writes no log when it stops in its bootstrap
206+
lines.append(":grey_question: No PHPUnit TeamCity logs found in `{}`, see the job log.".format(directory))
169207
return "\n".join(lines) + "\n"
170208

171209
lines.append(headline(suites))
172210
failing = [suite for suite in suites if broken(suite)]
173-
for suite in failing:
174-
lines += failure_details(suite, len(failing) <= MAX_EXPANDED_SUITES)
211+
tables = failure_rows(failing)
212+
for suite, rows in zip(failing, tables):
213+
lines += failure_details(suite, rows, len(failing) <= MAX_EXPANDED_SUITES)
214+
if sum(len(rows) for rows in tables) < sum(len(suite["failures"]) for suite in failing):
215+
reports = "[test reports]({})".format(reports_url) if reports_url else "TeamCity logs"
216+
lines += ["", "Not all failures are listed. The {} have all of them.".format(reports)]
175217

176218
table = ["| Suite | Tests | Failed | Skipped | Result |", "|---|---:|---:|---:|---|"]
177219
for suite in suites:
@@ -212,13 +254,14 @@ def annotations(suites):
212254

213255
def main(argv):
214256
if len(argv) < 2:
215-
print("Usage: report.py <directory with *.log files> [title]", file=sys.stderr)
257+
print("Usage: report.py <directory with *.log files> [title] [reports url]", file=sys.stderr)
216258
return 2
217259
directory = argv[1]
218260
title = argv[2] if len(argv) > 2 and argv[2] else "PHPUnit results"
261+
reports_url = argv[3] if len(argv) > 3 else ""
219262
suites = [parse(path) for path in sorted(glob.glob(os.path.join(directory, "*.log")))]
220263

221-
summary = markdown(suites, title, directory)
264+
summary = markdown(suites, title, directory, reports_url)
222265
summary_file = os.environ.get("GITHUB_STEP_SUMMARY")
223266
if summary_file:
224267
with open(summary_file, "a", encoding="utf-8") as handle:

‎phpunit-report/test/fixtures/Empty.log‎

Whitespace-only changes.

‎phpunit-report/test/test_report.py‎

Lines changed: 71 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,14 @@ def test_suite_that_ended_early(self):
6363
self.assertEqual(0, suite["failed_tests"])
6464
self.assertTrue(suite["ended_early"])
6565

66+
def test_empty_log(self):
67+
suite = report.parse(fixture("Empty"))
68+
69+
self.assertIsNone(suite["planned"])
70+
self.assertEqual(0, suite["failed_tests"])
71+
self.assertFalse(suite["ended_early"])
72+
self.assertTrue(report.no_results(suite))
73+
6674

6775
class MarkdownTest(unittest.TestCase):
6876
def test_summary_lists_failures_before_the_suites(self):
@@ -82,14 +90,37 @@ def test_summary_lists_failures_before_the_suites(self):
8290
self.assertIn("| Passing | 2 | 0 | 0 | :white_check_mark: passed |", summary)
8391

8492
def test_passing_run(self):
85-
empty = dict(report.parse(fixture("Passing")), name="Empty", planned=0)
93+
no_tests = dict(report.parse(fixture("Passing")), name="NoTests", planned=0)
8694

87-
summary = report.markdown([report.parse(fixture("Passing")), empty], "Tests", "logs")
95+
summary = report.markdown([report.parse(fixture("Passing")), no_tests], "Tests", "logs")
8896

8997
self.assertIn(":white_check_mark: 2 suites passed: 2 tests, 0 skipped.", summary)
90-
self.assertIn("| Empty | 0 | 0 | 0 | :heavy_minus_sign: no tests |", summary)
98+
self.assertIn("| NoTests | 0 | 0 | 0 | :heavy_minus_sign: no tests |", summary)
9199
self.assertNotIn("<details", summary)
92100

101+
def test_empty_log_is_not_reported_as_passed(self):
102+
suites = [report.parse(fixture(name)) for name in ("Empty", "Passing")]
103+
104+
summary = report.markdown(suites, "Tests", "logs")
105+
106+
self.assertIn(":grey_question: 1 of 2 suites passed: 2 tests, 0 skipped, 1 suite without results.", summary)
107+
self.assertIn(
108+
"| Empty | ? | 0 | 0 | :grey_question: no results (no test ran, or PHPUnit stopped before the first one),"
109+
" see the job log |",
110+
summary,
111+
)
112+
self.assertNotIn("<details", summary)
113+
114+
def test_suites_without_results_are_counted_next_to_failures(self):
115+
suites = [report.parse(fixture(name)) for name in ("Aborted", "Empty", "Failing")]
116+
117+
summary = report.markdown(suites, "Tests", "logs")
118+
119+
self.assertIn(
120+
":x: 2 of 3 suites failed: 3 failed tests, 1 suite ended early, 1 suite without results.", summary
121+
)
122+
self.assertNotIn("<b>Empty</b>", summary)
123+
93124
def test_many_suites_are_collapsed(self):
94125
failing = report.parse(fixture("Failing"))
95126
passing = report.parse(fixture("Passing"))
@@ -115,11 +146,35 @@ def test_long_failure_lists_are_cut(self):
115146
self.assertNotIn("`T::test100`", summary)
116147
self.assertIn("| … | and 5 more |", summary)
117148
self.assertIn("x" * (report.MAX_MESSAGE_LENGTH - 1) + "…", summary)
149+
self.assertIn("Not all failures are listed. The TeamCity logs have all of them.", summary)
150+
151+
def test_summary_stays_below_the_size_limit_of_github(self):
152+
# 30 suites with 100 failures of about 430 bytes each: 1.3 MB in full, over GitHub's limit of 1 MiB
153+
failures = [
154+
{"test": "Magento\\Demo\\Model\\{}Test::test{}".format("Long" * 20, number), "message": "y" * 400,
155+
"location": None}
156+
for number in range(100)
157+
]
158+
failing = report.parse(fixture("Failing"))
159+
suites = [
160+
dict(failing, name="Suite{}".format(number), failures=failures, failed_tests=100) for number in range(30)
161+
]
162+
163+
summary = report.markdown(suites, "Tests", "logs", "https://example.com/reports")
164+
165+
self.assertLess(len(summary.encode("utf-8")), 1024 * 1024)
166+
self.assertIn("| … | and ", summary)
167+
self.assertIn("<details><summary><b>Suite29</b>: 100 failed tests</summary>", summary)
168+
self.assertIn("100 failures not listed: the summary reached its size limit.", summary)
169+
self.assertIn(
170+
"Not all failures are listed. The [test reports](https://example.com/reports) have all of them.", summary
171+
)
172+
self.assertIn("| Suite29 | 5 | 100 | 1 | :x: failed |", summary)
118173

119174
def test_no_logs(self):
120175
summary = report.markdown([], "Tests", "phpunit-output/teamcity")
121176

122-
self.assertIn("No PHPUnit TeamCity logs in `phpunit-output/teamcity`", summary)
177+
self.assertIn("No PHPUnit TeamCity logs found in `phpunit-output/teamcity`, see the job log.", summary)
123178

124179

125180
class AnnotationsTest(unittest.TestCase):
@@ -172,6 +227,18 @@ def test_prints_the_summary_outside_github_actions(self):
172227
self.assertIn("## PHPUnit results", output.getvalue())
173228
self.assertNotIn("::error", output.getvalue())
174229

230+
def test_links_the_reports_for_the_failures_it_leaves_out(self):
231+
output = io.StringIO()
232+
environment = {key: value for key, value in os.environ.items() if key != "GITHUB_STEP_SUMMARY"}
233+
234+
with mock.patch.dict(os.environ, environment, clear=True), mock.patch.object(
235+
report, "MAX_ROWS_PER_SUITE", 1
236+
), contextlib.redirect_stdout(output):
237+
report.main(["report.py", self.directory, "Tests", "https://example.com/reports"])
238+
239+
self.assertIn("| … | and 2 more |", output.getvalue())
240+
self.assertIn("The [test reports](https://example.com/reports) have all of them.", output.getvalue())
241+
175242
def test_requires_a_directory(self):
176243
with contextlib.redirect_stderr(io.StringIO()):
177244
self.assertEqual(2, report.main(["report.py"]))

0 commit comments

Comments
 (0)