Skip to content

Commit 76f0ae8

Browse files
authored
Merge pull request #211 from aligent/chore/DO-2070_test_coverage
DO-2070: add test coverage workflow
2 parents bcd44ac + f8d8b6c commit 76f0ae8

3 files changed

Lines changed: 266 additions & 0 deletions

File tree

‎.github/workflows/coverage.yml‎

Lines changed: 194 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,194 @@
1+
name: 📊 Coverage
2+
3+
on:
4+
workflow_call:
5+
inputs:
6+
package-manager:
7+
description: "Node package manager to use (yarn or npm)"
8+
default: yarn
9+
type: string
10+
is-yarn-classic:
11+
description: "If Yarn (pre-Berry) should be used"
12+
default: false
13+
type: boolean
14+
node-version:
15+
description: "Node.js version to use when the repository has no .nvmrc file"
16+
default: "24"
17+
type: string
18+
test-command:
19+
description: "Script or Nx target that runs the tests"
20+
default: test
21+
type: string
22+
comment-id:
23+
description: >-
24+
Identifies this workflow's PR comment. Set a different value per call when the
25+
workflow runs more than once on a PR (e.g. a matrix). Letters, digits, '.', '_' and '-' only.
26+
default: default
27+
type: string
28+
29+
jobs:
30+
coverage:
31+
name: 📊 Coverage
32+
runs-on: ubuntu-latest
33+
permissions:
34+
contents: read
35+
pull-requests: write
36+
steps:
37+
- name: Validate inputs
38+
run: |
39+
case "${INPUTS_PACKAGE_MANAGER}" in
40+
yarn|npm) ;;
41+
*)
42+
echo "::error::Unsupported package-manager '${INPUTS_PACKAGE_MANAGER}'. Use 'yarn' or 'npm'."
43+
exit 1
44+
;;
45+
esac
46+
# comment-id is embedded in the comment marker and a jq filter, so restrict its characters.
47+
if ! [[ "${INPUTS_COMMENT_ID}" =~ ^[A-Za-z0-9._-]+$ ]]; then
48+
echo "::error::Invalid comment-id '${INPUTS_COMMENT_ID}'. Use letters, digits, '.', '_' and '-' only."
49+
exit 1
50+
fi
51+
env:
52+
INPUTS_COMMENT_ID: ${{ inputs.comment-id }}
53+
INPUTS_PACKAGE_MANAGER: ${{ inputs.package-manager }}
54+
55+
# run-many does not need Git history (only `nx affected` does), so a shallow clone is enough.
56+
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 #v7.0.1
57+
with:
58+
persist-credentials: false
59+
60+
# Use the consumer's .nvmrc when present, otherwise fall back to the node-version input.
61+
- name: Install Node.js
62+
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e #v6.4.0
63+
with:
64+
node-version: ${{ case(hashFiles('.nvmrc') != '', '', inputs.node-version) }}
65+
node-version-file: ${{ case(hashFiles('.nvmrc') != '', '.nvmrc', '') }}
66+
package-manager-cache: false
67+
68+
- name: Enable Corepack
69+
if: hashFiles('package.json') != ''
70+
run: |
71+
# Enable corepack if packageManager is specified in package.json
72+
if jq -e '.packageManager' package.json >/dev/null 2>&1; then
73+
echo "packageManager field detected in package.json, enabling corepack"
74+
corepack enable
75+
fi
76+
77+
- name: Configure Dependency Cache
78+
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e #v6.4.0
79+
with:
80+
cache: ${{ inputs.package-manager }}
81+
node-version: ${{ case(hashFiles('.nvmrc') != '', '', inputs.node-version) }}
82+
node-version-file: ${{ case(hashFiles('.nvmrc') != '', '.nvmrc', '') }}
83+
84+
- name: Install safe-chain
85+
uses: $/.github/actions/install-safe-chain
86+
87+
- name: Install dependencies
88+
run: |
89+
if [ "${INPUTS_PACKAGE_MANAGER}" = "yarn" ]; then
90+
yarn install ${FLAG_LOCK_DEPENDENCIES}
91+
else
92+
npm ci
93+
fi
94+
env:
95+
FLAG_LOCK_DEPENDENCIES: ${{ case(inputs.is-yarn-classic == true, '--frozen-lockfile', '--immutable') }}
96+
INPUTS_PACKAGE_MANAGER: ${{ inputs.package-manager }}
97+
98+
- name: Run tests with coverage
99+
id: coverage
100+
run: |
101+
set -o pipefail
102+
103+
if [ "${INPUTS_PACKAGE_MANAGER}" = "yarn" ]; then
104+
runner="yarn"
105+
else
106+
runner="npx"
107+
fi
108+
109+
if [ -f "nx.json" ]; then
110+
${runner} nx run-many -t "${INPUTS_TEST_COMMAND}" --skip-nx-cache --outputStyle=stream -- --coverage \
111+
2>&1 | tee "${RUNNER_TEMP}/coverage-output.log"
112+
elif [ "${INPUTS_PACKAGE_MANAGER}" = "yarn" ]; then
113+
yarn run "${INPUTS_TEST_COMMAND}" --coverage 2>&1 | tee "${RUNNER_TEMP}/coverage-output.log"
114+
else
115+
npm run "${INPUTS_TEST_COMMAND}" -- --coverage 2>&1 | tee "${RUNNER_TEMP}/coverage-output.log"
116+
fi
117+
env:
118+
INPUTS_PACKAGE_MANAGER: ${{ inputs.package-manager }}
119+
INPUTS_TEST_COMMAND: ${{ inputs.test-command }}
120+
121+
# Posts (or updates in place) a single comment on the PR with the coverage tables
122+
# printed by the test runner's text reporter. Runs even when tests fail so the
123+
# result is still visible, and is skipped outside pull request events.
124+
- name: Comment coverage on PR
125+
if: >-
126+
always() &&
127+
github.event.pull_request.number &&
128+
(steps.coverage.outcome == 'success' || steps.coverage.outcome == 'failure')
129+
run: |
130+
marker="<!-- coverage-report:${INPUTS_COMMENT_ID} -->"
131+
log_file="${RUNNER_TEMP}/coverage-output.log"
132+
table_file="${RUNNER_TEMP}/coverage-table.txt"
133+
body_file="${RUNNER_TEMP}/coverage-comment.md"
134+
max_table_chars=60000
135+
136+
# Strip ANSI escape codes (colours, cursor show/hide, etc.), then keep only istanbul
137+
# text-reporter rows: the header, separators (5+ dash columns) and rows with four
138+
# numeric columns. Pipes in test names, diffs or console output don't match.
139+
# Nx stream output keeps its "project: " prefix on each row.
140+
sed -E 's/\x1b\[[0-9;?]*[ -/]*[@-~]//g' "$log_file" \
141+
| grep -E 'File +\| +% Stmts|-+(\|-+){4,}|\|( +[0-9.]+ +\|){4}' > "$table_file" || true
142+
143+
if [ "${COVERAGE_OUTCOME}" = "success" ]; then
144+
status="✅ Tests passed"
145+
else
146+
status="❌ Tests failed"
147+
fi
148+
149+
heading="### 📊 Coverage Report"
150+
if [ "${INPUTS_COMMENT_ID}" != "default" ]; then
151+
heading="${heading} (${INPUTS_COMMENT_ID})"
152+
fi
153+
154+
{
155+
echo "$marker"
156+
echo "$heading"
157+
echo
158+
echo "${status} for commit ${COMMIT_SHA}."
159+
echo
160+
if [ -s "$table_file" ]; then
161+
echo '```'
162+
if [ "$(wc -c < "$table_file")" -gt "$max_table_chars" ]; then
163+
# Cut on a line boundary: drop the last, partial line so the fence closes.
164+
head -c "$max_table_chars" "$table_file" | sed '$d'
165+
echo '```'
166+
echo
167+
echo "_Output truncated. See the [workflow run](${RUN_URL}) for the full report._"
168+
else
169+
cat "$table_file"
170+
echo '```'
171+
fi
172+
else
173+
echo "_No coverage table found in the test output. Ensure the \`text\` coverage reporter is enabled._"
174+
fi
175+
echo
176+
echo "[View workflow run](${RUN_URL})"
177+
} > "$body_file"
178+
179+
comment_id="$(gh api --paginate "repos/${REPO}/issues/${PR_NUMBER}/comments" \
180+
--jq ".[] | select(.body | startswith(\"${marker}\")) | .id" | head -n 1)"
181+
182+
if [ -n "$comment_id" ]; then
183+
gh api -X PATCH "repos/${REPO}/issues/comments/${comment_id}" -F body=@"$body_file"
184+
else
185+
gh api -X POST "repos/${REPO}/issues/${PR_NUMBER}/comments" -F body=@"$body_file"
186+
fi
187+
env:
188+
COMMIT_SHA: ${{ github.event.pull_request.head.sha }}
189+
COVERAGE_OUTCOME: ${{ steps.coverage.outcome }}
190+
GH_TOKEN: ${{ github.token }}
191+
INPUTS_COMMENT_ID: ${{ inputs.comment-id }}
192+
PR_NUMBER: ${{ github.event.pull_request.number }}
193+
REPO: ${{ github.repository }}
194+
RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}

