1
0
mirror of https://github.com/actions/cache.git synced 2026-08-05 19:02:14 +08:00

Compare commits

..

5 Commits

Author SHA1 Message Date
Rob Herley 387e18722e Update publish-immutable-actions.yml 2025-02-18 17:56:11 -05:00
Rob Herley 7dd70e632b Create publish-immutable-actions.yml 2025-02-18 17:54:10 -05:00
Rob Herley 58c1e461ab bump @actions/cache to v4.0.1 2025-02-14 13:34:41 -05:00
Bassem Dghaidi f4b3439a65 Add licensed output 2024-12-05 04:36:53 -08:00
Bassem Dghaidi 727965cba7 Prepare 3.4.0 release 2024-12-05 04:35:59 -08:00
128 changed files with 239746 additions and 326649 deletions
-22
View File
@@ -1,22 +0,0 @@
# To get started with Dependabot version updates, you'll need to specify which
# package ecosystems to update and where the package manifests are located.
# Please see the documentation for all configuration options:
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
groups:
minor-actions-dependencies:
update-types: [minor, patch]
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "daily"
allow:
- dependency-type: direct
- dependency-type: production
+1 -6
View File
@@ -1,4 +1,4 @@
name: Check dist content name: Check dist/
on: on:
push: push:
@@ -11,12 +11,7 @@ on:
- '**.md' - '**.md'
workflow_dispatch: workflow_dispatch:
permissions:
contents: read
jobs: jobs:
call-check-dist: call-check-dist:
name: Check dist/ name: Check dist/
uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main uses: actions/reusable-workflows/.github/workflows/check-dist.yml@main
with:
node-version: "24.x"
+1 -2
View File
@@ -1,5 +1,4 @@
name: Close inactive issues name: Close inactive issues
on: on:
schedule: schedule:
- cron: "30 8 * * *" - cron: "30 8 * * *"
@@ -11,7 +10,7 @@ jobs:
issues: write issues: write
pull-requests: write pull-requests: write
steps: steps:
- uses: actions/stale@v9 - uses: actions/stale@v3
with: with:
days-before-issue-stale: 200 days-before-issue-stale: 200
days-before-issue-close: 5 days-before-issue-close: 5
+10 -9
View File
@@ -1,4 +1,4 @@
name: Code scanning name: "Code scanning - action"
on: on:
push: push:
@@ -6,21 +6,22 @@ on:
schedule: schedule:
- cron: '0 19 * * 0' - cron: '0 19 * * 0'
permissions:
contents: read
security-events: write
jobs: jobs:
CodeQL-Build: CodeQL-Build:
# CodeQL runs on ubuntu-latest, windows-latest, and macos-latest # CodeQL runs on ubuntu-latest, windows-latest, and macos-latest
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
# required for all workflows
security-events: write
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v5 uses: actions/checkout@v3
# Initializes the CodeQL tools for scanning. # Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL - name: Initialize CodeQL
uses: github/codeql-action/init@v3 uses: github/codeql-action/init@v2
# Override language selection by uncommenting this and choosing your languages # Override language selection by uncommenting this and choosing your languages
# with: # with:
# languages: go, javascript, csharp, python, cpp, java, ruby # languages: go, javascript, csharp, python, cpp, java, ruby
@@ -28,7 +29,7 @@ jobs:
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java). # Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
# If this step fails, then you should remove it and run the build manually (see below). # If this step fails, then you should remove it and run the build manually (see below).
- name: Autobuild - name: Autobuild
uses: github/codeql-action/autobuild@v3 uses: github/codeql-action/autobuild@v2
# ️ Command-line programs to run using the OS shell. # ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun # 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
@@ -42,4 +43,4 @@ jobs:
# make release # make release
- name: Perform CodeQL Analysis - name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v3 uses: github/codeql-action/analyze@v2
+7 -12
View File
@@ -1,21 +1,16 @@
name: Assign issue name: Assign issue
on: on:
issues: issues:
types: [opened] types: [opened]
permissions:
issues: write
jobs: jobs:
run-action: run-action:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Get current oncall - name: Get current oncall
id: oncall id: oncall
run: | run: |
echo "CURRENT=$(curl --request GET 'https://api.pagerduty.com/oncalls?include[]=users&schedule_ids[]=P5VG2BX&earliest=true' --header 'Authorization: Token token=${{ secrets.PAGERDUTY_TOKEN }}' --header 'Accept: application/vnd.pagerduty+json;version=2' --header 'Content-Type: application/json' | jq -r '.oncalls[].user.name')" >> $GITHUB_OUTPUT echo "CURRENT=$(curl --request GET 'https://api.pagerduty.com/oncalls?include[]=users&schedule_ids[]=P5VG2BX&earliest=true' --header 'Authorization: Token token=${{ secrets.PAGERDUTY_TOKEN }}' --header 'Accept: application/vnd.pagerduty+json;version=2' --header 'Content-Type: application/json' | jq -r '.oncalls[].user.name')" >> $GITHUB_OUTPUT
- name: add_assignees - name: add_assignees
run: | run: |
curl -X POST -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN}}" https://api.github.com/repos/${{github.repository}}/issues/${{ github.event.issue.number}}/assignees -d '{"assignees":["${{steps.oncall.outputs.CURRENT}}"]}' curl -X POST -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN}}" https://api.github.com/repos/${{github.repository}}/issues/${{ github.event.issue.number}}/assignees -d '{"assignees":["${{steps.oncall.outputs.CURRENT}}"]}'
+4 -32
View File
@@ -1,4 +1,4 @@
name: License check name: Licensed
on: on:
push: push:
@@ -9,35 +9,7 @@ on:
- main - main
workflow_dispatch: workflow_dispatch:
permissions:
contents: read
jobs: jobs:
validate-cached-dependency-records: call-licensed:
runs-on: ubuntu-latest name: Licensed
name: Check licenses uses: actions/reusable-workflows/.github/workflows/licensed.yml@main
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Install dependencies
run: npm ci --ignore-scripts
- name: Set up Ruby
uses: ruby/setup-ruby@v1
with:
ruby-version: '3.1.7'
- name: Install licensed tool
run: |
cd "$RUNNER_TEMP"
curl -Lfs -o licensed.tar.gz https://github.com/licensee/licensed/archive/refs/tags/v5.0.4.tar.gz
tar -xzf licensed.tar.gz
cd licensed-5.0.4
bundle install
- name: Check cached dependency records
run: |
cd ${{ github.workspace }}
BUNDLE_GEMFILE=$RUNNER_TEMP/licensed-5.0.4/Gemfile bundle exec $RUNNER_TEMP/licensed-5.0.4/exe/licensed status
+11 -16
View File
@@ -1,25 +1,20 @@
name: Assign pull request reviewer name: Add Reviewer PR
on: on:
pull_request_target: pull_request_target:
types: [opened] types: [opened]
permissions:
pull-requests: write
jobs: jobs:
run-action: run-action:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Get current oncall - name: Get current oncall
id: oncall id: oncall
run: | run: |
echo "CURRENT=$(curl --request GET 'https://api.pagerduty.com/oncalls?include[]=users&schedule_ids[]=P5VG2BX&earliest=true' --header 'Authorization: Token token=${{ secrets.PAGERDUTY_TOKEN }}' --header 'Accept: application/vnd.pagerduty+json;version=2' --header 'Content-Type: application/json' | jq -r '.oncalls[].user.name')" >> $GITHUB_OUTPUT echo "CURRENT=$(curl --request GET 'https://api.pagerduty.com/oncalls?include[]=users&schedule_ids[]=P5VG2BX&earliest=true' --header 'Authorization: Token token=${{ secrets.PAGERDUTY_TOKEN }}' --header 'Accept: application/vnd.pagerduty+json;version=2' --header 'Content-Type: application/json' | jq -r '.oncalls[].user.name')" >> $GITHUB_OUTPUT
- name: Request Review - name: Request Review
run: | run: |
curl -X POST -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN}}" https://api.github.com/repos/${{github.repository}}/pulls/${{ github.event.pull_request.number}}/requested_reviewers -d '{"reviewers":["${{steps.oncall.outputs.CURRENT}}"]}' curl -X POST -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN}}" https://api.github.com/repos/${{github.repository}}/pulls/${{ github.event.pull_request.number}}/requested_reviewers -d '{"reviewers":["${{steps.oncall.outputs.CURRENT}}"]}'
- name: Add Assignee - name: Add Assignee
run: | run: |
curl -X POST -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN}}" https://api.github.com/repos/${{github.repository}}/issues/${{ github.event.pull_request.number}}/assignees -d '{"assignees":["${{steps.oncall.outputs.CURRENT}}"]}' curl -X POST -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.GITHUB_TOKEN}}" https://api.github.com/repos/${{github.repository}}/issues/${{ github.event.pull_request.number}}/assignees -d '{"assignees":["${{steps.oncall.outputs.CURRENT}}"]}'
@@ -1,20 +1,20 @@
name: Publish immutable action name: 'Publish Immutable Action Version'
on: on:
release: release:
types: [released] types: [released]
permissions:
contents: read
id-token: write
packages: write
jobs: jobs:
publish: publish:
runs-on: ubuntu-latest runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
packages: write
steps: steps:
- name: Checking out - name: Checking out
uses: actions/checkout@v5 uses: actions/checkout@v4
- name: Publish - name: Publish
id: publish id: publish
uses: actions/publish-immutable-action@0.0.3 uses: actions/publish-immutable-action@0.0.3
@@ -1,30 +0,0 @@
name: Release new action version
on:
release:
types: [released]
workflow_dispatch:
inputs:
TAG_NAME:
description: 'Tag name that the major tag will point to'
required: true
env:
TAG_NAME: ${{ github.event.inputs.TAG_NAME || github.event.release.tag_name }}
permissions:
contents: write
jobs:
update_tag:
name: Update the major tag to include the ${{ github.event.inputs.TAG_NAME || github.event.release.tag_name }} changes
environment:
name: releaseNewActionVersion
runs-on: ubuntu-latest
steps:
- name: Update the ${{ env.TAG_NAME }} tag
id: update-major-tag
uses: actions/publish-action@v0.3.0
with:
source-tag: ${{ env.TAG_NAME }}
slack-webhook: ${{ secrets.SLACK_WEBHOOK }}
+10 -157
View File
@@ -10,9 +10,6 @@ on:
- main - main
- releases/** - releases/**
permissions:
contents: read
jobs: jobs:
# Build and unit test # Build and unit test
build: build:
@@ -23,11 +20,11 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v3
- name: Setup Node.js 24.x - name: Setup Node.js 16.x
uses: actions/setup-node@v4 uses: actions/setup-node@v3
with: with:
node-version: 24.x node-version: 16.x
cache: npm cache: npm
- run: npm ci - run: npm ci
- name: Prettier Format Check - name: Prettier Format Check
@@ -46,7 +43,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v3
- name: Generate files in working directory - name: Generate files in working directory
shell: bash shell: bash
run: __tests__/create-cache-files.sh ${{ runner.os }} test-cache run: __tests__/create-cache-files.sh ${{ runner.os }} test-cache
@@ -60,7 +57,6 @@ jobs:
path: | path: |
test-cache test-cache
~/test-cache ~/test-cache
test-restore: test-restore:
needs: test-save needs: test-save
strategy: strategy:
@@ -70,7 +66,7 @@ jobs:
runs-on: ${{ matrix.os }} runs-on: ${{ matrix.os }}
steps: steps:
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v3
- name: Restore cache - name: Restore cache
uses: ./ uses: ./
with: with:
@@ -90,88 +86,17 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: ubuntu:latest image: ubuntu:latest
options: --cap-add=NET_ADMIN options: --dns 127.0.0.1
services: services:
squid-proxy: squid-proxy:
image: ubuntu/squid:latest image: ubuntu/squid:latest
ports: ports:
- 3128:3128 - 3128:3128
env: env:
http_proxy: http://squid-proxy:3128
https_proxy: http://squid-proxy:3128 https_proxy: http://squid-proxy:3128
steps: steps:
- name: Wait for proxy to be ready
shell: bash
run: |
echo "Waiting for squid proxy to be ready..."
echo "Resolving squid-proxy hostname:"
getent hosts squid-proxy || echo "DNS resolution failed"
for i in $(seq 1 30); do
if (echo > /dev/tcp/squid-proxy/3128) 2>/dev/null; then
echo "Proxy is ready!"
exit 0
fi
echo "Attempt $i: Proxy not ready, waiting..."
sleep 2
done
echo "Proxy failed to become ready"
exit 1
env:
http_proxy: ""
https_proxy: ""
- name: Install dependencies
run: |
apt-get update
apt-get install -y iptables curl
- name: Verify proxy is working
run: |
echo "Testing proxy connectivity..."
curl -s -o /dev/null -w "%{http_code}" --proxy http://squid-proxy:3128 http://github.com || true
echo "Proxy verification complete"
- name: Block direct traffic (enforce proxy usage)
run: |
# Get the squid-proxy container IP
PROXY_IP=$(getent hosts squid-proxy | awk '{ print $1 }')
echo "Proxy IP: $PROXY_IP"
# Allow loopback traffic
iptables -A OUTPUT -o lo -j ACCEPT
# Allow traffic to the proxy container
iptables -A OUTPUT -d $PROXY_IP -j ACCEPT
# Allow established connections
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow DNS (needed for initial resolution)
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
# Block all other outbound traffic (HTTP/HTTPS)
iptables -A OUTPUT -p tcp --dport 80 -j REJECT
iptables -A OUTPUT -p tcp --dport 443 -j REJECT
# Log the iptables rules for debugging
iptables -L -v -n
- name: Verify direct HTTPS is blocked
run: |
echo "Testing that direct HTTPS requests fail..."
if curl --noproxy '*' -s --connect-timeout 5 https://github.com > /dev/null 2>&1; then
echo "ERROR: Direct HTTPS request succeeded - blocking is not working!"
exit 1
else
echo "SUCCESS: Direct HTTPS request was blocked as expected"
fi
echo "Testing that HTTPS through proxy succeeds..."
if curl --proxy http://squid-proxy:3128 -s --connect-timeout 10 https://github.com > /dev/null 2>&1; then
echo "SUCCESS: HTTPS request through proxy succeeded"
else
echo "ERROR: HTTPS request through proxy failed!"
exit 1
fi
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v3
- name: Generate files - name: Generate files
run: __tests__/create-cache-files.sh proxy test-cache run: __tests__/create-cache-files.sh proxy test-cache
- name: Save cache - name: Save cache
@@ -179,94 +104,22 @@ jobs:
with: with:
key: test-proxy-${{ github.run_id }} key: test-proxy-${{ github.run_id }}
path: test-cache path: test-cache
test-proxy-restore: test-proxy-restore:
needs: test-proxy-save needs: test-proxy-save
runs-on: ubuntu-latest runs-on: ubuntu-latest
container: container:
image: ubuntu:latest image: ubuntu:latest
options: --cap-add=NET_ADMIN options: --dns 127.0.0.1
services: services:
squid-proxy: squid-proxy:
image: ubuntu/squid:latest image: ubuntu/squid:latest
ports: ports:
- 3128:3128 - 3128:3128
env: env:
http_proxy: http://squid-proxy:3128
https_proxy: http://squid-proxy:3128 https_proxy: http://squid-proxy:3128
steps: steps:
- name: Wait for proxy to be ready
shell: bash
run: |
echo "Waiting for squid proxy to be ready..."
echo "Resolving squid-proxy hostname:"
getent hosts squid-proxy || echo "DNS resolution failed"
for i in $(seq 1 30); do
if (echo > /dev/tcp/squid-proxy/3128) 2>/dev/null; then
echo "Proxy is ready!"
exit 0
fi
echo "Attempt $i: Proxy not ready, waiting..."
sleep 2
done
echo "Proxy failed to become ready"
exit 1
env:
http_proxy: ""
https_proxy: ""
- name: Install dependencies
run: |
apt-get update
apt-get install -y iptables curl
- name: Verify proxy is working
run: |
echo "Testing proxy connectivity..."
curl -s -o /dev/null -w "%{http_code}" --proxy http://squid-proxy:3128 http://github.com || true
echo "Proxy verification complete"
- name: Block direct traffic (enforce proxy usage)
run: |
# Get the squid-proxy container IP
PROXY_IP=$(getent hosts squid-proxy | awk '{ print $1 }')
echo "Proxy IP: $PROXY_IP"
# Allow loopback traffic
iptables -A OUTPUT -o lo -j ACCEPT
# Allow traffic to the proxy container
iptables -A OUTPUT -d $PROXY_IP -j ACCEPT
# Allow established connections
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow DNS (needed for initial resolution)
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
# Block all other outbound traffic (HTTP/HTTPS)
iptables -A OUTPUT -p tcp --dport 80 -j REJECT
iptables -A OUTPUT -p tcp --dport 443 -j REJECT
# Log the iptables rules for debugging
iptables -L -v -n
- name: Verify direct HTTPS is blocked
run: |
echo "Testing that direct HTTPS requests fail..."
if curl --noproxy '*' -s --connect-timeout 5 https://github.com > /dev/null 2>&1; then
echo "ERROR: Direct HTTPS request succeeded - blocking is not working!"
exit 1
else
echo "SUCCESS: Direct HTTPS request was blocked as expected"
fi
echo "Testing that HTTPS through proxy succeeds..."
if curl --proxy http://squid-proxy:3128 -s --connect-timeout 10 https://github.com > /dev/null 2>&1; then
echo "SUCCESS: HTTPS request through proxy succeeded"
else
echo "ERROR: HTTPS request through proxy failed!"
exit 1
fi
- name: Checkout - name: Checkout
uses: actions/checkout@v5 uses: actions/checkout@v3
- name: Restore cache - name: Restore cache
uses: ./ uses: ./
with: with:
-9
View File
@@ -1,14 +1,6 @@
sources: sources:
npm: true npm: true
# Force UTF-8 encoding
encoding: 'utf-8'
# Ignore problematic packages with encoding issues
ignored:
npm:
- form-data
allowed: allowed:
- apache-2.0 - apache-2.0
- bsd-2-clause - bsd-2-clause
@@ -28,4 +20,3 @@ reviewed:
- glob # ISC - glob # ISC
- prettier # MIT - prettier # MIT
- lodash # MIT - lodash # MIT
- "@actions/http-client" # MIT
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+1 -1
View File
@@ -16,7 +16,7 @@ Please note that this project is released with a [Contributor Code of Conduct][c
1. [Fork][fork] and clone the repository 1. [Fork][fork] and clone the repository
2. Configure and install the dependencies: `npm install` 2. Configure and install the dependencies: `npm install`
3. Make sure the tests pass on your machine: `npm run test` 3. Make sure the tests pass on your machine: `npm run test`
4. Create a new branch: `git switch -c my-branch-name` 4. Create a new branch: `git checkout -b my-branch-name`
5. Make your change, add tests, and make sure the tests still pass 5. Make your change, add tests, and make sure the tests still pass
6. Push to your fork and [submit a pull request][pr] 6. Push to your fork and [submit a pull request][pr]
7. Pat your self on the back and wait for your pull request to be reviewed and merged. 7. Pat your self on the back and wait for your pull request to be reviewed and merged.
+22 -61
View File
@@ -17,42 +17,20 @@ See ["Caching dependencies to speed up workflows"](https://docs.github.com/en/ac
### ⚠️ Important changes ### ⚠️ Important changes
> [!IMPORTANT]
> `actions/cache@v5` runs on the Node.js 24 runtime and requires a minimum Actions Runner version of `2.327.1`.
> If you are using self-hosted runners, ensure they are updated before upgrading.
The cache backend service has been rewritten from the ground up for improved performance and reliability. [actions/cache](https://github.com/actions/cache) now integrates with the new cache service (v2) APIs. The cache backend service has been rewritten from the ground up for improved performance and reliability. [actions/cache](https://github.com/actions/cache) now integrates with the new cache service (v2) APIs.
The new service will gradually roll out as of **February 1st, 2025**. The legacy service will also be sunset on the same date. Changes in these releases are **fully backward compatible**. The new service will gradually roll out as of **February 1st, 2025**. The legacy service will also be sunset on the same date. Changes in these release are **fully backward compatible**.
**We are deprecating some versions of this action**. We recommend upgrading to version `v4` or `v3` as soon as possible before **February 1st, 2025.** (Upgrade instructions below). **We are deprecating some versions of this action**. We recommend upgrading to version `v4` or `v3` as soon as possible before **February 1st, 2025.** (Upgrade instructions below).
If you are using pinned SHAs, please use the SHAs of versions `v4.2.0` or `v3.4.0`. If you are using pinned SHAs, please use the SHAs of versions `v4.2.0` or `v3.4.0`
If you do not upgrade, all workflow runs using any of the deprecated [actions/cache](https://github.com/actions/cache) will fail. If you do not upgrade, all workflow runs using any of the deprecated [actions/cache](https://github.com/actions/cache) will fail.
Upgrading to the recommended versions will not break your workflows. Upgrading to the recommended versions will not break your workflows.
> **Additionally, if you are managing your own GitHub runners, you must update your runner version to `2.231.0` or newer to ensure compatibility with the new cache service.**
> Failure to update both the action version and your runner version may result in workflow failures after the migration date.
Read more about the change & access the migration guide: [reference to the announcement](https://github.com/actions/cache/discussions/1510). Read more about the change & access the migration guide: [reference to the announcement](https://github.com/actions/cache/discussions/1510).
### v6
* Updated `@actions/cache`, `@actions/core`, `@actions/exec` to latest major versions
* Migrated to ESM module system
### v5
* Updated to node 24
* Requires a minimum Actions Runner version of `2.327.1`
### v4
* Integrated with the new cache service (v2) APIs.
* Updated to node 20
### v3 ### v3
* Integrated with the new cache service (v2) APIs. * Integrated with the new cache service (v2) APIs.
@@ -83,15 +61,13 @@ Create a workflow `.yml` file in your repository's `.github/workflows` directory
If you are using this inside a container, a POSIX-compliant `tar` needs to be included and accessible from the execution path. If you are using this inside a container, a POSIX-compliant `tar` needs to be included and accessible from the execution path.
Note: `actions/cache@v5` runs on Node.js 24 and requires a minimum Actions Runner version of `2.327.1`.
If you are using a `self-hosted` Windows runner, `GNU tar` and `zstd` are required for [Cross-OS caching](https://github.com/actions/cache/blob/main/tips-and-workarounds.md#cross-os-cache) to work. They are also recommended to be installed in general so the performance is on par with `hosted` Windows runners. If you are using a `self-hosted` Windows runner, `GNU tar` and `zstd` are required for [Cross-OS caching](https://github.com/actions/cache/blob/main/tips-and-workarounds.md#cross-os-cache) to work. They are also recommended to be installed in general so the performance is on par with `hosted` Windows runners.
### Inputs ### Inputs
* `key` - An explicit key for a cache entry. See [creating a cache key](#creating-a-cache-key). * `key` - An explicit key for a cache entry. See [creating a cache key](#creating-a-cache-key).
* `path` - A list of files, directories, and wildcard patterns to cache and restore. See [`@actions/glob`](https://github.com/actions/toolkit/tree/main/packages/glob) for supported patterns. * `path` - A list of files, directories, and wildcard patterns to cache and restore. See [`@actions/glob`](https://github.com/actions/toolkit/tree/main/packages/glob) for supported patterns.
* `restore-keys` - An ordered multiline string listing the prefix-matched keys, that are used for restoring stale cache if no cache hit occurred for key. * `restore-keys` - An ordered list of prefix-matched keys to use for restoring stale cache if no cache hit occurred for key.
* `enableCrossOsArchive` - An optional boolean when enabled, allows Windows runners to save or restore caches that can be restored or saved respectively on other platforms. Default: `false` * `enableCrossOsArchive` - An optional boolean when enabled, allows Windows runners to save or restore caches that can be restored or saved respectively on other platforms. Default: `false`
* `fail-on-cache-miss` - Fail the workflow if cache entry is not found. Default: `false` * `fail-on-cache-miss` - Fail the workflow if cache entry is not found. Default: `false`
* `lookup-only` - If true, only checks if cache entry exists and skips download. Does not change save cache behavior. Default: `false` * `lookup-only` - If true, only checks if cache entry exists and skips download. Does not change save cache behavior. Default: `false`
@@ -102,9 +78,9 @@ If you are using a `self-hosted` Windows runner, `GNU tar` and `zstd` are requir
### Outputs ### Outputs
* `cache-hit` - A string value to indicate an exact match was found for the key. * `cache-hit` - A boolean value to indicate an exact match was found for the key.
* If there's a cache hit, this will be 'true' or 'false' to indicate if there's an exact match for `key`.
* If there's a cache miss, this will be an empty string. > **Note** `cache-hit` will only be set to `true` when a cache hit occurs for the exact `key` match. For a partial key match via `restore-keys` or a cache miss, it will be set to `false`.
See [Skipping steps based on cache-hit](#skipping-steps-based-on-cache-hit) for info on using this output See [Skipping steps based on cache-hit](#skipping-steps-based-on-cache-hit) for info on using this output
@@ -128,11 +104,11 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- name: Cache Primes - name: Cache Primes
id: cache-primes id: cache-primes
uses: actions/cache@v6 uses: actions/cache@v3
with: with:
path: prime-numbers path: prime-numbers
key: ${{ runner.os }}-primes key: ${{ runner.os }}-primes
@@ -159,11 +135,11 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- name: Restore cached Primes - name: Restore cached Primes
id: cache-primes-restore id: cache-primes-restore
uses: actions/cache/restore@v6 uses: actions/cache/restore@v3
with: with:
path: | path: |
path/to/dependencies path/to/dependencies
@@ -174,7 +150,7 @@ jobs:
. .
- name: Save Primes - name: Save Primes
id: cache-primes-save id: cache-primes-save
uses: actions/cache/save@v6 uses: actions/cache/save@v3
with: with:
path: | path: |
path/to/dependencies path/to/dependencies
@@ -195,7 +171,6 @@ Every programming language and framework has its own way of caching.
See [Examples](examples.md) for a list of `actions/cache` implementations for use with: See [Examples](examples.md) for a list of `actions/cache` implementations for use with:
* [Bun](./examples.md#bun)
* [C# - NuGet](./examples.md#c---nuget) * [C# - NuGet](./examples.md#c---nuget)
* [Clojure - Lein Deps](./examples.md#clojure---lein-deps) * [Clojure - Lein Deps](./examples.md#clojure---lein-deps)
* [D - DUB](./examples.md#d---dub) * [D - DUB](./examples.md#d---dub)
@@ -229,7 +204,7 @@ A cache key can include any of the contexts, functions, literals, and operators
For example, using the [`hashFiles`](https://docs.github.com/en/actions/learn-github-actions/expressions#hashfiles) function allows you to create a new cache when dependencies change. For example, using the [`hashFiles`](https://docs.github.com/en/actions/learn-github-actions/expressions#hashfiles) function allows you to create a new cache when dependencies change.
```yaml ```yaml
- uses: actions/cache@v6 - uses: actions/cache@v3
with: with:
path: | path: |
path/to/dependencies path/to/dependencies
@@ -247,7 +222,7 @@ Additionally, you can use arbitrary command output in a cache key, such as a dat
echo "date=$(/bin/date -u "+%Y%m%d")" >> $GITHUB_OUTPUT echo "date=$(/bin/date -u "+%Y%m%d")" >> $GITHUB_OUTPUT
shell: bash shell: bash
- uses: actions/cache@v6 - uses: actions/cache@v3
with: with:
path: path/to/dependencies path: path/to/dependencies
key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ hashFiles('**/lockfiles') }} key: ${{ runner.os }}-${{ steps.get-date.outputs.date }}-${{ hashFiles('**/lockfiles') }}
@@ -267,9 +242,9 @@ Example:
```yaml ```yaml
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- uses: actions/cache@v6 - uses: actions/cache@v3
id: cache id: cache
with: with:
path: path/to/dependencies path: path/to/dependencies
@@ -297,11 +272,11 @@ jobs:
build-linux: build-linux:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- name: Cache Primes - name: Cache Primes
id: cache-primes id: cache-primes
uses: actions/cache@v6 uses: actions/cache@v3
with: with:
path: prime-numbers path: prime-numbers
key: primes key: primes
@@ -312,7 +287,7 @@ jobs:
- name: Cache Numbers - name: Cache Numbers
id: cache-numbers id: cache-numbers
uses: actions/cache@v6 uses: actions/cache@v3
with: with:
path: numbers path: numbers
key: primes key: primes
@@ -324,11 +299,11 @@ jobs:
build-windows: build-windows:
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- uses: actions/checkout@v6 - uses: actions/checkout@v3
- name: Cache Primes - name: Cache Primes
id: cache-primes id: cache-primes
uses: actions/cache@v6 uses: actions/cache@v3
with: with:
path: prime-numbers path: prime-numbers
key: primes key: primes
@@ -354,23 +329,9 @@ There are a number of community practices/workarounds to fulfill specific requir
Please note that Windows environment variables (like `%LocalAppData%`) will NOT be expanded by this action. Instead, prefer using `~` in your paths which will expand to the HOME directory. For example, instead of `%LocalAppData%`, use `~\AppData\Local`. For a list of supported default environment variables, see the [Learn GitHub Actions: Variables](https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables) page. Please note that Windows environment variables (like `%LocalAppData%`) will NOT be expanded by this action. Instead, prefer using `~` in your paths which will expand to the HOME directory. For example, instead of `%LocalAppData%`, use `~\AppData\Local`. For a list of supported default environment variables, see the [Learn GitHub Actions: Variables](https://docs.github.com/en/actions/learn-github-actions/variables#default-environment-variables) page.
## Note ## Contributing
Thank you for your interest in this GitHub repo, however, right now we are not taking contributions. We would love for you to contribute to `actions/cache`. Pull requests are welcome! Please see the [CONTRIBUTING.md](CONTRIBUTING.md) for more information.
We continue to focus our resources on strategic areas that help our customers be successful while making developers' lives easier. While GitHub Actions remains a key part of this vision, we are allocating resources towards other areas of Actions and are not taking contributions to this repository at this time. The GitHub public roadmap is the best place to follow along for any updates on features were working on and what stage theyre in.
We are taking the following steps to better direct requests related to GitHub Actions, including:
1. We will be directing questions and support requests to our [Community Discussions area](https://github.com/orgs/community/discussions/categories/actions)
2. High Priority bugs can be reported through Community Discussions or you can report these to our support team https://support.github.com/contact/bug-report.
3. Security Issues should be handled as per our [security.md](SECURITY.md).
We will still provide security updates for this project and fix major breaking changes during this time.
You are welcome to still raise bugs in this repo.
## License ## License
+61 -177
View File
@@ -1,162 +1,77 @@
# Releases # Releases
## How to prepare a release ### 3.0.0
> [!NOTE] - Updated minimum runner version support from node 12 -> node 16
> Relevant for maintainers with write access only.
1. Switch to a new branch from `main`. ### 3.0.1
1. Run `npm test` to ensure all tests are passing.
1. Update the version in [`package.json`](package.json).
1. Run `npm run build` to update the compiled files.
1. Update this [`RELEASES.md`](RELEASES.md) with the new version and changes in the `## Changelog` section.
1. Run `licensed cache` to update the license report.
1. Run `licensed status` and resolve any warnings by updating the [`.licensed.yml`](.licensed.yml) file with the exceptions.
1. Commit your changes and push your branch upstream.
1. Open a pull request against `main` and get it reviewed and merged.
1. Draft a new release https://github.com/actions/cache/releases use the same version number used in `package.json`
1. Create a new tag with the version number.
1. Auto generate release notes and update them to match the changes you made in `RELEASES.md`.
1. Toggle the set as the latest release option.
1. Publish the release.
1. Navigate to https://github.com/actions/cache/actions/workflows/release-new-action-version.yml
1. There should be a workflow run queued with the same version number.
1. Approve the run to publish the new version and update the major tags for this action.
## Changelog - Added support for caching from GHES 3.5.
- Fixed download issue for files > 2GB during restore.
### 6.0.0 ### 3.0.2
- Updated `@actions/cache` to ^6.0.1, `@actions/core` to ^3.0.1, `@actions/exec` to ^3.0.0, `@actions/io` to ^3.0.2 - Added support for dynamic cache size cap on GHES.
- Migrated to ESM module system
- Upgraded Jest to v30 and test infrastructure to be ESM compatible
### 5.0.4 ### 3.0.3
- Bump `minimatch` to v3.1.5 (fixes ReDoS via globstar patterns) - Fixed avoiding empty cache save when no files are available for caching. ([issue](https://github.com/actions/cache/issues/624))
- Bump `undici` to v6.24.1 (WebSocket decompression bomb protection, header validation fixes)
- Bump `fast-xml-parser` to v5.5.6
### 5.0.3 ### 3.0.4
- Bump `@actions/cache` to v5.0.5 (Resolves: https://github.com/actions/cache/security/dependabot/33) - Fixed tar creation error while trying to create tar with path as `~/` home folder on `ubuntu-latest`. ([issue](https://github.com/actions/cache/issues/689))
- Bump `@actions/core` to v2.0.3
### 5.0.2 ### 3.0.5
- Bump `@actions/cache` to v5.0.3 [#1692](https://github.com/actions/cache/pull/1692) - Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. ([PR](https://github.com/actions/cache/pull/834))
### 5.0.1 ### 3.0.6
- Update `@azure/storage-blob` to `^12.29.1` via `@actions/cache@5.0.1` [#1685](https://github.com/actions/cache/pull/1685) - Fixed [#809](https://github.com/actions/cache/issues/809) - zstd -d: no such file or directory error
- Fixed [#833](https://github.com/actions/cache/issues/833) - cache doesn't work with github workspace directory
### 5.0.0 ### 3.0.7
> [!IMPORTANT] - Fixed [#810](https://github.com/actions/cache/issues/810) - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour.
> `actions/cache@v5` runs on the Node.js 24 runtime and requires a minimum Actions Runner version of `2.327.1`.
> If you are using self-hosted runners, ensure they are updated before upgrading.
### 4.3.0 ### 3.0.8
- Bump `@actions/cache` to [v4.1.0](https://github.com/actions/toolkit/pull/2132) - Fix zstd not working for windows on gnu tar in issues [#888](https://github.com/actions/cache/issues/888) and [#891](https://github.com/actions/cache/issues/891).
- Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable `SEGMENT_DOWNLOAD_TIMEOUT_MINS`. Default is 60 minutes.
### 4.2.4 ### 3.0.9
- Bump `@actions/cache` to v4.0.5 - Enhanced the warning message for cache unavailablity in case of GHES.
### 4.2.3 ### 3.0.10
- Bump `@actions/cache` to v4.0.3 (obfuscates SAS token in debug logs for cache entries) - Fix a bug with sorting inputs.
- Update definition for restore-keys in README.md
### 4.2.2 ### 3.0.11
- Bump `@actions/cache` to v4.0.2 - Update toolkit version to 3.0.5 to include `@actions/core@^1.10.0`
- Update `@actions/cache` to use updated `saveState` and `setOutput` functions from `@actions/core@^1.10.0`
### 4.2.1 ### 3.1.0-beta.1
- Bump `@actions/cache` to v4.0.1 - Update `@actions/cache` on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. ([issue](https://github.com/actions/cache/issues/984))
### 4.2.0 ### 3.1.0-beta.2
TLDR; The cache backend service has been rewritten from the ground up for improved performance and reliability. [actions/cache](https://github.com/actions/cache) now integrates with the new cache service (v2) APIs. - Added support for fallback to gzip to restore old caches on windows.
The new service will gradually roll out as of **February 1st, 2025**. The legacy service will also be sunset on the same date. Changes in these release are **fully backward compatible**. ### 3.1.0-beta.3
**We are deprecating some versions of this action**. We recommend upgrading to version `v4` or `v3` as soon as possible before **February 1st, 2025.** (Upgrade instructions below). - Bug fixes for bsdtar fallback if gnutar not available and gzip fallback if cache saved using old cache action on windows.
If you are using pinned SHAs, please use the SHAs of versions `v4.2.0` or `v3.4.0` ### 3.2.0-beta.1
If you do not upgrade, all workflow runs using any of the deprecated [actions/cache](https://github.com/actions/cache) will fail. - Added two new actions - [restore](restore/action.yml) and [save](save/action.yml) for granular control on cache.
Upgrading to the recommended versions will not break your workflows. ### 3.2.0
### 4.1.2 - Released the two new actions - [restore](restore/action.yml) and [save](save/action.yml) for granular control on cache
- Add GitHub Enterprise Cloud instances hostname filters to inform API endpoint choices - [#1474](https://github.com/actions/cache/pull/1474)
- Security fix: Bump braces from 3.0.2 to 3.0.3 - [#1475](https://github.com/actions/cache/pull/1475)
### 4.1.1
- Restore original behavior of `cache-hit` output - [#1467](https://github.com/actions/cache/pull/1467)
### 4.1.0
- Ensure `cache-hit` output is set when a cache is missed - [#1404](https://github.com/actions/cache/pull/1404)
- Deprecate `save-always` input - [#1452](https://github.com/actions/cache/pull/1452)
### 4.0.2
- Fixed restore `fail-on-cache-miss` not working.
### 4.0.1
- Updated `isGhes` check
### 4.0.0
- Updated minimum runner version support from node 12 -> node 20
### 3.4.0
- Integrated with the new cache service (v2) APIs
### 3.3.3
- Updates @actions/cache to v3.2.3 to fix accidental mutated path arguments to `getCacheVersion` [actions/toolkit#1378](https://github.com/actions/toolkit/pull/1378)
- Additional audit fixes of npm package(s)
### 3.3.2
- Fixes bug with Azure SDK causing blob downloads to get stuck.
### 3.3.1
- Reduced segment size to 128MB and segment timeout to 10 minutes to fail fast in case the cache download is stuck.
### 3.3.0
- Added option to lookup cache without downloading it.
### 3.2.6
- Fix zstd not being used after zstd version upgrade to 1.5.4 on hosted runners.
### 3.2.5
- Added fix to prevent from setting MYSYS environment variable globally.
### 3.2.4
- Added option to fail job on cache miss.
### 3.2.3
- Support cross os caching on Windows as an opt-in feature.
- Fix issue with symlink restoration on Windows for cross-os caches.
### 3.2.2
- Reverted the changes made in 3.2.1 to use gnu tar and zstd by default on windows.
### 3.2.1 ### 3.2.1
@@ -164,75 +79,44 @@ Upgrading to the recommended versions will not break your workflows.
- Added support for fallback to gzip to restore old caches on windows. - Added support for fallback to gzip to restore old caches on windows.
- Added logs for cache version in case of a cache miss. - Added logs for cache version in case of a cache miss.
### 3.2.0 ### 3.2.2
- Released the two new actions - [restore](restore/action.yml) and [save](save/action.yml) for granular control on cache - Reverted the changes made in 3.2.1 to use gnu tar and zstd by default on windows.
### 3.2.0-beta.1 ### 3.2.3
- Added two new actions - [restore](restore/action.yml) and [save](save/action.yml) for granular control on cache. - Support cross os caching on Windows as an opt-in feature.
- Fix issue with symlink restoration on Windows for cross-os caches.
### 3.1.0-beta.3 ### 3.2.4
- Bug fixes for bsdtar fallback if gnutar not available and gzip fallback if cache saved using old cache action on windows. - Added option to fail job on cache miss.
### 3.1.0-beta.2 ### 3.2.5
- Added support for fallback to gzip to restore old caches on windows. - Added fix to prevent from setting MYSYS environment variable globally.
### 3.1.0-beta.1 ### 3.2.6
- Update `@actions/cache` on windows to use gnu tar and zstd by default and fallback to bsdtar and zstd if gnu tar is not available. ([issue](https://github.com/actions/cache/issues/984)) - Fix zstd not being used after zstd version upgrade to 1.5.4 on hosted runners.
### 3.0.11 ### 3.3.0
- Update toolkit version to 3.0.5 to include `@actions/core@^1.10.0` - Added option to lookup cache without downloading it.
- Update `@actions/cache` to use updated `saveState` and `setOutput` functions from `@actions/core@^1.10.0`
### 3.0.10 ### 3.3.1
- Fix a bug with sorting inputs. - Reduced segment size to 128MB and segment timeout to 10 minutes to fail fast in case the cache download is stuck.
- Update definition for restore-keys in README.md
### 3.0.9 ### 3.3.2
- Enhanced the warning message for cache unavailablity in case of GHES. - Fixes bug with Azure SDK causing blob downloads to get stuck.
### 3.0.8 ### 3.3.3
- Fix zstd not working for windows on gnu tar in issues [#888](https://github.com/actions/cache/issues/888) and [#891](https://github.com/actions/cache/issues/891). - Updates @actions/cache to v3.2.3 to fix accidental mutated path arguments to `getCacheVersion` [actions/toolkit#1378](https://github.com/actions/toolkit/pull/1378)
- Allowing users to provide a custom timeout as input for aborting download of a cache segment using an environment variable `SEGMENT_DOWNLOAD_TIMEOUT_MINS`. Default is 60 minutes. - Additional audit fixes of npm package(s)
### 3.0.7 ### 3.4.0
- Fixed [#810](https://github.com/actions/cache/issues/810) - download stuck issue. A new timeout is introduced in the download process to abort the download if it gets stuck and doesn't finish within an hour. - Integrated with the new cache service (v2) APIs
### 3.0.6
- Fixed [#809](https://github.com/actions/cache/issues/809) - zstd -d: no such file or directory error
- Fixed [#833](https://github.com/actions/cache/issues/833) - cache doesn't work with github workspace directory
### 3.0.5
- Removed error handling by consuming actions/cache 3.0 toolkit, Now cache server error handling will be done by toolkit. ([PR](https://github.com/actions/cache/pull/834))
### 3.0.4
- Fixed tar creation error while trying to create tar with path as `~/` home folder on `ubuntu-latest`. ([issue](https://github.com/actions/cache/issues/689))
### 3.0.3
- Fixed avoiding empty cache save when no files are available for caching. ([issue](https://github.com/actions/cache/issues/624))
### 3.0.2
- Added support for dynamic cache size cap on GHES.
### 3.0.1
- Added support for caching from GHES 3.5.
- Fixed download issue for files > 2GB during restore.
### 3.0.0
- Updated minimum runner version support from node 12 -> node 16
+66 -110
View File
@@ -1,72 +1,22 @@
import { afterAll, beforeEach, expect, jest, test } from "@jest/globals"; import * as cache from "@actions/cache";
import * as core from "@actions/core";
// Mock @actions/core import { Events, RefKey } from "../src/constants";
jest.unstable_mockModule("@actions/core", () => ({ import * as actionUtils from "../src/utils/actionUtils";
getInput: jest.fn((name: string, options?: { required?: boolean }) => { import * as testUtils from "../src/utils/testUtils";
const val =
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || "";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}),
setOutput: jest.fn(),
setFailed: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(() => ""),
isDebug: jest.fn(() => false),
exportVariable: jest.fn(),
addPath: jest.fn(),
group: jest.fn((name: string, fn: () => Promise<unknown>) => fn()),
startGroup: jest.fn(),
endGroup: jest.fn()
}));
// Mock @actions/cache jest.mock("@actions/core");
jest.unstable_mockModule("@actions/cache", () => ({ jest.mock("@actions/cache");
restoreCache: jest.fn(),
saveCache: jest.fn(),
isFeatureAvailable: jest.fn(() => true),
ReserveCacheError: class ReserveCacheError extends Error {
constructor(message: string) {
super(message);
this.name = "ReserveCacheError";
}
}
}));
const core = await import("@actions/core"); beforeAll(() => {
const cache = await import("@actions/cache"); jest.spyOn(core, "getInput").mockImplementation((name, options) => {
const { Events, RefKey } = await import("../src/constants"); return jest.requireActual("@actions/core").getInput(name, options);
const actionUtils = await import("../src/utils/actionUtils"); });
const testUtils = await import("../src/utils/testUtils");
let pristineEnv: NodeJS.ProcessEnv;
beforeEach(() => {
pristineEnv = { ...process.env };
jest.clearAllMocks();
jest.mocked(core.getInput).mockImplementation(
(name: string, options?: { required?: boolean }) => {
const val =
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] ||
"";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}
);
delete process.env[Events.Key];
delete process.env[RefKey];
}); });
afterAll(() => { afterEach(() => {
process.env = pristineEnv; delete process.env[Events.Key];
delete process.env[RefKey];
}); });
test("isGhes returns true if server url is not github.com", () => { test("isGhes returns true if server url is not github.com", () => {
@@ -88,46 +38,74 @@ test("isGhes returns false when server url is github.com", () => {
}); });
test("isExactKeyMatch with undefined cache key returns false", () => { test("isExactKeyMatch with undefined cache key returns false", () => {
expect(actionUtils.isExactKeyMatch("linux-rust", undefined)).toBe(false); const key = "linux-rust";
const cacheKey = undefined;
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
}); });
test("isExactKeyMatch with empty cache key returns false", () => { test("isExactKeyMatch with empty cache key returns false", () => {
expect(actionUtils.isExactKeyMatch("linux-rust", "")).toBe(false); const key = "linux-rust";
const cacheKey = "";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
}); });
test("isExactKeyMatch with different keys returns false", () => { test("isExactKeyMatch with different keys returns false", () => {
expect(actionUtils.isExactKeyMatch("linux-rust", "linux-")).toBe(false); const key = "linux-rust";
const cacheKey = "linux-";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
}); });
test("isExactKeyMatch with different key accents returns false", () => { test("isExactKeyMatch with different key accents returns false", () => {
expect(actionUtils.isExactKeyMatch("linux-áccent", "linux-accent")).toBe( const key = "linux-áccent";
false const cacheKey = "linux-accent";
);
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
}); });
test("isExactKeyMatch with same key returns true", () => { test("isExactKeyMatch with same key returns true", () => {
expect(actionUtils.isExactKeyMatch("linux-rust", "linux-rust")).toBe(true); const key = "linux-rust";
const cacheKey = "linux-rust";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(true);
}); });
test("isExactKeyMatch with same key and different casing returns true", () => { test("isExactKeyMatch with same key and different casing returns true", () => {
expect(actionUtils.isExactKeyMatch("linux-rust", "LINUX-RUST")).toBe(true); const key = "linux-rust";
const cacheKey = "LINUX-RUST";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(true);
}); });
test("logWarning logs a message with a warning prefix", () => { test("logWarning logs a message with a warning prefix", () => {
const message = "A warning occurred."; const message = "A warning occurred.";
const infoMock = jest.spyOn(core, "info");
actionUtils.logWarning(message); actionUtils.logWarning(message);
expect(core.info).toHaveBeenCalledWith(`[warning]${message}`);
expect(infoMock).toHaveBeenCalledWith(`[warning]${message}`);
}); });
test("isValidEvent returns false for event that does not have a branch or tag", () => { test("isValidEvent returns false for event that does not have a branch or tag", () => {
process.env[Events.Key] = "foo"; const event = "foo";
expect(actionUtils.isValidEvent()).toBe(false); process.env[Events.Key] = event;
const isValidEvent = actionUtils.isValidEvent();
expect(isValidEvent).toBe(false);
}); });
test("isValidEvent returns true for event that has a ref", () => { test("isValidEvent returns true for event that has a ref", () => {
process.env[Events.Key] = Events.Push; const event = Events.Push;
process.env[Events.Key] = event;
process.env[RefKey] = "ref/heads/feature"; process.env[RefKey] = "ref/heads/feature";
expect(actionUtils.isValidEvent()).toBe(true);
const isValidEvent = actionUtils.isValidEvent();
expect(isValidEvent).toBe(true);
}); });
test("getInputAsArray returns empty array if not required and missing", () => { test("getInputAsArray returns empty array if not required and missing", () => {
@@ -137,7 +115,7 @@ test("getInputAsArray returns empty array if not required and missing", () => {
test("getInputAsArray throws error if required and missing", () => { test("getInputAsArray throws error if required and missing", () => {
expect(() => expect(() =>
actionUtils.getInputAsArray("foo", { required: true }) actionUtils.getInputAsArray("foo", { required: true })
).toThrow(); ).toThrowError();
}); });
test("getInputAsArray handles single line correctly", () => { test("getInputAsArray handles single line correctly", () => {
@@ -193,7 +171,7 @@ test("getInputAsInt returns undefined if input is invalid or NaN", () => {
test("getInputAsInt throws if required and value missing", () => { test("getInputAsInt throws if required and value missing", () => {
expect(() => expect(() =>
actionUtils.getInputAsInt("undefined", { required: true }) actionUtils.getInputAsInt("undefined", { required: true })
).toThrow(); ).toThrowError();
}); });
test("getInputAsBool returns false if input not set", () => { test("getInputAsBool returns false if input not set", () => {
@@ -213,65 +191,43 @@ test("getInputAsBool returns false if input is invalid or NaN", () => {
test("getInputAsBool throws if required and value missing", () => { test("getInputAsBool throws if required and value missing", () => {
expect(() => expect(() =>
actionUtils.getInputAsBool("undefined2", { required: true }) actionUtils.getInputAsBool("undefined2", { required: true })
).toThrow(); ).toThrowError();
}); });
test("isCacheFeatureAvailable for ac enabled", () => { test("isCacheFeatureAvailable for ac enabled", () => {
jest.mocked(cache.isFeatureAvailable).mockReturnValue(true); jest.spyOn(cache, "isFeatureAvailable").mockImplementation(() => true);
expect(actionUtils.isCacheFeatureAvailable()).toBe(true); expect(actionUtils.isCacheFeatureAvailable()).toBe(true);
}); });
test("isCacheFeatureAvailable for ac disabled on GHES", () => { test("isCacheFeatureAvailable for ac disabled on GHES", () => {
jest.mocked(cache.isFeatureAvailable).mockReturnValue(false); jest.spyOn(cache, "isFeatureAvailable").mockImplementation(() => false);
const message = `Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not. const message = `Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.
Otherwise please upgrade to GHES version >= 3.5 and If you are also using Github Connect, please unretire the actions/cache namespace before upgrade (see https://docs.github.com/en/enterprise-server@3.5/admin/github-actions/managing-access-to-actions-from-githubcom/enabling-automatic-access-to-githubcom-actions-using-github-connect#automatic-retirement-of-namespaces-for-actions-accessed-on-githubcom)`; Otherwise please upgrade to GHES version >= 3.5 and If you are also using Github Connect, please unretire the actions/cache namespace before upgrade (see https://docs.github.com/en/enterprise-server@3.5/admin/github-actions/managing-access-to-actions-from-githubcom/enabling-automatic-access-to-githubcom-actions-using-github-connect#automatic-retirement-of-namespaces-for-actions-accessed-on-githubcom)`;
const infoMock = jest.spyOn(core, "info");
try { try {
process.env["GITHUB_SERVER_URL"] = "http://example.com"; process.env["GITHUB_SERVER_URL"] = "http://example.com";
expect(actionUtils.isCacheFeatureAvailable()).toBe(false); expect(actionUtils.isCacheFeatureAvailable()).toBe(false);
expect(core.info).toHaveBeenCalledWith(`[warning]${message}`); expect(infoMock).toHaveBeenCalledWith(`[warning]${message}`);
} finally { } finally {
delete process.env["GITHUB_SERVER_URL"]; delete process.env["GITHUB_SERVER_URL"];
} }
}); });
test("isCacheFeatureAvailable for ac disabled on dotcom", () => { test("isCacheFeatureAvailable for ac disabled on dotcom", () => {
jest.mocked(cache.isFeatureAvailable).mockReturnValue(false); jest.spyOn(cache, "isFeatureAvailable").mockImplementation(() => false);
const message = const message =
"An internal error has occurred in cache backend. Please check https://www.githubstatus.com/ for any ongoing issue in actions."; "An internal error has occurred in cache backend. Please check https://www.githubstatus.com/ for any ongoing issue in actions.";
const infoMock = jest.spyOn(core, "info");
try { try {
process.env["GITHUB_SERVER_URL"] = "http://github.com"; process.env["GITHUB_SERVER_URL"] = "http://github.com";
expect(actionUtils.isCacheFeatureAvailable()).toBe(false); expect(actionUtils.isCacheFeatureAvailable()).toBe(false);
expect(core.info).toHaveBeenCalledWith(`[warning]${message}`); expect(infoMock).toHaveBeenCalledWith(`[warning]${message}`);
} finally { } finally {
delete process.env["GITHUB_SERVER_URL"]; delete process.env["GITHUB_SERVER_URL"];
} }
}); });
test("isGhes returns false when the GITHUB_SERVER_URL environment variable is not defined", () => {
delete process.env["GITHUB_SERVER_URL"];
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns false when the GITHUB_SERVER_URL environment variable is set to github.com", () => {
process.env["GITHUB_SERVER_URL"] = "https://github.com";
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns false when the GITHUB_SERVER_URL environment variable is set to a GitHub Enterprise Cloud-style URL", () => {
process.env["GITHUB_SERVER_URL"] = "https://contoso.ghe.com";
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns false when the GITHUB_SERVER_URL environment variable has a .localhost suffix", () => {
process.env["GITHUB_SERVER_URL"] = "https://mock-github.localhost";
expect(actionUtils.isGhes()).toBeFalsy();
});
test("isGhes returns true when the GITHUB_SERVER_URL environment variable is set to some other URL", () => {
process.env["GITHUB_SERVER_URL"] = "https://src.onpremise.fabrikam.com";
expect(actionUtils.isGhes()).toBeTruthy();
});
+197 -110
View File
@@ -1,66 +1,50 @@
import { afterEach, beforeEach, expect, jest, test } from "@jest/globals"; import * as cache from "@actions/cache";
import * as core from "@actions/core";
// Mock @actions/core import { Events, RefKey } from "../src/constants";
jest.unstable_mockModule("@actions/core", () => ({ import { restoreRun } from "../src/restoreImpl";
getInput: jest.fn((name: string, options?: { required?: boolean }) => { import * as actionUtils from "../src/utils/actionUtils";
const val = import * as testUtils from "../src/utils/testUtils";
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || "";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}),
setOutput: jest.fn(),
setFailed: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(() => ""),
isDebug: jest.fn(() => false),
exportVariable: jest.fn(),
addPath: jest.fn(),
group: jest.fn((name: string, fn: () => Promise<unknown>) => fn()),
startGroup: jest.fn(),
endGroup: jest.fn()
}));
// Mock @actions/cache jest.mock("../src/utils/actionUtils");
jest.unstable_mockModule("@actions/cache", () => ({
restoreCache: jest.fn(),
saveCache: jest.fn(),
isFeatureAvailable: jest.fn(() => true),
ReserveCacheError: class ReserveCacheError extends Error {
constructor(message: string) {
super(message);
this.name = "ReserveCacheError";
}
}
}));
const core = await import("@actions/core"); beforeAll(() => {
const cache = await import("@actions/cache"); jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
const { Events, RefKey } = await import("../src/constants"); (key, cacheResult) => {
const { restoreRun } = await import("../src/restoreImpl"); const actualUtils = jest.requireActual("../src/utils/actionUtils");
const testUtils = await import("../src/utils/testUtils"); return actualUtils.isExactKeyMatch(key, cacheResult);
beforeEach(() => {
jest.clearAllMocks();
(core.getInput as jest.Mock).mockImplementation(
(name: string, options?: { required?: boolean }) => {
const val =
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] ||
"";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
} }
); );
(cache.isFeatureAvailable as jest.Mock).mockReturnValue(true);
jest.spyOn(actionUtils, "isValidEvent").mockImplementation(() => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.isValidEvent();
});
jest.spyOn(actionUtils, "getInputAsArray").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsArray(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsBool(name, options);
}
);
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push; process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch"; process.env[RefKey] = "refs/heads/feature-branch";
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => false);
jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => true
);
}); });
afterEach(() => { afterEach(() => {
@@ -78,12 +62,19 @@ test("restore with no cache found", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreRun(); await restoreRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(cache.restoreCache).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path], [path],
key, key,
[], [],
@@ -93,10 +84,12 @@ test("restore with no cache found", async () => {
false false
); );
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(core.saveState).toHaveBeenCalledTimes(1); expect(stateMock).toHaveBeenCalledTimes(1);
expect(core.setFailed).toHaveBeenCalledTimes(0);
expect(core.info).toHaveBeenCalledWith( expect(failedMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}` `Cache not found for input keys: ${key}`
); );
}); });
@@ -112,12 +105,19 @@ test("restore with restore keys and no cache found", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreRun(); await restoreRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(cache.restoreCache).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path], [path],
key, key,
[restoreKey], [restoreKey],
@@ -127,10 +127,12 @@ test("restore with restore keys and no cache found", async () => {
false false
); );
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(core.saveState).toHaveBeenCalledTimes(1); expect(stateMock).toHaveBeenCalledTimes(1);
expect(core.setFailed).toHaveBeenCalledTimes(0);
expect(core.info).toHaveBeenCalledWith( expect(failedMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}, ${restoreKey}` `Cache not found for input keys: ${key}, ${restoreKey}`
); );
}); });
@@ -144,12 +146,20 @@ test("restore with cache found for key", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(key); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(key);
});
await restoreRun(); await restoreRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(cache.restoreCache).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path], [path],
key, key,
[], [],
@@ -159,13 +169,15 @@ test("restore with cache found for key", async () => {
false false
); );
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(core.saveState).toHaveBeenCalledWith("CACHE_RESULT", key); expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", key);
expect(core.saveState).toHaveBeenCalledTimes(2); expect(stateMock).toHaveBeenCalledTimes(2);
expect(core.setOutput).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "true"); expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(core.info).toHaveBeenCalledWith(`Cache restored from key: ${key}`); expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(core.setFailed).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("restore with cache found for restore key", async () => { test("restore with cache found for restore key", async () => {
@@ -179,20 +191,39 @@ test("restore with cache found for restore key", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(restoreKey); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(restoreKey);
});
await restoreRun(); await restoreRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.saveState).toHaveBeenCalledWith("CACHE_RESULT", restoreKey); [path],
expect(core.saveState).toHaveBeenCalledTimes(2); key,
expect(core.setOutput).toHaveBeenCalledTimes(1); [restoreKey],
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "false"); {
expect(core.info).toHaveBeenCalledWith( lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", restoreKey);
expect(stateMock).toHaveBeenCalledTimes(2);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "false");
expect(infoMock).toHaveBeenCalledWith(
`Cache restored from key: ${restoreKey}` `Cache restored from key: ${restoreKey}`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("Fail restore when fail on cache miss is enabled and primary + restore keys not found", async () => { test("Fail restore when fail on cache miss is enabled and primary + restore keys not found", async () => {
@@ -206,17 +237,35 @@ test("Fail restore when fail on cache miss is enabled and primary + restore keys
failOnCacheMiss: true failOnCacheMiss: true
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined); const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreRun(); await restoreRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setOutput).toHaveBeenCalledTimes(0); [path],
expect(core.setFailed).toHaveBeenCalledWith( key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(0);
expect(failedMock).toHaveBeenCalledWith(
`Failed to restore cache entry. Exiting as fail-on-cache-miss is set. Input key: ${key}` `Failed to restore cache entry. Exiting as fail-on-cache-miss is set. Input key: ${key}`
); );
expect(core.setFailed).toHaveBeenCalledTimes(1); expect(failedMock).toHaveBeenCalledTimes(1);
}); });
test("restore when fail on cache miss is enabled and primary key doesn't match restored key", async () => { test("restore when fail on cache miss is enabled and primary key doesn't match restored key", async () => {
@@ -230,20 +279,40 @@ test("restore when fail on cache miss is enabled and primary key doesn't match r
failOnCacheMiss: true failOnCacheMiss: true
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(restoreKey); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(restoreKey);
});
await restoreRun(); await restoreRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.saveState).toHaveBeenCalledWith("CACHE_RESULT", restoreKey); [path],
expect(core.saveState).toHaveBeenCalledTimes(2); key,
expect(core.setOutput).toHaveBeenCalledTimes(1); [restoreKey],
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "false"); {
expect(core.info).toHaveBeenCalledWith( lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", restoreKey);
expect(stateMock).toHaveBeenCalledTimes(2);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "false");
expect(infoMock).toHaveBeenCalledWith(
`Cache restored from key: ${restoreKey}` `Cache restored from key: ${restoreKey}`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("restore with fail on cache miss disabled and no cache found", async () => { test("restore with fail on cache miss disabled and no cache found", async () => {
@@ -257,15 +326,33 @@ test("restore with fail on cache miss disabled and no cache found", async () =>
failOnCacheMiss: false failOnCacheMiss: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreRun(); await restoreRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.saveState).toHaveBeenCalledTimes(1); [path],
expect(core.info).toHaveBeenCalledWith( key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(stateMock).toHaveBeenCalledTimes(1);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}, ${restoreKey}` `Cache not found for input keys: ${key}, ${restoreKey}`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
+250 -158
View File
@@ -1,68 +1,51 @@
import { afterEach, beforeEach, expect, jest, test } from "@jest/globals"; import * as cache from "@actions/cache";
import * as core from "@actions/core";
// Mock @actions/core import { Events, Inputs, RefKey } from "../src/constants";
jest.unstable_mockModule("@actions/core", () => ({ import { restoreImpl } from "../src/restoreImpl";
getInput: jest.fn((name: string, options?: { required?: boolean }) => { import { StateProvider } from "../src/stateProvider";
const val = import * as actionUtils from "../src/utils/actionUtils";
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || ""; import * as testUtils from "../src/utils/testUtils";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}),
setOutput: jest.fn(),
setFailed: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(() => ""),
isDebug: jest.fn(() => false),
exportVariable: jest.fn(),
addPath: jest.fn(),
group: jest.fn((name: string, fn: () => Promise<unknown>) => fn()),
startGroup: jest.fn(),
endGroup: jest.fn()
}));
// Mock @actions/cache jest.mock("../src/utils/actionUtils");
jest.unstable_mockModule("@actions/cache", () => ({
restoreCache: jest.fn(),
saveCache: jest.fn(),
isFeatureAvailable: jest.fn(() => true),
ReserveCacheError: class ReserveCacheError extends Error {
constructor(message: string) {
super(message);
this.name = "ReserveCacheError";
}
}
}));
const core = await import("@actions/core"); beforeAll(() => {
const cache = await import("@actions/cache"); jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
const { Events, Inputs, RefKey } = await import("../src/constants"); (key, cacheResult) => {
const { restoreImpl } = await import("../src/restoreImpl"); const actualUtils = jest.requireActual("../src/utils/actionUtils");
const { StateProvider } = await import("../src/stateProvider"); return actualUtils.isExactKeyMatch(key, cacheResult);
const testUtils = await import("../src/utils/testUtils");
beforeEach(() => {
jest.clearAllMocks();
jest.mocked(core.getInput).mockImplementation(
(name: string, options?: { required?: boolean }) => {
const val =
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] ||
"";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
} }
); );
jest.mocked(core.getState).mockReturnValue("");
jest.mocked(cache.isFeatureAvailable).mockReturnValue(true); jest.spyOn(actionUtils, "isValidEvent").mockImplementation(() => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.isValidEvent();
});
jest.spyOn(actionUtils, "getInputAsArray").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsArray(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsBool(name, options);
}
);
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push; process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch"; process.env[RefKey] = "refs/heads/feature-branch";
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => false);
jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => true
);
}); });
afterEach(() => { afterEach(() => {
@@ -72,45 +55,52 @@ afterEach(() => {
}); });
test("restore with invalid event outputs warning", async () => { test("restore with invalid event outputs warning", async () => {
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const invalidEvent = "commit_comment"; const invalidEvent = "commit_comment";
process.env[Events.Key] = invalidEvent; process.env[Events.Key] = invalidEvent;
delete process.env[RefKey]; delete process.env[RefKey];
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(core.info).toHaveBeenCalledWith( expect(logWarningMock).toHaveBeenCalledWith(
`[warning]Event Validation Error: The event type ${invalidEvent} is not supported because it's not tied to a branch or tag ref.` `Event Validation Error: The event type ${invalidEvent} is not supported because it's not tied to a branch or tag ref.`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("restore without AC available should no-op", async () => { test("restore without AC available should no-op", async () => {
jest.mocked(cache.isFeatureAvailable).mockReturnValue(false); jest.spyOn(actionUtils, "isGhes").mockImplementation(() => false);
jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => false
);
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(0); expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(core.setOutput).toHaveBeenCalledTimes(1); expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "false"); expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "false");
}); });
test("restore on GHES without AC available should no-op", async () => { test("restore on GHES without AC available should no-op", async () => {
process.env["GITHUB_SERVER_URL"] = "https://my-ghes-server.com"; jest.spyOn(actionUtils, "isGhes").mockImplementation(() => true);
jest.mocked(cache.isFeatureAvailable).mockReturnValue(false); jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => false
);
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(0); expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(core.setOutput).toHaveBeenCalledTimes(1); expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "false"); expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "false");
expect(core.info).toHaveBeenCalledWith(
expect.stringContaining(
"Cache action is only supported on GHES version >= 3.5"
)
);
delete process.env["GITHUB_SERVER_URL"];
}); });
test("restore on GHES with AC available ", async () => { test("restore on GHES with AC available ", async () => {
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => true);
const path = "node_modules"; const path = "node_modules";
const key = "node-test"; const key = "node-test";
testUtils.setInputs({ testUtils.setInputs({
@@ -119,12 +109,20 @@ test("restore on GHES with AC available ", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockResolvedValue(key); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(key);
});
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(cache.restoreCache).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path], [path],
key, key,
[], [],
@@ -134,26 +132,32 @@ test("restore on GHES with AC available ", async () => {
false false
); );
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(core.setOutput).toHaveBeenCalledTimes(1); expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "true"); expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(core.info).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(infoMock).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("restore with no path should fail", async () => { test("restore with no path should fail", async () => {
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(0); expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(core.setFailed).not.toHaveBeenCalledWith( // this input isn't necessary for restore b/c tarball contains entries relative to workspace
expect(failedMock).not.toHaveBeenCalledWith(
"Input required and not supplied: path" "Input required and not supplied: path"
); );
}); });
test("restore with no key", async () => { test("restore with no key", async () => {
testUtils.setInput(Inputs.Path, "node_modules"); testUtils.setInput(Inputs.Path, "node_modules");
const failedMock = jest.spyOn(core, "setFailed");
const restoreCacheMock = jest.spyOn(cache, "restoreCache");
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(0); expect(restoreCacheMock).toHaveBeenCalledTimes(0);
expect(core.setFailed).toHaveBeenCalledWith( expect(failedMock).toHaveBeenCalledWith(
"Input required and not supplied: key" "Input required and not supplied: key"
); );
}); });
@@ -168,32 +172,46 @@ test("restore with too many keys should fail", async () => {
restoreKeys, restoreKeys,
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockRejectedValue( const failedMock = jest.spyOn(core, "setFailed");
new Error("Key Validation Error: Keys are limited to a maximum of 10.") const restoreCacheMock = jest.spyOn(cache, "restoreCache");
);
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.setFailed).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
restoreKeys,
{
lookupOnly: false
},
false
);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: Keys are limited to a maximum of 10.` `Key Validation Error: Keys are limited to a maximum of 10.`
); );
}); });
test("restore with large key should fail", async () => { test("restore with large key should fail", async () => {
const path = "node_modules"; const path = "node_modules";
const key = "foo".repeat(512); const key = "foo".repeat(512); // Over the 512 character limit
testUtils.setInputs({ testUtils.setInputs({
path: path, path: path,
key, key,
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockRejectedValue( const failedMock = jest.spyOn(core, "setFailed");
new Error( const restoreCacheMock = jest.spyOn(cache, "restoreCache");
`Key Validation Error: ${key} cannot be larger than 512 characters.`
)
);
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.setFailed).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: ${key} cannot be larger than 512 characters.` `Key Validation Error: ${key} cannot be larger than 512 characters.`
); );
}); });
@@ -206,12 +224,20 @@ test("restore with invalid key should fail", async () => {
key, key,
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockRejectedValue( const failedMock = jest.spyOn(core, "setFailed");
new Error(`Key Validation Error: ${key} cannot contain commas.`) const restoreCacheMock = jest.spyOn(cache, "restoreCache");
);
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.setFailed).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path],
key,
[],
{
lookupOnly: false
},
false
);
expect(failedMock).toHaveBeenCalledWith(
`Key Validation Error: ${key} cannot contain commas.` `Key Validation Error: ${key} cannot contain commas.`
); );
}); });
@@ -225,14 +251,32 @@ test("restore with no cache found", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockResolvedValue(undefined); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setFailed).toHaveBeenCalledTimes(0); [path],
expect(core.info).toHaveBeenCalledWith( key,
[],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(failedMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}` `Cache not found for input keys: ${key}`
); );
}); });
@@ -248,14 +292,32 @@ test("restore with restore keys and no cache found", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockResolvedValue(undefined); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setFailed).toHaveBeenCalledTimes(0); [path],
expect(core.info).toHaveBeenCalledWith( key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(failedMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}, ${restoreKey}` `Cache not found for input keys: ${key}, ${restoreKey}`
); );
}); });
@@ -269,16 +331,35 @@ test("restore with cache found for key", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockResolvedValue(key); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(key);
});
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setOutput).toHaveBeenCalledTimes(1); [path],
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "true"); key,
expect(core.info).toHaveBeenCalledWith(`Cache restored from key: ${key}`); [],
expect(core.setFailed).toHaveBeenCalledTimes(0); {
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(infoMock).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("restore with cache found for restore key", async () => { test("restore with cache found for restore key", async () => {
@@ -292,18 +373,36 @@ test("restore with cache found for restore key", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
jest.mocked(cache.restoreCache).mockResolvedValue(restoreKey); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(restoreKey);
});
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setOutput).toHaveBeenCalledTimes(1); [path],
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "false"); key,
expect(core.info).toHaveBeenCalledWith( [restoreKey],
{
lookupOnly: false
},
false
);
expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "false");
expect(infoMock).toHaveBeenCalledWith(
`Cache restored from key: ${restoreKey}` `Cache restored from key: ${restoreKey}`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("restore with lookup-only set", async () => { test("restore with lookup-only set", async () => {
@@ -315,12 +414,20 @@ test("restore with lookup-only set", async () => {
lookupOnly: true lookupOnly: true
}); });
jest.mocked(cache.restoreCache).mockResolvedValue(key); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const stateMock = jest.spyOn(core, "saveState");
const setCacheHitOutputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(key);
});
await restoreImpl(new StateProvider()); await restoreImpl(new StateProvider());
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(cache.restoreCache).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path], [path],
key, key,
[], [],
@@ -330,30 +437,15 @@ test("restore with lookup-only set", async () => {
false false
); );
expect(core.saveState).toHaveBeenCalledWith("CACHE_KEY", key); expect(stateMock).toHaveBeenCalledWith("CACHE_KEY", key);
expect(core.saveState).toHaveBeenCalledWith("CACHE_RESULT", key); expect(stateMock).toHaveBeenCalledWith("CACHE_RESULT", key);
expect(core.saveState).toHaveBeenCalledTimes(2); expect(stateMock).toHaveBeenCalledTimes(2);
expect(core.setOutput).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "true"); expect(setCacheHitOutputMock).toHaveBeenCalledTimes(1);
expect(core.info).toHaveBeenCalledWith( expect(setCacheHitOutputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(infoMock).toHaveBeenCalledWith(
`Cache found and can be restored from key: ${key}` `Cache found and can be restored from key: ${key}`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
});
test("restore failure with earlyExit should call process exit", async () => {
testUtils.setInput(Inputs.Path, "node_modules");
const processExitMock = jest
.spyOn(process, "exit")
// eslint-disable-next-line @typescript-eslint/no-explicit-any
.mockImplementation((() => {}) as any);
await restoreImpl(new StateProvider(), true);
expect(cache.restoreCache).toHaveBeenCalledTimes(0);
expect(core.setFailed).toHaveBeenCalledWith(
"Input required and not supplied: key"
);
expect(processExitMock).toHaveBeenCalledWith(1);
processExitMock.mockRestore();
}); });
+132 -86
View File
@@ -1,66 +1,51 @@
import { afterEach, beforeEach, expect, jest, test } from "@jest/globals"; import * as cache from "@actions/cache";
import * as core from "@actions/core";
// Mock @actions/core import { Events, RefKey } from "../src/constants";
jest.unstable_mockModule("@actions/core", () => ({ import { restoreOnlyRun } from "../src/restoreImpl";
getInput: jest.fn((name: string, options?: { required?: boolean }) => { import * as actionUtils from "../src/utils/actionUtils";
const val = import * as testUtils from "../src/utils/testUtils";
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || "";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}),
setOutput: jest.fn(),
setFailed: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(() => ""),
isDebug: jest.fn(() => false),
exportVariable: jest.fn(),
addPath: jest.fn(),
group: jest.fn((name: string, fn: () => Promise<unknown>) => fn()),
startGroup: jest.fn(),
endGroup: jest.fn()
}));
// Mock @actions/cache jest.mock("../src/utils/actionUtils");
jest.unstable_mockModule("@actions/cache", () => ({
restoreCache: jest.fn(),
saveCache: jest.fn(),
isFeatureAvailable: jest.fn(() => true),
ReserveCacheError: class ReserveCacheError extends Error {
constructor(message: string) {
super(message);
this.name = "ReserveCacheError";
}
}
}));
const core = await import("@actions/core"); beforeAll(() => {
const cache = await import("@actions/cache"); jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
const { Events, RefKey } = await import("../src/constants"); (key, cacheResult) => {
const { restoreOnlyRun } = await import("../src/restoreImpl"); const actualUtils = jest.requireActual("../src/utils/actionUtils");
const testUtils = await import("../src/utils/testUtils"); return actualUtils.isExactKeyMatch(key, cacheResult);
beforeEach(() => {
jest.clearAllMocks();
(core.getInput as jest.Mock).mockImplementation(
(name: string, options?: { required?: boolean }) => {
const val =
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] ||
"";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
} }
); );
(cache.isFeatureAvailable as jest.Mock).mockReturnValue(true);
jest.spyOn(actionUtils, "isValidEvent").mockImplementation(() => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.isValidEvent();
});
jest.spyOn(actionUtils, "getInputAsArray").mockImplementation(
(name, options) => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.getInputAsArray(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsBool(name, options);
}
);
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push; process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch"; process.env[RefKey] = "refs/heads/feature-branch";
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => false);
jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => true
);
}); });
afterEach(() => { afterEach(() => {
@@ -78,12 +63,19 @@ test("restore with no cache found", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const outputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreOnlyRun(); await restoreOnlyRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(cache.restoreCache).toHaveBeenCalledWith( expect(restoreCacheMock).toHaveBeenCalledWith(
[path], [path],
key, key,
[], [],
@@ -93,10 +85,11 @@ test("restore with no cache found", async () => {
false false
); );
expect(core.setOutput).toHaveBeenCalledWith("cache-primary-key", key); expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(core.setOutput).toHaveBeenCalledTimes(1); expect(outputMock).toHaveBeenCalledTimes(1);
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
expect(core.info).toHaveBeenCalledWith(
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}` `Cache not found for input keys: ${key}`
); );
}); });
@@ -112,14 +105,32 @@ test("restore with restore keys and no cache found", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(undefined); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const outputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(undefined);
});
await restoreOnlyRun(); await restoreOnlyRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-primary-key", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setFailed).toHaveBeenCalledTimes(0); [path],
expect(core.info).toHaveBeenCalledWith( key,
[restoreKey],
{
lookupOnly: false
},
false
);
expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(failedMock).toHaveBeenCalledTimes(0);
expect(infoMock).toHaveBeenCalledWith(
`Cache not found for input keys: ${key}, ${restoreKey}` `Cache not found for input keys: ${key}, ${restoreKey}`
); );
}); });
@@ -133,17 +144,36 @@ test("restore with cache found for key", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(key); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const outputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(key);
});
await restoreOnlyRun(); await restoreOnlyRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-primary-key", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "true"); [path],
expect(core.setOutput).toHaveBeenCalledWith("cache-matched-key", key); key,
expect(core.setOutput).toHaveBeenCalledTimes(3); [],
expect(core.info).toHaveBeenCalledWith(`Cache restored from key: ${key}`); {
expect(core.setFailed).toHaveBeenCalledTimes(0); lookupOnly: false
},
false
);
expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(outputMock).toHaveBeenCalledWith("cache-hit", "true");
expect(outputMock).toHaveBeenCalledWith("cache-matched-key", key);
expect(outputMock).toHaveBeenCalledTimes(3);
expect(infoMock).toHaveBeenCalledWith(`Cache restored from key: ${key}`);
expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("restore with cache found for restore key", async () => { test("restore with cache found for restore key", async () => {
@@ -157,20 +187,36 @@ test("restore with cache found for restore key", async () => {
enableCrossOsArchive: false enableCrossOsArchive: false
}); });
(cache.restoreCache as jest.Mock).mockResolvedValue(restoreKey); const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const outputMock = jest.spyOn(core, "setOutput");
const restoreCacheMock = jest
.spyOn(cache, "restoreCache")
.mockImplementationOnce(() => {
return Promise.resolve(restoreKey);
});
await restoreOnlyRun(); await restoreOnlyRun();
expect(cache.restoreCache).toHaveBeenCalledTimes(1); expect(restoreCacheMock).toHaveBeenCalledTimes(1);
expect(core.setOutput).toHaveBeenCalledWith("cache-primary-key", key); expect(restoreCacheMock).toHaveBeenCalledWith(
expect(core.setOutput).toHaveBeenCalledWith("cache-hit", "false"); [path],
expect(core.setOutput).toHaveBeenCalledWith( key,
"cache-matched-key", [restoreKey],
restoreKey {
lookupOnly: false
},
false
); );
expect(core.setOutput).toHaveBeenCalledTimes(3);
expect(core.info).toHaveBeenCalledWith( expect(outputMock).toHaveBeenCalledWith("cache-primary-key", key);
expect(outputMock).toHaveBeenCalledWith("cache-hit", "false");
expect(outputMock).toHaveBeenCalledWith("cache-matched-key", restoreKey);
expect(outputMock).toHaveBeenCalledTimes(3);
expect(infoMock).toHaveBeenCalledWith(
`Cache restored from key: ${restoreKey}` `Cache restored from key: ${restoreKey}`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
+79 -63
View File
@@ -1,66 +1,70 @@
import { afterEach, beforeEach, expect, jest, test } from "@jest/globals"; import * as cache from "@actions/cache";
import * as core from "@actions/core";
// Mock @actions/core import { Events, Inputs, RefKey } from "../src/constants";
jest.unstable_mockModule("@actions/core", () => ({ import run from "../src/save";
getInput: jest.fn((name: string, options?: { required?: boolean }) => { import * as actionUtils from "../src/utils/actionUtils";
const val = import * as testUtils from "../src/utils/testUtils";
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || "";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}),
setOutput: jest.fn(),
setFailed: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(() => ""),
isDebug: jest.fn(() => false),
exportVariable: jest.fn(),
addPath: jest.fn(),
group: jest.fn((name: string, fn: () => Promise<unknown>) => fn()),
startGroup: jest.fn(),
endGroup: jest.fn()
}));
// Mock @actions/cache jest.mock("@actions/core");
jest.unstable_mockModule("@actions/cache", () => ({ jest.mock("@actions/cache");
restoreCache: jest.fn(), jest.mock("../src/utils/actionUtils");
saveCache: jest.fn(),
isFeatureAvailable: jest.fn(() => true),
ReserveCacheError: class ReserveCacheError extends Error {
constructor(message: string) {
super(message);
this.name = "ReserveCacheError";
}
}
}));
const core = await import("@actions/core"); beforeAll(() => {
const cache = await import("@actions/cache"); jest.spyOn(core, "getInput").mockImplementation((name, options) => {
const { Events, Inputs, RefKey } = await import("../src/constants"); return jest.requireActual("@actions/core").getInput(name, options);
const { saveRun } = await import("../src/saveImpl"); });
const testUtils = await import("../src/utils/testUtils");
beforeEach(() => { jest.spyOn(core, "getState").mockImplementation(name => {
jest.clearAllMocks(); return jest.requireActual("@actions/core").getState(name);
(core.getInput as jest.Mock).mockImplementation( });
(name: string, options?: { required?: boolean }) => {
const val = jest.spyOn(actionUtils, "getInputAsArray").mockImplementation(
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || (name, options) => {
""; return jest
if (options && options.required && !val) { .requireActual("../src/utils/actionUtils")
throw new Error(`Input required and not supplied: ${name}`); .getInputAsArray(name, options);
}
return val.trim();
} }
); );
(cache.isFeatureAvailable as jest.Mock).mockReturnValue(true);
jest.spyOn(actionUtils, "getInputAsInt").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsInt(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsBool(name, options);
}
);
jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
(key, cacheResult) => {
return jest
.requireActual("../src/utils/actionUtils")
.isExactKeyMatch(key, cacheResult);
}
);
jest.spyOn(actionUtils, "isValidEvent").mockImplementation(() => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.isValidEvent();
});
});
beforeEach(() => {
process.env[Events.Key] = Events.Push; process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch"; process.env[RefKey] = "refs/heads/feature-branch";
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => false);
jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => true
);
}); });
afterEach(() => { afterEach(() => {
@@ -70,24 +74,36 @@ afterEach(() => {
}); });
test("save with valid inputs uploads a cache", async () => { test("save with valid inputs uploads a cache", async () => {
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = "Linux-node-"; const savedCacheKey = "Linux-node-";
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(savedCacheKey); .mockImplementationOnce(() => {
return primaryKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return savedCacheKey;
});
const inputPath = "node_modules"; const inputPath = "node_modules";
testUtils.setInput(Inputs.Path, inputPath); testUtils.setInput(Inputs.Path, inputPath);
testUtils.setInput(Inputs.UploadChunkSize, "4000000"); testUtils.setInput(Inputs.UploadChunkSize, "4000000");
const cacheId = 4; const cacheId = 4;
(cache.saveCache as jest.Mock).mockResolvedValue(cacheId); const saveCacheMock = jest
.spyOn(cache, "saveCache")
.mockImplementationOnce(() => {
return Promise.resolve(cacheId);
});
await saveRun(); await run();
expect(cache.saveCache).toHaveBeenCalledTimes(1); expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(cache.saveCache).toHaveBeenCalledWith( expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath], [inputPath],
primaryKey, primaryKey,
{ {
@@ -96,5 +112,5 @@ test("save with valid inputs uploads a cache", async () => {
false false
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
+270 -146
View File
@@ -1,68 +1,68 @@
import { afterEach, beforeEach, expect, jest, test } from "@jest/globals"; import * as cache from "@actions/cache";
import * as core from "@actions/core";
// Mock @actions/core import { Events, Inputs, RefKey } from "../src/constants";
jest.unstable_mockModule("@actions/core", () => ({ import run from "../src/saveImpl";
getInput: jest.fn((name: string, options?: { required?: boolean }) => { import { StateProvider } from "../src/stateProvider";
const val = import * as actionUtils from "../src/utils/actionUtils";
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] || ""; import * as testUtils from "../src/utils/testUtils";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
}),
setOutput: jest.fn(),
setFailed: jest.fn(),
info: jest.fn(),
warning: jest.fn(),
debug: jest.fn(),
error: jest.fn(),
saveState: jest.fn(),
getState: jest.fn(() => ""),
isDebug: jest.fn(() => false),
exportVariable: jest.fn(),
addPath: jest.fn(),
group: jest.fn((name: string, fn: () => Promise<unknown>) => fn()),
startGroup: jest.fn(),
endGroup: jest.fn()
}));
// Mock @actions/cache jest.mock("@actions/core");
jest.unstable_mockModule("@actions/cache", () => ({ jest.mock("@actions/cache");
restoreCache: jest.fn(), jest.mock("../src/utils/actionUtils");
saveCache: jest.fn(),
isFeatureAvailable: jest.fn(() => true),
ReserveCacheError: class ReserveCacheError extends Error {
constructor(message: string) {
super(message);
this.name = "ReserveCacheError";
}
}
}));
const core = await import("@actions/core"); beforeAll(() => {
const cache = await import("@actions/cache"); jest.spyOn(core, "getInput").mockImplementation((name, options) => {
const { Events, Inputs, RefKey } = await import("../src/constants"); return jest.requireActual("@actions/core").getInput(name, options);
const { saveImpl } = await import("../src/saveImpl"); });
const { StateProvider } = await import("../src/stateProvider");
const testUtils = await import("../src/utils/testUtils");
beforeEach(() => { jest.spyOn(actionUtils, "getInputAsArray").mockImplementation(
jest.clearAllMocks(); (name, options) => {
(core.getInput as jest.Mock).mockImplementation( return jest
(name: string, options?: { required?: boolean }) => { .requireActual("../src/utils/actionUtils")
const val = .getInputAsArray(name, options);
process.env[`INPUT_${name.replace(/ /g, "_").toUpperCase()}`] ||
"";
if (options && options.required && !val) {
throw new Error(`Input required and not supplied: ${name}`);
}
return val.trim();
} }
); );
(core.getState as jest.Mock).mockReturnValue("");
(cache.isFeatureAvailable as jest.Mock).mockReturnValue(true); jest.spyOn(actionUtils, "getInputAsInt").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsInt(name, options);
}
);
jest.spyOn(actionUtils, "getInputAsBool").mockImplementation(
(name, options) => {
return jest
.requireActual("../src/utils/actionUtils")
.getInputAsBool(name, options);
}
);
jest.spyOn(actionUtils, "isExactKeyMatch").mockImplementation(
(key, cacheResult) => {
return jest
.requireActual("../src/utils/actionUtils")
.isExactKeyMatch(key, cacheResult);
}
);
jest.spyOn(actionUtils, "isValidEvent").mockImplementation(() => {
const actualUtils = jest.requireActual("../src/utils/actionUtils");
return actualUtils.isValidEvent();
});
});
beforeEach(() => {
jest.restoreAllMocks();
process.env[Events.Key] = Events.Push; process.env[Events.Key] = Events.Push;
process.env[RefKey] = "refs/heads/feature-branch"; process.env[RefKey] = "refs/heads/feature-branch";
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => false);
jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => true
);
}); });
afterEach(() => { afterEach(() => {
@@ -72,69 +72,99 @@ afterEach(() => {
}); });
test("save with invalid event outputs warning", async () => { test("save with invalid event outputs warning", async () => {
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const invalidEvent = "commit_comment"; const invalidEvent = "commit_comment";
process.env[Events.Key] = invalidEvent; process.env[Events.Key] = invalidEvent;
delete process.env[RefKey]; delete process.env[RefKey];
await saveImpl(new StateProvider()); await run(new StateProvider());
expect(core.info).toHaveBeenCalledWith( expect(logWarningMock).toHaveBeenCalledWith(
`[warning]Event Validation Error: The event type ${invalidEvent} is not supported because it's not tied to a branch or tag ref.` `Event Validation Error: The event type ${invalidEvent} is not supported because it's not tied to a branch or tag ref.`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("save with no primary key in state outputs warning", async () => { test("save with no primary key in state outputs warning", async () => {
(core.getState as jest.Mock).mockReturnValue(""); const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
await saveImpl(new StateProvider()); const savedCacheKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
jest.spyOn(core, "getState")
// Cache Entry State
.mockImplementationOnce(() => {
return "";
})
// Cache Key State
.mockImplementationOnce(() => {
return savedCacheKey;
});
const saveCacheMock = jest.spyOn(cache, "saveCache");
expect(cache.saveCache).toHaveBeenCalledTimes(0); await run(new StateProvider());
expect(core.info).toHaveBeenCalledWith(`[warning]Key is not specified.`);
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(saveCacheMock).toHaveBeenCalledTimes(0);
expect(logWarningMock).toHaveBeenCalledWith(`Key is not specified.`);
expect(logWarningMock).toHaveBeenCalledTimes(1);
expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("save without AC available should no-op", async () => { test("save without AC available should no-op", async () => {
(cache.isFeatureAvailable as jest.Mock).mockReturnValue(false); jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => false
);
await saveImpl(new StateProvider()); const saveCacheMock = jest.spyOn(cache, "saveCache");
expect(cache.saveCache).toHaveBeenCalledTimes(0); await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(0);
}); });
test("save on ghes without AC available should no-op", async () => { test("save on ghes without AC available should no-op", async () => {
process.env["GITHUB_SERVER_URL"] = "https://my-ghes-server.com"; jest.spyOn(actionUtils, "isGhes").mockImplementation(() => true);
(cache.isFeatureAvailable as jest.Mock).mockReturnValue(false); jest.spyOn(actionUtils, "isCacheFeatureAvailable").mockImplementation(
() => false
await saveImpl(new StateProvider());
expect(cache.saveCache).toHaveBeenCalledTimes(0);
expect(core.info).toHaveBeenCalledWith(
expect.stringContaining(
"Cache action is only supported on GHES version >= 3.5"
)
); );
delete process.env["GITHUB_SERVER_URL"]; const saveCacheMock = jest.spyOn(cache, "saveCache");
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(0);
}); });
test("save on GHES with AC available", async () => { test("save on GHES with AC available", async () => {
jest.spyOn(actionUtils, "isGhes").mockImplementation(() => true);
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = "Linux-node-"; const savedCacheKey = "Linux-node-";
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(savedCacheKey); .mockImplementationOnce(() => {
return savedCacheKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return primaryKey;
});
const inputPath = "node_modules"; const inputPath = "node_modules";
testUtils.setInput(Inputs.Path, inputPath); testUtils.setInput(Inputs.Path, inputPath);
testUtils.setInput(Inputs.UploadChunkSize, "4000000"); testUtils.setInput(Inputs.UploadChunkSize, "4000000");
const cacheId = 4; const cacheId = 4;
(cache.saveCache as jest.Mock).mockResolvedValue(cacheId); const saveCacheMock = jest
.spyOn(cache, "saveCache")
.mockImplementationOnce(() => {
return Promise.resolve(cacheId);
});
await saveImpl(new StateProvider()); await run(new StateProvider());
expect(cache.saveCache).toHaveBeenCalledTimes(1); expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(cache.saveCache).toHaveBeenCalledWith( expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath], [inputPath],
primaryKey, primaryKey,
{ {
@@ -143,135 +173,229 @@ test("save on GHES with AC available", async () => {
false false
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("save with exact match returns early", async () => { test("save with exact match returns early", async () => {
const infoMock = jest.spyOn(core, "info");
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = primaryKey;
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(primaryKey); .mockImplementationOnce(() => {
return savedCacheKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return primaryKey;
});
const saveCacheMock = jest.spyOn(cache, "saveCache");
await saveImpl(new StateProvider()); await run(new StateProvider());
expect(cache.saveCache).toHaveBeenCalledTimes(0); expect(saveCacheMock).toHaveBeenCalledTimes(0);
expect(core.info).toHaveBeenCalledWith( expect(infoMock).toHaveBeenCalledWith(
`Cache hit occurred on the primary key ${primaryKey}, not saving cache.` `Cache hit occurred on the primary key ${primaryKey}, not saving cache.`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("save with missing input outputs warning", async () => { test("save with missing input outputs warning", async () => {
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = "Linux-node-"; const savedCacheKey = "Linux-node-";
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(savedCacheKey); .mockImplementationOnce(() => {
return savedCacheKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return primaryKey;
});
const saveCacheMock = jest.spyOn(cache, "saveCache");
await saveImpl(new StateProvider()); await run(new StateProvider());
expect(cache.saveCache).toHaveBeenCalledTimes(0); expect(saveCacheMock).toHaveBeenCalledTimes(0);
expect(core.info).toHaveBeenCalledWith( expect(logWarningMock).toHaveBeenCalledWith(
"[warning]Input required and not supplied: path" "Input required and not supplied: path"
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(logWarningMock).toHaveBeenCalledTimes(1);
expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("save with large cache outputs warning", async () => { test("save with large cache outputs warning", async () => {
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = "Linux-node-"; const savedCacheKey = "Linux-node-";
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(savedCacheKey); .mockImplementationOnce(() => {
return savedCacheKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return primaryKey;
});
const inputPath = "node_modules"; const inputPath = "node_modules";
testUtils.setInput(Inputs.Path, inputPath); testUtils.setInput(Inputs.Path, inputPath);
(cache.saveCache as jest.Mock).mockRejectedValue( const saveCacheMock = jest
new Error( .spyOn(cache, "saveCache")
"Cache size of ~6144 MB (6442450944 B) is over the 5GB limit, not saving cache." .mockImplementationOnce(() => {
) throw new Error(
"Cache size of ~6144 MB (6442450944 B) is over the 5GB limit, not saving cache."
);
});
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
expect.anything(),
false
); );
await saveImpl(new StateProvider()); expect(logWarningMock).toHaveBeenCalledTimes(1);
expect(logWarningMock).toHaveBeenCalledWith(
expect(cache.saveCache).toHaveBeenCalledTimes(1); "Cache size of ~6144 MB (6442450944 B) is over the 5GB limit, not saving cache."
expect(core.info).toHaveBeenCalledWith(
"[warning]Cache size of ~6144 MB (6442450944 B) is over the 5GB limit, not saving cache."
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("save with reserve cache failure outputs warning", async () => { test("save with reserve cache failure outputs warning", async () => {
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = "Linux-node-"; const savedCacheKey = "Linux-node-";
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(savedCacheKey); .mockImplementationOnce(() => {
return savedCacheKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return primaryKey;
});
const inputPath = "node_modules"; const inputPath = "node_modules";
testUtils.setInput(Inputs.Path, inputPath); testUtils.setInput(Inputs.Path, inputPath);
(cache.saveCache as jest.Mock).mockRejectedValue( const saveCacheMock = jest
new Error( .spyOn(cache, "saveCache")
`Unable to reserve cache with key ${primaryKey}, another job may be creating this cache.` .mockImplementationOnce(() => {
) const actualCache = jest.requireActual("@actions/cache");
const error = new actualCache.ReserveCacheError(
`Unable to reserve cache with key ${primaryKey}, another job may be creating this cache.`
);
throw error;
});
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
expect.anything(),
false
); );
await saveImpl(new StateProvider()); expect(logWarningMock).toHaveBeenCalledWith(
`Unable to reserve cache with key ${primaryKey}, another job may be creating this cache.`
expect(cache.saveCache).toHaveBeenCalledTimes(1);
expect(core.info).toHaveBeenCalledWith(
`[warning]Unable to reserve cache with key ${primaryKey}, another job may be creating this cache.`
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(logWarningMock).toHaveBeenCalledTimes(1);
expect(failedMock).toHaveBeenCalledTimes(0);
}); });
test("save with server error outputs warning", async () => { test("save with server error outputs warning", async () => {
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = "Linux-node-"; const savedCacheKey = "Linux-node-";
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(savedCacheKey); .mockImplementationOnce(() => {
return savedCacheKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return primaryKey;
});
const inputPath = "node_modules"; const inputPath = "node_modules";
testUtils.setInput(Inputs.Path, inputPath); testUtils.setInput(Inputs.Path, inputPath);
(cache.saveCache as jest.Mock).mockRejectedValue( const saveCacheMock = jest
new Error("HTTP Error Occurred") .spyOn(cache, "saveCache")
.mockImplementationOnce(() => {
throw new Error("HTTP Error Occurred");
});
await run(new StateProvider());
expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath],
primaryKey,
expect.anything(),
false
); );
await saveImpl(new StateProvider()); expect(logWarningMock).toHaveBeenCalledTimes(1);
expect(logWarningMock).toHaveBeenCalledWith("HTTP Error Occurred");
expect(cache.saveCache).toHaveBeenCalledTimes(1); expect(failedMock).toHaveBeenCalledTimes(0);
expect(core.info).toHaveBeenCalledWith("[warning]HTTP Error Occurred");
expect(core.setFailed).toHaveBeenCalledTimes(0);
}); });
test("save with valid inputs uploads a cache", async () => { test("save with valid inputs uploads a cache", async () => {
const failedMock = jest.spyOn(core, "setFailed");
const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43"; const primaryKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
const savedCacheKey = "Linux-node-"; const savedCacheKey = "Linux-node-";
(core.getState as jest.Mock) jest.spyOn(core, "getState")
.mockReturnValueOnce(primaryKey) // Cache Entry State
.mockReturnValueOnce(savedCacheKey); .mockImplementationOnce(() => {
return savedCacheKey;
})
// Cache Key State
.mockImplementationOnce(() => {
return primaryKey;
});
const inputPath = "node_modules"; const inputPath = "node_modules";
testUtils.setInput(Inputs.Path, inputPath); testUtils.setInput(Inputs.Path, inputPath);
testUtils.setInput(Inputs.UploadChunkSize, "4000000"); testUtils.setInput(Inputs.UploadChunkSize, "4000000");
const cacheId = 4; const cacheId = 4;
(cache.saveCache as jest.Mock).mockResolvedValue(cacheId); const saveCacheMock = jest
.spyOn(cache, "saveCache")
.mockImplementationOnce(() => {
return Promise.resolve(cacheId);
});
await saveImpl(new StateProvider()); await run(new StateProvider());
expect(cache.saveCache).toHaveBeenCalledTimes(1); expect(saveCacheMock).toHaveBeenCalledTimes(1);
expect(cache.saveCache).toHaveBeenCalledWith( expect(saveCacheMock).toHaveBeenCalledWith(
[inputPath], [inputPath],
primaryKey, primaryKey,
{ {
@@ -280,5 +404,5 @@ test("save with valid inputs uploads a cache", async () => {
false false
); );
expect(core.setFailed).toHaveBeenCalledTimes(0); expect(failedMock).toHaveBeenCalledTimes(0);
}); });

Some files were not shown because too many files have changed in this diff Show More