cache/__tests__/actionUtils.test.ts

336 lines
11 KiB
TypeScript
Raw Normal View History

import * as cache from "@actions/cache";
import * as core from "@actions/core";
2023-04-08 02:38:17 +01:00
import { RequestError } from "@octokit/request-error";
import nock from "nock";
GA for granular cache (#1035) * Add example for Haskell Stack * Revert "Add example for Haskell Stack" * Basic implementation * Updated variable name * Adding wrapper class * Changed logs to warnings * added debug logs * experimenting * Test * test * new try * test * Impl separated * Reverted wrapper changes * Added test cases * Some cleanup * Formatted document * Fixed test cases issues * Slight modification for test cases check * Updated new actions' input descriptions * Reverted custom asks implemented and added wrapper * refactor into a generic outputter * Readme draft for new actions * Generated dist * Fixed breaking test case * Removed return type in promise * Removed commented lines * Calling methods from same file * dist * update save as well * fix merge * Changes for beta release * Update dist folder * Fixed formatting * dist * Add support for gzip fallback for restore of old cache on windows * Fixed test cases * Fixed test cases * Added restore only and save only test cases * Updated new actions dist files * Removed comments * Fixed inputs * Renamed variables and added tests * Fixed breaking test case * Fixed review comments and tests * added stateprovider changes * Deleted stateprovider tests until added * Added stateprovider test cases * Fixed breaking test case * Updated outputs of restore action * Changes for beta release * Update dist folder * Add support for gzip fallback for restore of old cache on windows * update for new beta release * Update save/action.yml Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update restore/action.yml Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update restore/action.yml Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update restore/action.yml Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update restore/action.yml Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Added more assertions as values can't be checked * Removed unused code * Merged beta branch and resolved conflicts * Added save readme * Updates to save readme * Renamed output * Added cache hit info in readme * Update restore/README.md Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update restore/README.md Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update restore/README.md Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update save/README.md Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Update save/README.md Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> * Removed verbose statements * Repositioned new actions introduction * Added test case for restore state * Addressed review comments * nit * nit: added language to code blocks * Updated beta version to 3.2.0-beta.1 * Added stateprovider mock implementations * Linting errors fixed * Save-only warning added * Updated return ID to -2 * Removed -2 error code * Removed comment * Updated cache npm lib version * Updated license version * Updated releases.md * Updated readme with the new actions in what's new Co-authored-by: Malo Bourgon <mbourgon@gmail.com> Co-authored-by: Vipul <vsvipul@github.com> Co-authored-by: Bishal Prasad <bishal-pdmsft@github.com> Co-authored-by: Tanuj Kumar Mishra <tanuj077@users.noreply.github.com> Co-authored-by: Sampark Sharma <phantsure@github.com>
2022-12-21 14:08:44 +00:00
import { Events, RefKey } from "../src/constants";
import * as actionUtils from "../src/utils/actionUtils";
2020-06-02 16:21:03 +01:00
import * as testUtils from "../src/utils/testUtils";
jest.mock("@actions/core");
jest.mock("@actions/cache");
2020-06-02 16:21:03 +01:00
beforeAll(() => {
2023-04-08 02:38:17 +01:00
nock.disableNetConnect();
2020-06-02 16:21:03 +01:00
jest.spyOn(core, "getInput").mockImplementation((name, options) => {
return jest.requireActual("@actions/core").getInput(name, options);
});
2023-04-08 02:38:17 +01:00
testUtils.mockServer.listen({
onUnhandledRequest: "warn"
});
2020-06-02 16:21:03 +01:00
});
afterEach(() => {
delete process.env[Events.Key];
2020-04-17 20:46:46 +01:00
delete process.env[RefKey];
2023-04-08 02:38:17 +01:00
delete process.env["GITHUB_REPOSITORY"];
delete process.env["GITHUB_TOKEN"];
delete process.env["GITHUB_ACTION"];
});
afterAll(() => {
testUtils.mockServer.close();
nock.enableNetConnect();
});
2020-09-29 18:36:19 +01:00
test("isGhes returns true if server url is not github.com", () => {
try {
process.env["GITHUB_SERVER_URL"] = "http://example.com";
expect(actionUtils.isGhes()).toBe(true);
} finally {
process.env["GITHUB_SERVER_URL"] = undefined;
}
});
2022-02-07 05:20:40 +00:00
test("isGhes returns false when server url is github.com", () => {
2020-09-29 18:36:19 +01:00
try {
process.env["GITHUB_SERVER_URL"] = "http://github.com";
expect(actionUtils.isGhes()).toBe(false);
} finally {
process.env["GITHUB_SERVER_URL"] = undefined;
}
});
test("isExactKeyMatch with undefined cache key returns false", () => {
const key = "linux-rust";
const cacheKey = undefined;
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
});
test("isExactKeyMatch with empty cache key returns false", () => {
const key = "linux-rust";
const cacheKey = "";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
});
test("isExactKeyMatch with different keys returns false", () => {
const key = "linux-rust";
const cacheKey = "linux-";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
});
test("isExactKeyMatch with different key accents returns false", () => {
const key = "linux-áccent";
const cacheKey = "linux-accent";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(false);
});
test("isExactKeyMatch with same key returns 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", () => {
const key = "linux-rust";
const cacheKey = "LINUX-RUST";
expect(actionUtils.isExactKeyMatch(key, cacheKey)).toBe(true);
});
test("logWarning logs a message with a warning prefix", () => {
const message = "A warning occurred.";
const infoMock = jest.spyOn(core, "info");
actionUtils.logWarning(message);
expect(infoMock).toHaveBeenCalledWith(`[warning]${message}`);
});
2020-04-17 20:46:46 +01:00
test("isValidEvent returns false for event that does not have a branch or tag", () => {
const event = "foo";
process.env[Events.Key] = event;
const isValidEvent = actionUtils.isValidEvent();
expect(isValidEvent).toBe(false);
});
2020-04-17 20:46:46 +01:00
test("isValidEvent returns true for event that has a ref", () => {
const event = Events.Push;
process.env[Events.Key] = event;
2020-04-17 20:46:46 +01:00
process.env[RefKey] = "ref/heads/feature";
const isValidEvent = actionUtils.isValidEvent();
expect(isValidEvent).toBe(true);
});
2020-06-02 16:21:03 +01:00
test("getInputAsArray returns empty array if not required and missing", () => {
expect(actionUtils.getInputAsArray("foo")).toEqual([]);
});
test("getInputAsArray throws error if required and missing", () => {
expect(() =>
actionUtils.getInputAsArray("foo", { required: true })
).toThrowError();
});
test("getInputAsArray handles single line correctly", () => {
testUtils.setInput("foo", "bar");
expect(actionUtils.getInputAsArray("foo")).toEqual(["bar"]);
});
test("getInputAsArray handles multiple lines correctly", () => {
testUtils.setInput("foo", "bar\nbaz");
expect(actionUtils.getInputAsArray("foo")).toEqual(["bar", "baz"]);
});
test("getInputAsArray handles different new lines correctly", () => {
testUtils.setInput("foo", "bar\r\nbaz");
expect(actionUtils.getInputAsArray("foo")).toEqual(["bar", "baz"]);
});
test("getInputAsArray handles empty lines correctly", () => {
testUtils.setInput("foo", "\n\nbar\n\nbaz\n\n");
expect(actionUtils.getInputAsArray("foo")).toEqual(["bar", "baz"]);
});
2020-10-02 15:59:55 +01:00
test("getInputAsArray removes spaces after ! at the beginning", () => {
testUtils.setInput(
"foo",
"! bar\n! baz\n! qux\n!quux\ncorge\ngrault! garply\n!\r\t waldo"
);
expect(actionUtils.getInputAsArray("foo")).toEqual([
"!bar",
"!baz",
"!qux",
2022-10-03 07:39:10 +01:00
"!quux",
"corge",
2022-10-03 07:39:10 +01:00
"grault! garply",
"!waldo"
]);
});
2020-10-02 15:59:55 +01:00
test("getInputAsInt returns undefined if input not set", () => {
expect(actionUtils.getInputAsInt("undefined")).toBeUndefined();
2020-10-02 15:59:55 +01:00
});
test("getInputAsInt returns value if input is valid", () => {
testUtils.setInput("foo", "8");
expect(actionUtils.getInputAsInt("foo")).toBe(8);
});
test("getInputAsInt returns undefined if input is invalid or NaN", () => {
testUtils.setInput("foo", "bar");
expect(actionUtils.getInputAsInt("foo")).toBeUndefined();
});
test("getInputAsInt throws if required and value missing", () => {
expect(() =>
actionUtils.getInputAsInt("undefined", { required: true })
).toThrowError();
});
test("getInputAsBool returns false if input not set", () => {
expect(actionUtils.getInputAsBool("undefined")).toBe(false);
});
test("getInputAsBool returns value if input is valid", () => {
testUtils.setInput("foo", "true");
expect(actionUtils.getInputAsBool("foo")).toBe(true);
});
test("getInputAsBool returns false if input is invalid or NaN", () => {
testUtils.setInput("foo", "bar");
expect(actionUtils.getInputAsBool("foo")).toBe(false);
});
test("getInputAsBool throws if required and value missing", () => {
expect(() =>
actionUtils.getInputAsBool("undefined2", { required: true })
).toThrowError();
});
2023-04-08 02:38:17 +01:00
test("deleteCacheByKey returns '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).toBeInstanceOf(RequestError);
expect(response).toMatchObject({
name: "HttpError",
status: 404
});
});
test("deleteCacheByKey returns 'HttpError: 401' on an invalid non-mocked request.", 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";
await nock.enableNetConnect();
const logWarningMock = jest.spyOn(actionUtils, "logWarning");
const response = await actionUtils.deleteCacheByKey(
testUtils.passThroughCacheKey,
"owner",
"repo"
);
expect(logWarningMock).toHaveBeenCalledWith(
expect.stringMatching(/401: Bad Credentials/i)
);
expect(response).toBeInstanceOf(RequestError);
expect(response).toMatchObject({
name: "HttpError",
status: 401
});
nock.disableNetConnect();
});
test("deleteCacheByKey returns matched cache data when successful.", 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 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(logWarningMock).toHaveBeenCalledTimes(0);
});
test("isCacheFeatureAvailable for ac enabled", () => {
jest.spyOn(cache, "isFeatureAvailable").mockImplementation(() => true);
expect(actionUtils.isCacheFeatureAvailable()).toBe(true);
});
test("isCacheFeatureAvailable for ac disabled on GHES", () => {
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.
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 {
process.env["GITHUB_SERVER_URL"] = "http://example.com";
expect(actionUtils.isCacheFeatureAvailable()).toBe(false);
expect(infoMock).toHaveBeenCalledWith(`[warning]${message}`);
} finally {
delete process.env["GITHUB_SERVER_URL"];
}
});
test("isCacheFeatureAvailable for ac disabled on dotcom", () => {
jest.spyOn(cache, "isFeatureAvailable").mockImplementation(() => false);
const message =
"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 {
process.env["GITHUB_SERVER_URL"] = "http://github.com";
expect(actionUtils.isCacheFeatureAvailable()).toBe(false);
expect(infoMock).toHaveBeenCalledWith(`[warning]${message}`);
} finally {
delete process.env["GITHUB_SERVER_URL"];
}
});