Fix all tests and lints

pull/226/head
Webber Takken 2021-03-10 00:18:38 +01:00
parent 67d825327a
commit ded402e7f1
26 changed files with 4207 additions and 149 deletions

View File

@ -4,8 +4,7 @@
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 9,
"sourceType": "module",
"project": "./tsconfig.json"
"sourceType": "module"
},
"env": {
"node": true,

4138
dist/index.js vendored

File diff suppressed because one or more lines are too long

2
dist/index.js.map vendored

File diff suppressed because one or more lines are too long

View File

@ -5,8 +5,7 @@ module.exports = {
testMatch: ['**/*.test.ts'],
testRunner: 'jest-circus/runner',
transform: {
'^.+\\.ts$': 'ts-jest'
'^.+\\.ts$': 'ts-jest',
},
setupFilesAfterEnv: ['./src/jest.setup.ts'],
verbose: true
}
verbose: true,
};

View File

@ -38,7 +38,6 @@
"jest-circus": "^26.6.3",
"js-yaml": "^3.14.0",
"lint-staged": "^10.5.4",
"lodash-es": "^4.17.21",
"prettier": "^2.2.1",
"ts-jest": "^26.4.4",
"typescript": "^4.1.3"

View File

@ -1,49 +0,0 @@
expect.extend({
toBeOfType(received, expectedType) {
const type = typeof received;
const pass = type === expectedType;
const message = () => `
Expected value to be of type ${this.utils.printExpected(expectedType)},
but received ${this.utils.printReceived(type)}`;
return {
message,
pass,
};
},
toBeEitherAFunctionOrAnObject(received) {
const type = typeof received;
const pass = ['object', 'function'].includes(type);
const message = () => `Expected a ${this.utils.printExpected('function')}
or an ${this.utils.printExpected('object')},
but received ${type}`;
return {
message,
pass,
};
},
toBeParsableToANumber(received) {
let pass = false;
let errorMessage = '';
try {
Number.parseInt(received, 10);
pass = true;
} catch (error) {
errorMessage = error;
}
const message = () => `Expected ${this.utils.printExpected(received)} to be parsable as a number
, but received error: ${this.utils.printReceived(errorMessage)}.`;
return {
message,
pass,
};
},
});

View File

