Skip to content

Commit

Permalink
update tests
Browse files Browse the repository at this point in the history
  • Loading branch information
smac89 committed Nov 21, 2023
1 parent 2bc0c40 commit 53434db
Show file tree
Hide file tree
Showing 11 changed files with 89 additions and 41 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ jobs:
permissions: # (2)
contents: write
steps:
- uses: Actions-R-Us/actions-tagger@latest
- uses: Actions-R-Us/actions-tagger@v2
with:
publish_latest_tag: true
```
Expand Down
11 changes: 8 additions & 3 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,15 @@ description:
'Keep your action versions up-to-date by automatically promoting a major
version each time a minor release is created'
inputs:
# TODO v3: rename this to publish_latest and latest will not
# default to a tag, but will follow `prefer_branch_release`
# TODO v3: remove this
publish_latest_tag:
description: 'Whether or not to also publish a `latest` tag'
description: '(Deprecated) Whether or not to also publish a `latest` tag'
required: false
default: false
publish_latest:
description:
'Whether or not to also publish a `latest` ref (depending on
`prefer_branch_releases`)'
required: false
default: false
prefer_branch_releases:
Expand Down
2 changes: 1 addition & 1 deletion index.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
declare namespace NodeJS {
interface ProcessEnv {
GITHUB_SHA: string;
GITHUB_SHA?: string;
}
}
1 change: 1 addition & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ const config: JestConfigWithTsJest = {
},
],
},
cache: process.env.CI !== 'true', // disable caching in CI environments
testEnvironment: 'node',
roots: ['<rootDir>'],
// https://kulshekhar.github.io/ts-jest/docs/getting-started/paths-mapping
Expand Down
9 changes: 4 additions & 5 deletions src/functions/public.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,18 +105,17 @@ namespace Functions {
* Creates the tags required and optionally a 'latest' tag
*
* @param {GitHub} github The octokit client for making requests
* @param {Boolean} overridePublishLatest Flag used to force the publishing of the latest tag
* @param {Boolean} publishLatest Flag used to signal the publishing of the latest tag
*/
export async function createRequiredRefs(
github: GitHub,
overridePublishLatest?: boolean
publishLatest: boolean
): Promise<TaggedRef> {
const mayor = Functions.majorVersion();
const major = Functions.majorVersion();

const ref = `${Functions.getPreferredRef()}/v${mayor}`;
const ref = `${Functions.getPreferredRef()}/v${major}`;
await Private.createRef(github, ref);

const publishLatest: boolean = overridePublishLatest ?? preferences.publishLatest;
if (publishLatest) {
// TODO v3: `${getPreferredRef()}/latest`
await Private.createRef(github, 'tags/latest');
Expand Down
4 changes: 2 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ export default async function main(): Promise<void> {
const releaseVer = getPublishRefVersion();

if (semverGte(releaseVer, majorLatest.name)) {
const overridePubLatest = preferences.publishLatest && semverGte(releaseVer, repoLatest.name);
const publishLatest = preferences.publishLatest && semverGte(releaseVer, repoLatest.name);

const { ref, latest } = await createRequiredRefs(octokit, overridePubLatest);
const { ref, latest } = await createRequiredRefs(octokit, publishLatest);
outputTagName(ref);
outputLatest(latest);
} else if (majorLatest.shaId !== process.env.GITHUB_SHA) {
Expand Down
1 change: 1 addition & 0 deletions src/util.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface ActionPreferences {

export const preferences: ActionPreferences = {
publishLatest:
// TODO v3: Ignore INPUT_PUBLISH_LATEST_TAG
(process.env.INPUT_PUBLISH_LATEST ?? process.env.INPUT_PUBLISH_LATEST_TAG)?.toLowerCase() ===
'true',
preferBranchRelease: process.env.INPUT_PREFER_BRANCH_RELEASES?.toLowerCase() === 'true',
Expand Down
95 changes: 69 additions & 26 deletions tests/functions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,18 @@ import os from 'node:os';
import { getOctokit } from '@actions/github';
import type { GraphQlQueryRepository } from '@actionstagger/functions/types';

beforeEach(() => jest.resetModules());
afterEach(() => jest.resetAllMocks());

describe('Functions', () => {
beforeEach(() => jest.resetModules());
afterEach(() => jest.restoreAllMocks());

describe.each([
{ preferbranchReleases: 'false', expected: 'tags' },
{ preferbranchReleases: 'true', expected: 'heads' },
])('#getPreferredRef()', ({ preferbranchReleases, expected }) => {
test(`when INPUT_PREFER_BRANCH_RELEASES=${preferbranchReleases} returns ${expected}`, async () => {
process.env.INPUT_PREFER_BRANCH_RELEASES = preferbranchReleases;
jest.replaceProperty(process, 'env', {
INPUT_PREFER_BRANCH_RELEASES: preferbranchReleases,
});
await import('@actionstagger/functions/public').then(({ default: { getPreferredRef } }) =>
expect(getPreferredRef()).toBe(expected)
);
Expand Down Expand Up @@ -42,17 +44,17 @@ describe('Functions', () => {
created: true,
};
fs.writeFileSync(`${dir}/event.json`, JSON.stringify(pushEvent));
process.env.GITHUB_EVENT_PATH = `${dir}/event.json`;
process.env.INPUT_PREFER_BRANCH_RELEASES = preferbranchReleases;
process.env.GITHUB_EVENT_NAME = eventName;
process.env.GITHUB_REF_NAME = githubRef.replace(/refs\/.+\//g, '');
process.env.GITHUB_REF = githubRef;
jest.replaceProperty(process, 'env', {
GITHUB_EVENT_PATH: `${dir}/event.json`,
INPUT_PREFER_BRANCH_RELEASES: preferbranchReleases,
GITHUB_EVENT_NAME: eventName,
GITHUB_REF_NAME: githubRef.replace(/refs\/.+\//g, ''),
GITHUB_REF: githubRef,
});
});

afterEach(() => {
fs.rmSync(dir, { recursive: true });
// actions toolkit tries to read this file if it is set, which we don't want
delete process.env.GITHUB_EVENT_PATH;
});

test(`on ${eventName} when INPUT_PREFER_BRANCH_RELEASES=${preferbranchReleases}, pushed ref=${githubRef}, returns=${expected}`, async () => {
Expand Down Expand Up @@ -84,14 +86,14 @@ describe('Functions', () => {
},
};
fs.writeFileSync(`${dir}/event.json`, JSON.stringify(releaseEvent));
process.env.GITHUB_EVENT_PATH = `${dir}/event.json`;
process.env.GITHUB_EVENT_NAME = eventName;
jest.replaceProperty(process, 'env', {
GITHUB_EVENT_PATH: `${dir}/event.json`,
GITHUB_EVENT_NAME: eventName,
});
});

afterEach(() => {
fs.rmSync(dir, { recursive: true });
// actions toolkit tries to read this file if it is set, which we don't want
delete process.env.GITHUB_EVENT_PATH;
});

test(`on ${eventName}, release tag=${tagName}, returns=${expected}`, async () => {
Expand Down Expand Up @@ -133,17 +135,16 @@ describe('Functions', () => {
}));

beforeEach(async () => {
const semverTag = (await import('semver/functions/parse')).default(pushedRef);

jest.doMock('@actionstagger/functions/public', () => {
const MockFunctions = jest.requireActual<typeof import('@actionstagger/functions/public')>(
'@actionstagger/functions/public'
).default;
MockFunctions.getPublishRefVersion = jest.fn().mockReturnValue(semverTag);
return {
__esModule: true,
default: MockFunctions,
};
// We need to import it here because jest mucks with the global scope which creates issues
// when trying to use `instanceof`.
// In this case, if the parse function was imported earlier, it will exist in a different
// global scope than the rest of the test. Which leads to infruiating errors when used
// to create semver objects such as SemVer is not instanceof SemVer...🙄
// In short see https://backend.cafe/should-you-use-jest-as-a-testing-library
const semverTag = (await import('semver/functions/parse')).default(pushedRef)!;

await import('@actionstagger/functions/public').then(functions => {
jest.spyOn(functions.default, 'getPublishRefVersion').mockReturnValue(semverTag);
});
});

Expand Down Expand Up @@ -175,4 +176,46 @@ describe('Functions', () => {
});
});
});

describe.each([
{
refToCreate: 'v3.3.7',
publishLatest: false,
expectedRef: 'tags/v3',
},
{
refToCreate: 'v3.3.1',
publishLatest: true,

expectedRef: 'tags/v3',
},
])('#createRequiredRefs', ({ refToCreate, publishLatest, expectedRef }) => {
const octokit = getOctokit('TEST_TOKEN');

beforeEach(async () => {
const semverTag = (await import('semver/functions/parse')).default(refToCreate)!;
await import('@actionstagger/functions/private').then(functions =>
jest.spyOn(functions.default, 'createRef').mockResolvedValue(Promise.resolve())
);

await import('@actionstagger/functions/public').then(functions =>
jest.spyOn(functions.default, 'getPublishRefVersion').mockReturnValue(semverTag)
);

await import('@actionstagger/functions/public').then(functions =>
jest.spyOn(functions.default, 'getPreferredRef').mockReturnValue('tags')
);
});

test(`when creating ref for ${refToCreate} and publishLatest=${publishLatest}, will create ${expectedRef} and${
publishLatest ? '' : ' not'
} publish latest tag`, async () => {
await import('@actionstagger/functions/public').then(({ default: { createRequiredRefs } }) =>
createRequiredRefs(octokit, publishLatest).then(({ ref, latest }) => {
expect(ref).toBe(expectedRef);
expect(latest).toBe(publishLatest);
})
);
});
});
});
2 changes: 0 additions & 2 deletions tests/main.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
beforeEach(() => jest.resetModules());

test('placeholder', () => {
expect(true).toBeTruthy();
});
2 changes: 1 addition & 1 deletion tests/setup.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
beforeAll(() => {
process.env.INPUT_PUBLISH_LATEST_TAG ??= 'false';
process.env.INPUT_PUBLISH_LATEST ??= 'false';
process.env.INPUT_PREFER_BRANCH_RELEASES ??= 'false';
process.env.INPUT_TOKEN ??= 'test-token';
process.env.GITHUB_REPOSITORY ??= 'test/test';
Expand Down
1 change: 1 addition & 0 deletions tests/util.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ describe('preferences.publishLatestTag', () => {
);
});

// TODO: v3 remove this test or set it to failing
it('Should have been set to true when input is true', async () => {
process.env.INPUT_PUBLISH_LATEST_TAG = 'true';
await import('@actionstagger/util').then(({ preferences }) =>
Expand Down

0 comments on commit 53434db

Please sign in to comment.