‎README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ A collection of GitHub action workflows. Built using the [reusable workflows](ht
1212
| [AWS CDK](docs/aws-cdk.md) | Multi-environment infrastructure synthesis, diffs and deployments with automatic package manager detection |
1313
| [Changeset Check](docs/changeset-check.md) | Advisory PR comments when changesets are missing for affected packages |
1414
| [Changeset Release](docs/changeset-release.md) | Automated package versioning and publishing with Changesets |
15+
| [Coverage](docs/coverage.md) | Run tests with coverage and post the results as a PR comment, for Yarn and npm projects |
1516
| [Gadget App Deployment](docs/gadget-deploy.md) | Gadget app deployment with push and production deployment stages |
1617
| [Magento Cloud Deployment](docs/magento-cloud-deploy.md) | Magento Cloud deployment with optional NewRelic monitoring and CST reporting |
1718
| [Node Pull Request Checks](docs/node-pr.md) | Pull request quality checks for Node.js projects |

‎docs/coverage.md‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
# Coverage
2+
3+
Runs the test suite with coverage and posts the coverage tables as a comment on the pull request. The comment is updated in place on later runs instead of adding a new one.
4+
5+
#### **Inputs**
6+
| Name | Required | Type | Default | Description |
7+
|-----------------|----------|---------|---------|------------------------------------|
8+
| package-manager | ❌ | string | yarn | Node package manager to use (`yarn` or `npm`) |
9+
| is-yarn-classic | ❌ | boolean | false | When `package-manager` is `yarn`, indicates the project uses a pre-Berry version of Yarn, which changes the install flags |
10+
| node-version | ❌ | string | 24 | Node.js version to use when the repository has no `.nvmrc` file |
11+
| test-command | ❌ | string | test | Script (or Nx target) that runs the tests |
12+
| comment-id | ❌ | string | default | Identifies this workflow's PR comment. Use a different value per call when the workflow runs more than once on a PR (e.g. a matrix). Letters, digits, `.`, `_` and `-` only |
13+
14+
#### **Node.js version**
15+
16+
If the calling repository has an `.nvmrc` file at its root, the version in it is used. Otherwise `node-version` is used (24 by default).
17+
18+
#### **How tests are run**
19+
20+
- **Nx workspace** (`nx.json` present): `nx run-many -t <test-command> --skip-nx-cache --outputStyle=stream -- --coverage`, using `yarn nx` or `npx nx`.
21+
- **Yarn**: `yarn run <test-command> --coverage`
22+
- **npm**: `npm run <test-command> -- --coverage`
23+
24+
#### **PR comment**
25+
26+
The comment holds the coverage tables from the test output, so the test runner must print the `text` coverage reporter. Jest and Vitest both do this by default. Only table rows are kept (the header, separators and rows with four numeric columns), and other output is ignored. In an Nx workspace each row keeps its project-name prefix; when projects run in parallel their rows can be interleaved. Tables longer than 60,000 characters are truncated.
27+
28+
The comment is posted even when tests fail, and is skipped when the workflow isn't running for a pull request. Each `comment-id` has its own comment, which later runs update in place.
29+
30+
The calling job needs `pull-requests: write` permission. On pull requests from forks the token is read-only, so posting the comment fails.
31+
32+
#### Example Usage
33+
34+
**Yarn (default):**
35+
```yaml
36+
jobs:
37+
coverage:
38+
permissions:
39+
contents: read
40+
pull-requests: write
41+
uses: aligent/workflows/.github/workflows/coverage.yml@main
42+
```
43+
44+
**npm with a fallback Node.js version:**
45+
```yaml
46+
jobs:
47+
coverage:
48+
permissions:
49+
contents: read
50+
pull-requests: write
51+
uses: aligent/workflows/.github/workflows/coverage.yml@main
52+
with:
53+
package-manager: npm
54+
node-version: "22"
55+
```
56+
57+
**Several runs on one PR (one comment each):**
58+
```yaml
59+
jobs:
60+
coverage:
61+
strategy:
62+
matrix:
63+
suite: [unit, integration]
64+
permissions:
65+
contents: read
66+
pull-requests: write
67+
uses: aligent/workflows/.github/workflows/coverage.yml@main
68+
with:
69+
test-command: test:${{ matrix.suite }}
70+
comment-id: ${{ matrix.suite }}
71+
```

0 commit comments

Comments
 (0)