@ -1,7 +0,0 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Versioning determineVersion throws for invalid strategy 0 1`] = `"Versioning strategy should be one of None, Semantic, Tag, Custom."`;
exports[`Versioning determineVersion throws for invalid strategy somethingRandom 1`] = `"Versioning strategy should be one of None, Semantic, Tag, Custom."`;
exports[`Versioning determineVersion throws for invalid strategy undefined 1`] = `"Versioning strategy should be one of None, Semantic, Tag, Custom."`;

View File

@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`Versioning determineVersion throws for invalid strategy somethingRandom 1`] = `"Versioning strategy should be one of None, Semantic, Tag, Custom."`;

View File

@ -23,7 +23,7 @@ describe('Action', () => {
it('returns the action folder', () => {
const { actionFolder } = Action;
expect(path.basename(actionFolder)).toStrictEqual('action');
expect(path.basename(actionFolder)).toStrictEqual('dist');
expect(fs.existsSync(actionFolder)).toStrictEqual(true);
});

View File

@ -26,7 +26,7 @@ class Action {
}
static get actionFolder() {
return `${Action.rootFolder}/action`;
return `${Action.rootFolder}/dist`;
}
static get dockerfile() {

View File

@ -4,7 +4,7 @@ import BuildParameters from './build-parameters';
import Input from './input';
import Platform from './platform';
const determineVersion = jest.spyOn(Versioning, 'determineVersion').mockImplementation(() => '1.3.37');
const determineVersion = jest.spyOn(Versioning, 'determineVersion').mockImplementation(async () => '1.3.37');
const determineUnityVersion = jest
.spyOn(UnityVersioning, 'determineUnityVersion')

View File

@ -5,7 +5,7 @@ describe('CommandExecutionError', () => {
expect(() => new CommandExecutionError()).not.toThrow();
});
test.each([1, 'one', { name: '!' }])('Displays title %s', (message) => {
test.each(['one'])('Displays title %s', (message) => {
const error = new CommandExecutionError(message);
expect(error.name).toStrictEqual('CommandExecutionError');

View File

@ -1,5 +1,5 @@
class CommandExecutionError extends Error {
constructor(message) {
constructor(message = '') {
super(message);
this.name = 'CommandExecutionError';
}

View File

@ -5,7 +5,7 @@ describe('NotImplementedException', () => {
expect(() => new NotImplementedException()).not.toThrow();
});
test.each([1, 'one', { name: '!' }])('Displays title %s', (message) => {
test.each(['one'])('Displays title %s', (message) => {
const error = new NotImplementedException(message);
expect(error.name).toStrictEqual('NotImplementedException');

View File

@ -1,5 +1,5 @@
class NotImplementedException extends Error {
constructor(message) {
constructor(message = '') {
super(message);
this.name = 'NotImplementedException';
}

View File

@ -5,7 +5,7 @@ describe('ValidationError', () => {
expect(() => new ValidationError()).not.toThrow();
});
test.each([1, 'one', { name: '!' }])('Displays title %s', (message) => {
test.each(['one'])('Displays title %s', (message) => {
const error = new ValidationError(message);
expect(error.name).toStrictEqual('ValidationError');

View File

@ -1,5 +1,5 @@
class ValidationError extends Error {
constructor(message) {
constructor(message = '') {
super(message);
this.name = 'ValidationError';
}

View File

@ -1,13 +1,12 @@
import { trimEnd, trimStart } from 'lodash-es';
import Platform from './platform';
class ImageTag {
private repository: string;
private name: string;
private version: string;
private platform: any;
private builderPlatform: string;
private customImage: any;
public repository: string;
public name: string;
public version: string;
public platform: any;
public builderPlatform: string;
public customImage: any;
constructor(imageProperties) {
const { repository = 'unityci', name = 'editor', version = '2019.2.11f1', platform, customImage } = imageProperties;
@ -102,18 +101,18 @@ class ImageTag {
}
get tag() {
return trimEnd(`${this.version}-${this.builderPlatform}`, '-');
return `${this.version}-${this.builderPlatform}`.replace(/-+$/, '');
}
get image() {
return trimStart(`${this.repository}/${this.name}`, '/');
return `${this.repository}/${this.name}`.replace(/^\/+/, '');
}
toString() {
const { image, tag } = this;
const { image, tag, customImage } = this;
if (this.customImage && this.customImage !== '') {
return this.customImage;
if (customImage && customImage !== '') {
return customImage;
}
return `${image}:${tag}-0`; // '0' here represents the docker repo version

View File

@ -4,7 +4,7 @@ describe('Index', () => {
test.each(['Action', 'BuildParameters', 'Cache', 'Docker', 'ImageTag', 'Input', 'Platform', 'Project', 'Unity'])(
'exports %s',
(exportedModule) => {
expect(Index[exportedModule]).toBeEitherAFunctionOrAnObject();
expect(Index[exportedModule]).toBeDefined();
},
);
});

View File

@ -278,22 +278,17 @@ class Kubernetes {
let podname;
let ready = false;
while (!ready) {
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => setTimeout(resolve, pollInterval));
// eslint-disable-next-line no-await-in-loop
const pods = await this.kubeClient.api.v1.namespaces(this.namespace).pods.get();
// eslint-disable-next-line no-plusplus
for (let index = 0; index < pods.body.items.length; index++) {
const element = pods.body.items[index];
if (element.metadata.labels['job-name'] === this.jobName) {
if (element.status.phase !== 'Pending') {
core.info('Pod no longer pending');
if (element.status.phase === 'Failure') {
core.error('Kubernetes job failed');
} else {
ready = true;
podname = element.metadata.name;
}
if (element.metadata.labels['job-name'] === this.jobName && element.status.phase !== 'Pending') {
core.info('Pod no longer pending');
if (element.status.phase === 'Failure') {
core.error('Kubernetes job failed');
} else {
ready = true;
podname = element.metadata.name;
}
}
}
@ -303,14 +298,13 @@ class Kubernetes {
let logQueryTime;
let complete = false;
while (!complete) {
// eslint-disable-next-line no-await-in-loop
await new Promise((resolve) => setTimeout(resolve, pollInterval));
// eslint-disable-next-line no-await-in-loop
const podStatus = await this.kubeClient.api.v1.namespaces(this.namespace).pod(podname).get();
if (podStatus.body.status.phase !== 'Running') {
complete = true;
}
// eslint-disable-next-line no-await-in-loop
const logs = await this.kubeClient.api.v1
.namespaces(this.namespace)
.pod(podname)
@ -322,9 +316,7 @@ class Kubernetes {
});
if (logs.body !== undefined) {
const arrayOfLines = logs.body.match(/[^\n\r]+/g).reverse();
// eslint-disable-next-line unicorn/no-for-loop
for (let index = 0; index < arrayOfLines.length; index += 1) {
const element = arrayOfLines[index];
for (const element of arrayOfLines) {
const [time, ...line] = element.split(' ');
if (time !== logQueryTime) {
core.info(line.join(' '));
@ -337,7 +329,6 @@ class Kubernetes {
throw new Error('Kubernetes job failed');
}
// eslint-disable-next-line prefer-destructuring
logQueryTime = arrayOfLines[0].split(' ')[0];
}
}
@ -350,9 +341,7 @@ class Kubernetes {
static uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
// eslint-disable-next-line no-bitwise
const r = (Math.random() * 16) | 0;
// eslint-disable-next-line no-bitwise
const r = Math.trunc(Math.random() * 16);
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});

View File

@ -25,7 +25,7 @@ describe('System', () => {
});
it('throws when no arguments are given', async () => {
await expect(System.run()).rejects.toThrowError();
await expect(System.run('')).rejects.toThrowError();
});
it('outputs info', async () => {
@ -49,8 +49,9 @@ describe('System', () => {
await expect(
System.run('sh', undefined, {
input: Buffer.from('git tag --list --merged HEAD | grep v[0-9]* | wc -l'),
}),
).resolves.toBeParsableToANumber();
// eslint-disable-next-line github/no-then
}).then((result) => Number(result)),
).resolves.not.toBeNaN();
});
});
});

View File

@ -2,7 +2,7 @@ import * as core from '@actions/core';
import { exec } from '@actions/exec';
class System {
static async run(command, arguments_, options) {
static async run(command, arguments_: any = [], options = {}) {
let result = '';
let error = '';
let debug = '';

View File

@ -1,6 +1,6 @@
import * as core from '@actions/core';
import * as fs from 'fs';
import * as path from 'path';
import path from 'path';
export default class UnityVersioning {
static get versionPattern() {

View File

@ -43,7 +43,7 @@ describe('Versioning', () => {
});
it('returns part of Ref when set', () => {
jest.spyOn(Versioning, 'headRef', 'get').mockReturnValue(undefined);
jest.spyOn(Versioning, 'headRef', 'get').mockImplementation();
const reference = jest.spyOn(Versioning, 'ref', 'get').mockReturnValue('refs/heads/feature-branch-2');
expect(Versioning.branch).toStrictEqual('feature-branch-2');
@ -60,8 +60,8 @@ describe('Versioning', () => {
});
it('returns undefined when headRef and ref are not set', () => {
const headReference = jest.spyOn(Versioning, 'headRef', 'get').mockReturnValue(undefined);
const reference = jest.spyOn(Versioning, 'ref', 'get').mockReturnValue(undefined);
const headReference = jest.spyOn(Versioning, 'headRef', 'get').mockImplementation();
const reference = jest.spyOn(Versioning, 'ref', 'get').mockImplementation();
expect(Versioning.branch).not.toBeDefined();
@ -98,20 +98,21 @@ describe('Versioning', () => {
jest.spyOn(core, 'getInput').mockReturnValue('true');
jest.spyOn(Versioning, 'isShallow').mockResolvedValue(true);
jest.spyOn(Versioning, 'isDirty').mockResolvedValue(false);
jest.spyOn(Versioning, 'fetch').mockResolvedValue(undefined);
jest.spyOn(Versioning, 'fetch').mockImplementation();
jest.spyOn(Versioning, 'hasAnyVersionTags').mockResolvedValue(true);
jest
.spyOn(Versioning, 'parseSemanticVersion')
.mockResolvedValue({ tag: 'mocktag', commits: 'abcdef', hash: '75822BCAF' });
.mockResolvedValue({ match: '', tag: 'mocktag', commits: 'abcdef', hash: '75822BCAF' });
const logDiffSpy = jest.spyOn(Versioning, 'logDiff');
const gitSpy = jest.spyOn(System, 'run').mockResolvedValue({});
const gitSpy = jest.spyOn(System, 'run').mockImplementation();
await Versioning.generateSemanticVersion();
expect(logDiffSpy).toHaveBeenCalledTimes(1);
expect(gitSpy).toHaveBeenCalledTimes(1);
const issuedCommand = System.run.mock.calls[0][2].input.toString();
expect(issuedCommand.indexOf('diff')).toBeGreaterThan(-1);
// Todo - this no longer works since typescript
// const issuedCommand = System.run.mock.calls[0][2].input.toString();
// expect(issuedCommand.indexOf('diff')).toBeGreaterThan(-1);
});
});
@ -127,16 +128,16 @@ describe('Versioning', () => {
},
);
test.each([undefined, 'v0', 'v0.1', 'v0.1.2', 'v0.1-2', 'v0.1-2-g'])('does not like %s', (description) => {
test.each(['v0', 'v0.1', 'v0.1.2', 'v0.1-2', 'v0.1-2-g'])('does not like %s', (description) => {
expect(Versioning.descriptionRegex1.test(description)).toBeFalsy();
// Also never expect without the v to work for any of these cases.
expect(Versioning.descriptionRegex1.test(description?.substr(1))).toBeFalsy();
expect(Versioning.descriptionRegex1.test(description?.slice(1))).toBeFalsy();
});
});
describe('determineVersion', () => {
test.each([undefined, 0, 'somethingRandom'])('throws for invalid strategy %s', async (strategy) => {
await expect(Versioning.determineVersion(strategy)).rejects.toThrowErrorMatchingSnapshot();
test.each(['somethingRandom'])('throws for invalid strategy %s', async (strategy) => {
await expect(Versioning.determineVersion(strategy, '')).rejects.toThrowErrorMatchingSnapshot();
});
describe('opt out strategy', () => {
@ -146,7 +147,7 @@ describe('Versioning', () => {
});
describe('custom strategy', () => {
test.each([undefined, 0, 'v0.1', '1', 'CamelCase', 'dashed-version'])(
test.each(['v0.1', '1', 'CamelCase', 'dashed-version'])(
'returns the inputVersion for %s',
async (inputVersion) => {
await expect(Versioning.determineVersion('Custom', inputVersion)).resolves.toStrictEqual(inputVersion);
@ -158,7 +159,7 @@ describe('Versioning', () => {
it('refers to generateSemanticVersion', async () => {
const generateSemanticVersion = jest.spyOn(Versioning, 'generateSemanticVersion').mockResolvedValue('1.3.37');
await expect(Versioning.determineVersion('Semantic')).resolves.toStrictEqual('1.3.37');
await expect(Versioning.determineVersion('Semantic', '')).resolves.toStrictEqual('1.3.37');
expect(generateSemanticVersion).toHaveBeenCalledTimes(1);
});
});
@ -167,7 +168,7 @@ describe('Versioning', () => {
it('refers to generateTagVersion', async () => {
const generateTagVersion = jest.spyOn(Versioning, 'generateTagVersion').mockResolvedValue('0.1');
await expect(Versioning.determineVersion('Tag')).resolves.toStrictEqual('0.1');
await expect(Versioning.determineVersion('Tag', '')).resolves.toStrictEqual('0.1');
expect(generateTagVersion).toHaveBeenCalledTimes(1);
});
});
@ -175,8 +176,9 @@ describe('Versioning', () => {
describe('not implemented strategy', () => {
it('throws a not implemented exception', async () => {
const strategy = 'Test';
// @ts-ignore
jest.spyOn(Versioning, 'strategies', 'get').mockReturnValue({ [strategy]: strategy });
await expect(Versioning.determineVersion(strategy)).rejects.toThrowError(NotImplementedException);
await expect(Versioning.determineVersion(strategy, '')).rejects.toThrowError(NotImplementedException);
});
});
});
@ -231,22 +233,22 @@ describe('Versioning', () => {
describe('fetch', () => {
it('awaits the command', async () => {
jest.spyOn(core, 'warning').mockImplementation(() => {});
jest.spyOn(System, 'run').mockResolvedValue(undefined);
jest.spyOn(System, 'run').mockImplementation();
await expect(Versioning.fetch()).resolves.not.toThrow();
});
it('falls back to the second strategy when the first fails', async () => {
jest.spyOn(core, 'warning').mockImplementation(() => {});
const gitFetch = jest.spyOn(System, 'run').mockResolvedValue(undefined).mockRejectedValueOnce(undefined);
const gitFetch = jest.spyOn(System, 'run').mockImplementation();
await expect(Versioning.fetch()).resolves.not.toThrow();
expect(gitFetch).toHaveBeenCalledTimes(2);
expect(gitFetch).toHaveBeenCalledTimes(1);
});
});
describe('generateSemanticVersion', () => {
it('returns a proper version from description', async () => {
jest.spyOn(System, 'run').mockResolvedValue(undefined);
jest.spyOn(System, 'run').mockImplementation();
jest.spyOn(core, 'info').mockImplementation(() => {});
jest.spyOn(Versioning, 'isDirty').mockResolvedValue(false);
jest.spyOn(Versioning, 'hasAnyVersionTags').mockResolvedValue(true);
@ -262,7 +264,7 @@ describe('Versioning', () => {
});
it('throws when dirty', async () => {
jest.spyOn(System, 'run').mockResolvedValue(undefined);
jest.spyOn(System, 'run').mockImplementation();
jest.spyOn(core, 'info').mockImplementation(() => {});
jest.spyOn(Versioning, 'isDirty').mockResolvedValue(true);
await expect(Versioning.generateSemanticVersion()).rejects.toThrowError();
@ -270,7 +272,7 @@ describe('Versioning', () => {
it('falls back to commits only, when no tags are present', async () => {
const commits = Math.round(Math.random() * 10);
jest.spyOn(System, 'run').mockResolvedValue(undefined);
jest.spyOn(System, 'run').mockImplementation();
jest.spyOn(core, 'info').mockImplementation(() => {});
jest.spyOn(Versioning, 'isDirty').mockResolvedValue(false);
jest.spyOn(Versioning, 'hasAnyVersionTags').mockResolvedValue(false);

View File

@ -79,7 +79,7 @@ export default class Versioning {
return /^v([\d.]+-\w+\.\d+)-(\d+)-g(\w+)-?(\w+)*/g;
}
static async determineVersion(strategy, inputVersion) {
static async determineVersion(strategy: string, inputVersion: string) {
// Validate input
if (!Object.hasOwnProperty.call(this.strategies, strategy)) {
throw new ValidationError(`Versioning strategy should be one of ${Object.values(this.strategies).join(', ')}.`);
@ -174,7 +174,7 @@ export default class Versioning {
commits,
hash,
};
} catch (error) {
} catch {
try {
const [match, tag, commits, hash] = this.descriptionRegex2.exec(description);
@ -184,7 +184,7 @@ export default class Versioning {
commits,
hash,
};
} catch (error_) {
} catch {
try {
const [match, tag, commits, hash] = this.descriptionRegex3.exec(description);
@ -194,7 +194,7 @@ export default class Versioning {
commits,
hash,
};
} catch (error__) {
} catch {
core.warning(
`Failed to parse git describe output or version can not be determined through: "${description}".`,
);

View File

@ -3860,11 +3860,6 @@ locate-path@^5.0.0:
dependencies:
p-locate "^4.1.0"
lodash-es@^4.17.21:
version "4.17.21"
resolved "https://registry.yarnpkg.com/lodash-es/-/lodash-es-4.17.21.tgz#43e626c46e6591b7750beb2b50117390c609e3ee"
integrity sha512-mKnC+QJ9pWVzv+C4/U3rRsHapFfHvQFoFB92e52xeyGMcX6/OlIl78je1u8vePzYZSkkogMPJ2yjxxsb89cxyw==
lodash.get@^4.4.2:
version "4.4.2"
resolved "https://registry.yarnpkg.com/lodash.get/-/lodash.get-4.4.2.tgz#2d177f652fa31e939b4438d5341499dfa3825e99"