3
0
Fork 0
mirror of https://code.forgejo.org/actions/cache.git synced 2025-04-30 15:15:52 +00:00

Update tests for deleteCacheByKey.

And rebuild.

Signed-off-by: Gregorio Litenstein <g.litenstein@gmail.com>
This commit is contained in:
Gregorio Litenstein 2025-02-03 15:19:55 -03:00
parent 0417c21165
commit da1b6c90c6
No known key found for this signature in database
GPG key ID: 4EB52A1A9CE2C63F
8 changed files with 314 additions and 1580 deletions

View file

@ -1,6 +1,5 @@
import * as cache from "@actions/cache";
import * as core from "@actions/core";
import { RequestError } from "@octokit/request-error";
import nock from "nock";
import { Events, RefKey } from "../src/constants";
@ -214,7 +213,7 @@ test("getInputAsBool throws if required and value missing", () => {
).toThrowError();
});
test("deleteCacheByKey returns 'HttpError: 404' when cache is not found.", async () => {
test("deleteCacheByKey produces 'HttpError: 404' when cache is not found.", async () => {
const event = Events.Push;
process.env["GITHUB_REPOSITORY"] = "owner/repo";
@ -232,14 +231,73 @@ test("deleteCacheByKey returns 'HttpError: 404' when cache is not found.", async
expect(logWarningMock).toHaveBeenCalledWith(
expect.stringMatching(/404: Not Found/i)
);
expect(response).toBeInstanceOf(RequestError);
expect(response).toMatchObject({
name: "HttpError",
status: 404
});
expect(response).toBe(undefined);
});
test("deleteCacheByKey returns 'HttpError: 401' on an invalid non-mocked request.", async () => {
test("deleteCacheByKey does not delete anything if it finds more than one entry for the given key.", async () => {
const event = Events.Push;
process.env["GITHUB_REPOSITORY"] = "owner/repo";
process.env["GITHUB_TOKEN"] =
"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";
process.env["GITHUB_ACTION"] = "__owner___run-repo";
process.env[Events.Key] = event;
process.env[RefKey] = "";
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const response = await actionUtils.deleteCacheByKey(
testUtils.failureCacheKey,
"owner",
"repo"
);
expect(logWarningMock).toHaveBeenCalledWith(
`More than one cache entry found for key ${testUtils.failureCacheKey}`
);
expect(response).toBe(undefined);
});
test("deleteCacheByKey does not delete anything if the key matches a cache belonging to another ref.", async () => {
const event = Events.Push;
process.env["GITHUB_REPOSITORY"] = "owner/repo";
process.env["GITHUB_TOKEN"] =
"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";
process.env["GITHUB_ACTION"] = "__owner___run-repo";
process.env[Events.Key] = event;
process.env[RefKey] = "ref/heads/feature";
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const response = await actionUtils.deleteCacheByKey(
testUtils.wrongRefCacheKey,
"owner",
"repo"
);
expect(logWarningMock).toHaveBeenCalledWith(
`No cache entries for key ${testUtils.wrongRefCacheKey} belong to gitref ${process.env[RefKey]}.`
);
expect(response).toBe(undefined);
});
test("deleteCacheByKey produces 'HttpError: 404' when cache is not found.", async () => {
const event = Events.Push;
process.env["GITHUB_REPOSITORY"] = "owner/repo";
process.env["GITHUB_TOKEN"] =
"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";
process.env["GITHUB_ACTION"] = "__owner___run-repo";
process.env[Events.Key] = event;
process.env[RefKey] = "ref/heads/feature";
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const response = await actionUtils.deleteCacheByKey(
testUtils.failureCacheKey,
"owner",
"repo"
);
expect(logWarningMock).toHaveBeenCalledWith(
expect.stringMatching(/404: Not Found/i)
);
expect(response).toBe(undefined);
});
test("deleteCacheByKey produces 'HttpError: 401' on an invalid non-mocked request.", async () => {
const event = Events.Push;
process.env["GITHUB_REPOSITORY"] = "owner/repo";
@ -258,15 +316,11 @@ test("deleteCacheByKey returns 'HttpError: 401' on an invalid non-mocked request
expect(logWarningMock).toHaveBeenCalledWith(
expect.stringMatching(/401: Bad Credentials/i)
);
expect(response).toBeInstanceOf(RequestError);
expect(response).toMatchObject({
name: "HttpError",
status: 401
});
expect(response).toBe(undefined);
nock.disableNetConnect();
});
test("deleteCacheByKey returns matched cache data when successful.", async () => {
test("deleteCacheByKey returns 204 / No Content when successful.", async () => {
const event = Events.Push;
process.env["GITHUB_REPOSITORY"] = "owner/repo";
@ -276,29 +330,13 @@ test("deleteCacheByKey returns matched cache data when successful.", async () =>
process.env[Events.Key] = event;
process.env[RefKey] = "ref/heads/feature";
const expectedResponse = {
id: expect.any(Number),
ref: expect.any(String),
key: expect.any(String),
version: expect.any(String),
last_accessed_at: expect.any(String),
created_at: expect.any(String),
size_in_bytes: expect.any(Number)
};
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const response = await actionUtils.deleteCacheByKey(
testUtils.successCacheKey,
"owner",
"repo"
);
expect(response).toMatchObject({
data: expect.objectContaining({
total_count: expect.any(Number),
actions_caches: expect.arrayContaining([
expect.objectContaining(expectedResponse)
])
})
});
expect(response).toBe(204);
expect(logWarningMock).toHaveBeenCalledTimes(0);
});

View file

@ -492,7 +492,11 @@ test("save with cache hit and refresh-cache will try to delete and re-create ent
);
expect(infoMock).toHaveBeenNthCalledWith(
2,
`Succesfully deleted cache with key: ${primaryKey}`
expect.stringMatching(
new RegExp(
`Succesfully deleted cache with key: ${primaryKey}, id: \\d+`
)
)
);
expect(infoMock).toHaveBeenNthCalledWith(
3,
@ -565,7 +569,11 @@ test("Granular save will use lookup to determine if cache needs to be updated or
);
expect(infoMock).toHaveBeenNthCalledWith(
2,
`Succesfully deleted cache with key: ${primaryKey}`
expect.stringMatching(
new RegExp(
`Succesfully deleted cache with key: ${primaryKey}, id: \\d+`
)
)
);
expect(infoMock).toHaveBeenNthCalledWith(
3,

View file

@ -77734,7 +77734,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.logWarning = exports.deleteCacheByKey = exports.isExactKeyMatch = exports.isGhes = void 0;
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.deleteCacheByKey = exports.logWarning = exports.isExactKeyMatch = exports.isGhes = void 0;
const cache = __importStar(__nccwpck_require__(5116));
const core = __importStar(__nccwpck_require__(7484));
const request_error_1 = __nccwpck_require__(3708);
@ -77756,38 +77756,63 @@ function isExactKeyMatch(key, cacheKey) {
}) === 0);
}
exports.isExactKeyMatch = isExactKeyMatch;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
function deleteCacheByKey(key, owner, repo) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const octokit = new Octokit();
let response;
try {
response = yield octokit.rest.actions.deleteActionsCacheByKey({
const gitRef = process.env[constants_1.RefKey];
let cacheEntry = yield octokit.rest.actions.getActionsCacheList({
owner: owner,
repo: repo,
key: key
key: key,
ref: gitRef
});
if (response.status === 200) {
core.info(`Succesfully deleted cache with key: ${response.data.actions_caches[0].key}`);
const { data: { total_count, actions_caches } } = cacheEntry;
if (total_count !== 1 || total_count !== actions_caches.length) { // leave all find logic to the actual cache implementation. We just want to make sure we're returned a single element so we don't accidentally delete an entry that belongs to a different gitref.
if (total_count > 1) {
exports.logWarning(`More than one cache entry found for key ${key}`);
}
else if (total_count === 0 || actions_caches.length === 0) {
exports.logWarning(`No cache entries for key ${key} belong to gitref ${gitRef}.`);
}
// This situation is likely never actually going to come up.
// Istanbul is being dumb and I can't ignore this path.
else if (total_count !== actions_caches.length) {
exports.logWarning(`Reported cache entry matches for ${key} does not match length of 'actions_caches' array in API response.`);
}
core.info(`Skip trying to delete cache entry for key ${key}.`);
return;
}
let id = actions_caches[0].id;
response = yield octokit.rest.actions.deleteActionsCacheById({
owner: owner,
repo: repo,
cache_id: id
});
if (response.status === 204) {
core.info(`Succesfully deleted cache with key: ${key}, id: ${id}`);
return 204;
}
}
catch (e) {
if (e instanceof request_error_1.RequestError) {
let err = e;
let errData = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data;
exports.logWarning(`${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}' trying to delete cache with key: ${key}`);
exports.logWarning(`Github API reported error: ${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}'`);
}
response = e;
core.info(`Couldn't delete cache entry for key ${key}.`);
return;
}
return response;
});
}
exports.deleteCacheByKey = deleteCacheByKey;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
// Cache token authorized for all events that are tied to a ref
// See GitHub Context https://help.github.com/actions/automating-your-workflow-with-github-actions/contexts-and-expression-syntax-for-github-actions#github-context
function isValidEvent() {

51
dist/restore/index.js vendored
View file

@ -77734,7 +77734,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.logWarning = exports.deleteCacheByKey = exports.isExactKeyMatch = exports.isGhes = void 0;
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.deleteCacheByKey = exports.logWarning = exports.isExactKeyMatch = exports.isGhes = void 0;
const cache = __importStar(__nccwpck_require__(5116));
const core = __importStar(__nccwpck_require__(7484));
const request_error_1 = __nccwpck_require__(3708);
@ -77756,38 +77756,63 @@ function isExactKeyMatch(key, cacheKey) {
}) === 0);
}
exports.isExactKeyMatch = isExactKeyMatch;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
function deleteCacheByKey(key, owner, repo) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const octokit = new Octokit();
let response;
try {
response = yield octokit.rest.actions.deleteActionsCacheByKey({
const gitRef = process.env[constants_1.RefKey];
let cacheEntry = yield octokit.rest.actions.getActionsCacheList({
owner: owner,
repo: repo,
key: key
key: key,
ref: gitRef
});
if (response.status === 200) {
core.info(`Succesfully deleted cache with key: ${response.data.actions_caches[0].key}`);
const { data: { total_count, actions_caches } } = cacheEntry;
if (total_count !== 1 || total_count !== actions_caches.length) { // leave all find logic to the actual cache implementation. We just want to make sure we're returned a single element so we don't accidentally delete an entry that belongs to a different gitref.
if (total_count > 1) {
exports.logWarning(`More than one cache entry found for key ${key}`);
}
else if (total_count === 0 || actions_caches.length === 0) {
exports.logWarning(`No cache entries for key ${key} belong to gitref ${gitRef}.`);
}
// This situation is likely never actually going to come up.
// Istanbul is being dumb and I can't ignore this path.
else if (total_count !== actions_caches.length) {
exports.logWarning(`Reported cache entry matches for ${key} does not match length of 'actions_caches' array in API response.`);
}
core.info(`Skip trying to delete cache entry for key ${key}.`);
return;
}
let id = actions_caches[0].id;
response = yield octokit.rest.actions.deleteActionsCacheById({
owner: owner,
repo: repo,
cache_id: id
});
if (response.status === 204) {
core.info(`Succesfully deleted cache with key: ${key}, id: ${id}`);
return 204;
}
}
catch (e) {
if (e instanceof request_error_1.RequestError) {
let err = e;
let errData = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data;
exports.logWarning(`${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}' trying to delete cache with key: ${key}`);
exports.logWarning(`Github API reported error: ${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}'`);
}
response = e;
core.info(`Couldn't delete cache entry for key ${key}.`);
return;
}
return response;
});
}
exports.deleteCacheByKey = deleteCacheByKey;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
// Cache token authorized for all events that are tied to a ref
// See GitHub Context https://help.github.com/actions/automating-your-workflow-with-github-actions/contexts-and-expression-syntax-for-github-actions#github-context
function isValidEvent() {

View file

@ -77572,6 +77572,7 @@ function saveImpl(stateProvider) {
restoredKey = yield cache.restoreCache(cachePaths, primaryKey, [], { lookupOnly: true }, enableCrossOsArchive);
}
if (utils.isExactKeyMatch(primaryKey, restoredKey)) {
/* istanbul ignore next */
const { GITHUB_TOKEN, GITHUB_REPOSITORY } = process.env || null;
if (GITHUB_TOKEN && GITHUB_REPOSITORY && refreshCache === true) {
core.info(`Cache hit occurred on the primary key ${primaryKey}, attempting to refresh the contents of the cache.`);
@ -77771,7 +77772,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.logWarning = exports.deleteCacheByKey = exports.isExactKeyMatch = exports.isGhes = void 0;
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.deleteCacheByKey = exports.logWarning = exports.isExactKeyMatch = exports.isGhes = void 0;
const cache = __importStar(__nccwpck_require__(5116));
const core = __importStar(__nccwpck_require__(7484));
const request_error_1 = __nccwpck_require__(3708);
@ -77793,38 +77794,63 @@ function isExactKeyMatch(key, cacheKey) {
}) === 0);
}
exports.isExactKeyMatch = isExactKeyMatch;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
function deleteCacheByKey(key, owner, repo) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const octokit = new Octokit();
let response;
try {
response = yield octokit.rest.actions.deleteActionsCacheByKey({
const gitRef = process.env[constants_1.RefKey];
let cacheEntry = yield octokit.rest.actions.getActionsCacheList({
owner: owner,
repo: repo,
key: key
key: key,
ref: gitRef
});
if (response.status === 200) {
core.info(`Succesfully deleted cache with key: ${response.data.actions_caches[0].key}`);
const { data: { total_count, actions_caches } } = cacheEntry;
if (total_count !== 1 || total_count !== actions_caches.length) { // leave all find logic to the actual cache implementation. We just want to make sure we're returned a single element so we don't accidentally delete an entry that belongs to a different gitref.
if (total_count > 1) {
exports.logWarning(`More than one cache entry found for key ${key}`);
}
else if (total_count === 0 || actions_caches.length === 0) {
exports.logWarning(`No cache entries for key ${key} belong to gitref ${gitRef}.`);
}
// This situation is likely never actually going to come up.
// Istanbul is being dumb and I can't ignore this path.
else if (total_count !== actions_caches.length) {
exports.logWarning(`Reported cache entry matches for ${key} does not match length of 'actions_caches' array in API response.`);
}
core.info(`Skip trying to delete cache entry for key ${key}.`);
return;
}
let id = actions_caches[0].id;
response = yield octokit.rest.actions.deleteActionsCacheById({
owner: owner,
repo: repo,
cache_id: id
});
if (response.status === 204) {
core.info(`Succesfully deleted cache with key: ${key}, id: ${id}`);
return 204;
}
}
catch (e) {
if (e instanceof request_error_1.RequestError) {
let err = e;
let errData = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data;
exports.logWarning(`${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}' trying to delete cache with key: ${key}`);
exports.logWarning(`Github API reported error: ${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}'`);
}
response = e;
core.info(`Couldn't delete cache entry for key ${key}.`);
return;
}
return response;
});
}
exports.deleteCacheByKey = deleteCacheByKey;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
// Cache token authorized for all events that are tied to a ref
// See GitHub Context https://help.github.com/actions/automating-your-workflow-with-github-actions/contexts-and-expression-syntax-for-github-actions#github-context
function isValidEvent() {

52
dist/save/index.js vendored
View file

@ -77572,6 +77572,7 @@ function saveImpl(stateProvider) {
restoredKey = yield cache.restoreCache(cachePaths, primaryKey, [], { lookupOnly: true }, enableCrossOsArchive);
}
if (utils.isExactKeyMatch(primaryKey, restoredKey)) {
/* istanbul ignore next */
const { GITHUB_TOKEN, GITHUB_REPOSITORY } = process.env || null;
if (GITHUB_TOKEN && GITHUB_REPOSITORY && refreshCache === true) {
core.info(`Cache hit occurred on the primary key ${primaryKey}, attempting to refresh the contents of the cache.`);
@ -77771,7 +77772,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
});
};
Object.defineProperty(exports, "__esModule", ({ value: true }));
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.logWarning = exports.deleteCacheByKey = exports.isExactKeyMatch = exports.isGhes = void 0;
exports.isCacheFeatureAvailable = exports.getInputAsBool = exports.getInputAsInt = exports.getInputAsArray = exports.isValidEvent = exports.deleteCacheByKey = exports.logWarning = exports.isExactKeyMatch = exports.isGhes = void 0;
const cache = __importStar(__nccwpck_require__(5116));
const core = __importStar(__nccwpck_require__(7484));
const request_error_1 = __nccwpck_require__(3708);
@ -77793,38 +77794,63 @@ function isExactKeyMatch(key, cacheKey) {
}) === 0);
}
exports.isExactKeyMatch = isExactKeyMatch;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
function deleteCacheByKey(key, owner, repo) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const octokit = new Octokit();
let response;
try {
response = yield octokit.rest.actions.deleteActionsCacheByKey({
const gitRef = process.env[constants_1.RefKey];
let cacheEntry = yield octokit.rest.actions.getActionsCacheList({
owner: owner,
repo: repo,
key: key
key: key,
ref: gitRef
});
if (response.status === 200) {
core.info(`Succesfully deleted cache with key: ${response.data.actions_caches[0].key}`);
const { data: { total_count, actions_caches } } = cacheEntry;
if (total_count !== 1 || total_count !== actions_caches.length) { // leave all find logic to the actual cache implementation. We just want to make sure we're returned a single element so we don't accidentally delete an entry that belongs to a different gitref.
if (total_count > 1) {
exports.logWarning(`More than one cache entry found for key ${key}`);
}
else if (total_count === 0 || actions_caches.length === 0) {
exports.logWarning(`No cache entries for key ${key} belong to gitref ${gitRef}.`);
}
// This situation is likely never actually going to come up.
// Istanbul is being dumb and I can't ignore this path.
else if (total_count !== actions_caches.length) {
exports.logWarning(`Reported cache entry matches for ${key} does not match length of 'actions_caches' array in API response.`);
}
core.info(`Skip trying to delete cache entry for key ${key}.`);
return;
}
let id = actions_caches[0].id;
response = yield octokit.rest.actions.deleteActionsCacheById({
owner: owner,
repo: repo,
cache_id: id
});
if (response.status === 204) {
core.info(`Succesfully deleted cache with key: ${key}, id: ${id}`);
return 204;
}
}
catch (e) {
if (e instanceof request_error_1.RequestError) {
let err = e;
let errData = (_a = err.response) === null || _a === void 0 ? void 0 : _a.data;
exports.logWarning(`${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}' trying to delete cache with key: ${key}`);
exports.logWarning(`Github API reported error: ${err.name} '${err.status}: ${errData === null || errData === void 0 ? void 0 : errData.message}'`);
}
response = e;
core.info(`Couldn't delete cache entry for key ${key}.`);
return;
}
return response;
});
}
exports.deleteCacheByKey = deleteCacheByKey;
function logWarning(message) {
const warningPrefix = "[warning]";
core.info(`${warningPrefix}${message}`);
}
exports.logWarning = logWarning;
// Cache token authorized for all events that are tied to a ref
// See GitHub Context https://help.github.com/actions/automating-your-workflow-with-github-actions/contexts-and-expression-syntax-for-github-actions#github-context
function isValidEvent() {

1469
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,12 +1,16 @@
/* istanbul ignore file */
import { Inputs } from "../constants";
import { rest } from "msw";
import { setupServer } from "msw/node";
import nock from "nock";
export const successCacheKey = "Linux-node-bb828da54c148048dd17899ba9fda624811cfb43";
export const wrongRefCacheKey = "Linux-latest-node-bb828da54c148048dd17899ba9fda624811cfb43";
export const failureCacheKey = "Windows-node-bb828da54c148048dd17899ba9fda624811cfb43";
export const passThroughCacheKey = "macOS-node-bb828da54c148048dd17899ba9fda624811cfb43";
const successCacheId = 1337;
const failureCacheId = 69;
// See: https://github.com/actions/toolkit/blob/master/packages/core/src/core.ts#L67
function getInputName(name: string): string {
@ -56,31 +60,80 @@ export function clearInputs(): void {
delete process.env[getInputName(Inputs.RefreshCache)];
}
/* istanbul ignore next */
export const mockServer = setupServer(rest.delete('https://api.github.com/repos/owner/repo/actions/caches', (req, res, ctx) => {
if (req.url?.searchParams?.get('key') === failureCacheKey) {
return res(ctx.status(404),
export const mockServer = setupServer(
rest.delete('https://api.github.com/repos/owner/repo/actions/caches/', (req, res, ctx) => {
return res(ctx.status(422),
ctx.json({
message: "Not Found",
documentation_url: "https://docs.github.com/rest/actions/cache#delete-github-actions-caches-for-a-repository-using-a-cache-key"
}));
}
else if (req.url?.searchParams?.get('key') === successCacheKey) {
return res(ctx.status(200),
ctx.json({
total_count: 1,
actions_caches: [{
id: 15,
ref: "refs/heads/main",
key: successCacheKey,
version: "93a0f912fdb70083e929c1bf564bca2050be1c4e0932f7f9e78465ddcfbcc8f6",
last_accessed_at: "2022-12-29T22:06:42.683333300Z",
created_at: "2022-12-29T22:06:42.683333300Z",
size_in_bytes: 6057793
}]
}));
}
else if (req.url?.searchParams?.get('key') === passThroughCacheKey) {
message: "Invalid request.\n\nMissing required query parameter key",
documentation_url: "https://docs.github.com/rest/actions/cache#delete-github-actions-caches-for-a-repository-using-a-cache-key",
})
)
}),
rest.delete('https://api.github.com/repos/owner/repo/actions/caches/:id', (req, res, ctx) => {
const { id } = req.params;
if (parseInt(id as string) === failureCacheId) {
return res(ctx.status(404),
ctx.json({
message: "Not Found",
documentation_url: "https://docs.github.com/rest/actions/cache#delete-a-github-actions-cache-for-a-repository-using-a-cache-id"
}));
}
return res(ctx.status(204));
}),
// This endpoint always returns 200/OK, what we're checking here is whether we can get a unique cache ID, to avoid deleting the wrong entry.
rest.get('https://api.github.com/repos/owner/repo/actions/caches', (req, res, ctx) => {
let key : string = req.url?.searchParams?.get('key') || '';
let ref : string = req.url?.searchParams?.get('ref') || '';
if (key === '' || ref === '') {
return res(ctx.status(200),
ctx.json({
total_count: 2,
actions_caches: [{
id: 15,
ref: "refs/heads/main",
key: failureCacheKey,
version: "73885106f58cc52a7df9ec4d4a5622a5614813162cb516c759a30af6bf56e6f0",
last_accessed_at: "2022-12-29T22:06:42.683333300Z",
created_at: "2022-12-29T22:06:42.683333300Z",
size_in_bytes: 6057793
},
{
id: 16,
ref: "refs/heads/another-feature-branch",
key: failureCacheKey,
version: "73885106f58cc52a7df9ec4d4a5622a5614813162cb516c759a30af6bf56e6f0",
last_accessed_at: "2022-12-29T22:06:42.683333300Z",
created_at: "2022-12-29T22:06:42.683333300Z",
size_in_bytes: 6057793
}]
})
);
}
// This is the behavior seen when search doesn't find anything, but it is seen both when no key matches, as well as when the key matches but the entry belongs to another (likely the base) branch.
else if (key === wrongRefCacheKey) {
return res(ctx.status(200),
ctx.json({
total_count: 0,
actions_caches: []
})
);
}
else if (key === successCacheKey || key === failureCacheKey) {
return res(ctx.status(200),
ctx.json({
total_count: 1,
actions_caches: [{
id: (key === successCacheKey ? successCacheId : failureCacheId),
ref: ref,
key: key,
version: "93a0f912fdb70083e929c1bf564bca2050be1c4e0932f7f9e78465ddcfbcc8f6",
last_accessed_at: "2022-12-29T22:06:42.683333300Z",
created_at: "2022-12-29T22:06:42.683333300Z",
size_in_bytes: 6057793
}]
})
);
}
return req.passthrough();
}
}));
})
);