Refactor code to comply with ESLint rules

Major refactoring using ESLint with rules from AirBnb and Vue.

Enable most of the ESLint rules and do necessary linting in the code.
Also add more information for rules that are disabled to describe what
they are and why they are disabled.

Allow logging (`console.log`) in test files, and in development mode
(e.g. when working with `npm run serve`), but disable it when
environment is production (as pre-configured by Vue). Also add flag
(`--mode production`) in `lint:eslint` command so production linting is
executed earlier in lifecycle.

Disable rules that requires a separate work. Such as ESLint rules that
are broken in TypeScript: no-useless-constructor (eslint/eslint#14118)
and no-shadow (eslint/eslint#13014).
This commit is contained in:
undergroundwires
2022-01-02 18:20:14 +01:00
parent 96265b75de
commit 5b1fbe1e2f
341 changed files with 16126 additions and 15101 deletions

View File

@@ -5,246 +5,254 @@ import { OperatingSystem } from '@/domain/OperatingSystem';
import { CodeRunner } from '@/infrastructure/CodeRunner';
describe('CodeRunner', () => {
describe('runCode', () => {
it('creates temporary directory recursively', async () => {
// arrange
const expectedDir = 'expected-dir';
const folderName = 'privacy.sexy';
const context = new TestContext();
context.mocks.os.setupTmpdir('tmp');
context.mocks.path.setupJoin(expectedDir, 'tmp', folderName);
describe('runCode', () => {
it('creates temporary directory recursively', async () => {
// arrange
const expectedDir = 'expected-dir';
const folderName = 'privacy.sexy';
const context = new TestContext();
context.mocks.os.setupTmpdir('tmp');
context.mocks.path.setupJoin(expectedDir, 'tmp', folderName);
// act
await context
.withFolderName(folderName)
.runCode();
// act
await context
.withFolderName(folderName)
.runCode();
// assert
expect(context.mocks.fs.mkdirHistory.length).to.equal(1);
expect(context.mocks.fs.mkdirHistory[0].isRecursive).to.equal(true);
expect(context.mocks.fs.mkdirHistory[0].path).to.equal(expectedDir);
});
it('creates a file with expected code and path', async () => {
// arrange
const expectedCode = 'expected-code';
const expectedFilePath = 'expected-file-path';
const extension = '.sh';
const expectedName = `run.${extension}`;
const folderName = 'privacy.sexy';
const context = new TestContext();
context.mocks.os.setupTmpdir('tmp');
context.mocks.path.setupJoin('folder', 'tmp', folderName);
context.mocks.path.setupJoin(expectedFilePath, 'folder', expectedName);
// act
await context
.withCode(expectedCode)
.withFolderName(folderName)
.withExtension(extension)
.runCode();
// assert
expect(context.mocks.fs.writeFileHistory.length).to.equal(1);
expect(context.mocks.fs.writeFileHistory[0].data).to.equal(expectedCode);
expect(context.mocks.fs.writeFileHistory[0].path).to.equal(expectedFilePath);
});
it('set file permissions as expected', async () => {
// arrange
const expectedMode = '755';
const expectedFilePath = 'expected-file-path';
const extension = '.sh';
const expectedName = `run.${extension}`;
const folderName = 'privacy.sexy';
const context = new TestContext();
context.mocks.os.setupTmpdir('tmp');
context.mocks.path.setupJoin('folder', 'tmp', folderName);
context.mocks.path.setupJoin(expectedFilePath, 'folder', expectedName);
// act
await context
.withFolderName(folderName)
.withExtension(extension)
.runCode();
// assert
expect(context.mocks.fs.chmodCallHistory.length).to.equal(1);
expect(context.mocks.fs.chmodCallHistory[0].mode).to.equal(expectedMode);
expect(context.mocks.fs.chmodCallHistory[0].path).to.equal(expectedFilePath);
});
describe('executes as expected', () => {
// arrange
const filePath = 'expected-file-path';
const testData = [ {
os: OperatingSystem.Windows,
expected: filePath,
}, {
os: OperatingSystem.macOS,
expected: `open -a Terminal.app ${filePath}`,
}];
for (const data of testData) {
it(`returns ${data.expected} on ${OperatingSystem[data.os]}`, async () => {
const context = new TestContext();
context.mocks.os.setupTmpdir('non-important-temp-dir-name');
context.mocks.path.setupJoinSequence('non-important-folder-name', filePath);
context.withOs(data.os);
// act
await context
.withOs(data.os)
.runCode();
// assert
expect(context.mocks.child_process.executionHistory.length).to.equal(1);
expect(context.mocks.child_process.executionHistory[0]).to.equal(data.expected);
});
}
});
it('runs in expected order', async () => {
// arrange
const expectedOrder = [ NodeJsCommand.mkdir, NodeJsCommand.writeFile, NodeJsCommand.chmod ];
const context = new TestContext();
context.mocks.os.setupTmpdir('non-important-temp-dir-name');
context.mocks.path.setupJoinSequence('non-important-folder-name1', 'non-important-folder-name2');
// act
await context.runCode();
// assert
const actualOrder = context.mocks.commandHistory.filter((command) => expectedOrder.includes(command));
expect(expectedOrder).to.deep.equal(actualOrder);
});
// assert
expect(context.mocks.fs.mkdirHistory.length).to.equal(1);
expect(context.mocks.fs.mkdirHistory[0].isRecursive).to.equal(true);
expect(context.mocks.fs.mkdirHistory[0].path).to.equal(expectedDir);
});
it('creates a file with expected code and path', async () => {
// arrange
const expectedCode = 'expected-code';
const expectedFilePath = 'expected-file-path';
const extension = '.sh';
const expectedName = `run.${extension}`;
const folderName = 'privacy.sexy';
const context = new TestContext();
context.mocks.os.setupTmpdir('tmp');
context.mocks.path.setupJoin('folder', 'tmp', folderName);
context.mocks.path.setupJoin(expectedFilePath, 'folder', expectedName);
// act
await context
.withCode(expectedCode)
.withFolderName(folderName)
.withExtension(extension)
.runCode();
// assert
expect(context.mocks.fs.writeFileHistory.length).to.equal(1);
expect(context.mocks.fs.writeFileHistory[0].data).to.equal(expectedCode);
expect(context.mocks.fs.writeFileHistory[0].path).to.equal(expectedFilePath);
});
it('set file permissions as expected', async () => {
// arrange
const expectedMode = '755';
const expectedFilePath = 'expected-file-path';
const extension = '.sh';
const expectedName = `run.${extension}`;
const folderName = 'privacy.sexy';
const context = new TestContext();
context.mocks.os.setupTmpdir('tmp');
context.mocks.path.setupJoin('folder', 'tmp', folderName);
context.mocks.path.setupJoin(expectedFilePath, 'folder', expectedName);
// act
await context
.withFolderName(folderName)
.withExtension(extension)
.runCode();
// assert
expect(context.mocks.fs.chmodCallHistory.length).to.equal(1);
expect(context.mocks.fs.chmodCallHistory[0].mode).to.equal(expectedMode);
expect(context.mocks.fs.chmodCallHistory[0].path).to.equal(expectedFilePath);
});
describe('executes as expected', () => {
// arrange
const filePath = 'expected-file-path';
const testData = [{
os: OperatingSystem.Windows,
expected: filePath,
}, {
os: OperatingSystem.macOS,
expected: `open -a Terminal.app ${filePath}`,
}];
for (const data of testData) {
it(`returns ${data.expected} on ${OperatingSystem[data.os]}`, async () => {
const context = new TestContext();
context.mocks.os.setupTmpdir('non-important-temp-dir-name');
context.mocks.path.setupJoinSequence('non-important-folder-name', filePath);
context.withOs(data.os);
// act
await context
.withOs(data.os)
.runCode();
// assert
expect(context.mocks.child_process.executionHistory.length).to.equal(1);
expect(context.mocks.child_process.executionHistory[0]).to.equal(data.expected);
});
}
});
it('runs in expected order', async () => {
// arrange
const expectedOrder = [NodeJsCommand.mkdir, NodeJsCommand.writeFile, NodeJsCommand.chmod];
const context = new TestContext();
context.mocks.os.setupTmpdir('non-important-temp-dir-name');
context.mocks.path.setupJoinSequence('non-important-folder-name1', 'non-important-folder-name2');
// act
await context.runCode();
// assert
const actualOrder = context.mocks.commandHistory
.filter((command) => expectedOrder.includes(command));
expect(expectedOrder).to.deep.equal(actualOrder);
});
});
});
class TestContext {
public mocks = getNodeJsMocks();
public mocks = getNodeJsMocks();
private code: string = 'code';
private folderName: string = 'folderName';
private fileExtension: string = 'fileExtension';
private env = mockEnvironment(OperatingSystem.Windows);
private code = 'code';
public async runCode(): Promise<void> {
const runner = new CodeRunner(this.mocks, this.env);
await runner.runCode(this.code, this.folderName, this.fileExtension);
}
public withOs(os: OperatingSystem) {
this.env = mockEnvironment(os);
return this;
}
public withFolderName(folderName: string) {
this.folderName = folderName;
return this;
}
public withCode(code: string) {
this.code = code;
return this;
}
public withExtension(fileExtension: string) {
this.fileExtension = fileExtension;
return this;
}
private folderName = 'folderName';
private fileExtension = 'fileExtension';
private env = mockEnvironment(OperatingSystem.Windows);
public async runCode(): Promise<void> {
const runner = new CodeRunner(this.mocks, this.env);
await runner.runCode(this.code, this.folderName, this.fileExtension);
}
public withOs(os: OperatingSystem) {
this.env = mockEnvironment(os);
return this;
}
public withFolderName(folderName: string) {
this.folderName = folderName;
return this;
}
public withCode(code: string) {
this.code = code;
return this;
}
public withExtension(fileExtension: string) {
this.fileExtension = fileExtension;
return this;
}
}
function mockEnvironment(os: OperatingSystem) {
return new EnvironmentStub().withOs(os);
return new EnvironmentStub().withOs(os);
}
const enum NodeJsCommand { tmpdir, join, exec, mkdir, writeFile, chmod }
function getNodeJsMocks() {
const commandHistory = new Array<NodeJsCommand>();
return {
os: mockOs(commandHistory),
path: mockPath(commandHistory),
fs: mockNodeFs(commandHistory),
child_process: mockChildProcess(commandHistory),
commandHistory,
};
const commandHistory = new Array<NodeJsCommand>();
return {
os: mockOs(commandHistory),
path: mockPath(commandHistory),
fs: mockNodeFs(commandHistory),
child_process: mockChildProcess(commandHistory),
commandHistory,
};
}
function mockOs(commandHistory: NodeJsCommand[]) {
let tmpDir: string;
return {
setupTmpdir: (value: string): void => {
tmpDir = value;
},
tmpdir: (): string => {
if (!tmpDir) {
throw new Error('tmpdir not set up');
}
commandHistory.push(NodeJsCommand.tmpdir);
return tmpDir;
},
};
let tmpDir: string;
return {
setupTmpdir: (value: string): void => {
tmpDir = value;
},
tmpdir: (): string => {
if (!tmpDir) {
throw new Error('tmpdir not set up');
}
commandHistory.push(NodeJsCommand.tmpdir);
return tmpDir;
},
};
}
function mockPath(commandHistory: NodeJsCommand[]) {
const sequence = new Array<string>();
const scenarios = new Map<string, string>();
const getScenarioKey = (paths: string[]) => paths.join('|');
return {
setupJoin: (returnValue: string, ...paths: string[]): void => {
scenarios.set(getScenarioKey(paths), returnValue);
},
setupJoinSequence: (...valuesToReturn: string[]): void => {
sequence.push(...valuesToReturn);
sequence.reverse();
},
join: (...paths: string[]): string => {
commandHistory.push(NodeJsCommand.join);
if (sequence.length > 0) {
return sequence.pop();
}
const key = getScenarioKey(paths);
if (!scenarios.has(key)) {
return paths.join('/');
}
return scenarios.get(key);
},
};
const sequence = new Array<string>();
const scenarios = new Map<string, string>();
const getScenarioKey = (paths: string[]) => paths.join('|');
return {
setupJoin: (returnValue: string, ...paths: string[]): void => {
scenarios.set(getScenarioKey(paths), returnValue);
},
setupJoinSequence: (...valuesToReturn: string[]): void => {
sequence.push(...valuesToReturn);
sequence.reverse();
},
join: (...paths: string[]): string => {
commandHistory.push(NodeJsCommand.join);
if (sequence.length > 0) {
return sequence.pop();
}
const key = getScenarioKey(paths);
if (!scenarios.has(key)) {
return paths.join('/');
}
return scenarios.get(key);
},
};
}
function mockChildProcess(commandHistory: NodeJsCommand[]) {
const executionHistory = new Array<string>();
return {
exec: (command: string): void => {
commandHistory.push(NodeJsCommand.exec);
executionHistory.push(command);
},
executionHistory,
};
const executionHistory = new Array<string>();
return {
exec: (command: string): void => {
commandHistory.push(NodeJsCommand.exec);
executionHistory.push(command);
},
executionHistory,
};
}
function mockNodeFs(commandHistory: NodeJsCommand[]) {
interface IMkdirCall { path: string; isRecursive: boolean; }
interface IWriteFileCall { path: string; data: string; }
interface IChmodCall { path: string; mode: string | number; }
const mkdirHistory = new Array<IMkdirCall>();
const writeFileHistory = new Array<IWriteFileCall>();
const chmodCallHistory = new Array<IChmodCall>();
return {
promises: {
mkdir: (path, options) => {
commandHistory.push(NodeJsCommand.mkdir);
mkdirHistory.push({ path, isRecursive: options && options.recursive });
return Promise.resolve(path);
},
writeFile: (path, data) => {
commandHistory.push(NodeJsCommand.writeFile);
writeFileHistory.push({ path, data });
return Promise.resolve();
},
chmod: (path, mode) => {
commandHistory.push(NodeJsCommand.chmod);
chmodCallHistory.push({ path, mode });
return Promise.resolve();
},
},
mkdirHistory,
writeFileHistory,
chmodCallHistory,
};
interface IMkdirCall { path: string; isRecursive: boolean; }
interface IWriteFileCall { path: string; data: string; }
interface IChmodCall { path: string; mode: string | number; }
const mkdirHistory = new Array<IMkdirCall>();
const writeFileHistory = new Array<IWriteFileCall>();
const chmodCallHistory = new Array<IChmodCall>();
return {
promises: {
mkdir: (path, options) => {
commandHistory.push(NodeJsCommand.mkdir);
mkdirHistory.push({ path, isRecursive: options && options.recursive });
return Promise.resolve(path);
},
writeFile: (path, data) => {
commandHistory.push(NodeJsCommand.writeFile);
writeFileHistory.push({ path, data });
return Promise.resolve();
},
chmod: (path, mode) => {
commandHistory.push(NodeJsCommand.chmod);
chmodCallHistory.push({ path, mode });
return Promise.resolve();
},
},
mkdirHistory,
writeFileHistory,
chmodCallHistory,
};
}

View File

@@ -4,81 +4,86 @@ import { EventHandler, IEventSource, IEventSubscription } from '@/infrastructure
import { EventSource } from '@/infrastructure/Events/EventSource';
describe('EventSource', () => {
class ObserverMock {
public readonly onReceiveCalls = new Array<number>();
public readonly callbacks = new Array<EventHandler<number>>();
public readonly subscription: IEventSubscription;
constructor(subject: IEventSource<number>) {
this.callbacks.push((arg) => this.onReceiveCalls.push(arg));
this.subscription = subject.on((arg) => this.callbacks.forEach((action) => action(arg)));
}
class ObserverMock {
public readonly onReceiveCalls = new Array<number>();
public readonly callbacks = new Array<EventHandler<number>>();
public readonly subscription: IEventSubscription;
constructor(subject: IEventSource<number>) {
this.callbacks.push((arg) => this.onReceiveCalls.push(arg));
this.subscription = subject.on((arg) => this.callbacks.forEach((action) => action(arg)));
}
let sut: EventSource<number>;
beforeEach(() => sut = new EventSource());
describe('single observer', () => {
// arrange
let observer: ObserverMock;
beforeEach(() => {
observer = new ObserverMock(sut);
});
it('notify() executes the callback', () => {
// act
sut.notify(5);
// assert
expect(observer.onReceiveCalls).to.have.length(1);
});
it('notify() executes the callback with the payload', () => {
const expected = 5;
// act
sut.notify(expected);
// assert
expect(observer.onReceiveCalls).to.deep.equal([expected]);
});
it('notify() does not call callback when unsubscribed', () => {
// act
observer.subscription.unsubscribe();
sut.notify(5);
// assert
expect(observer.onReceiveCalls).to.have.lengthOf(0);
});
}
let sut: EventSource<number>;
beforeEach(() => {
sut = new EventSource();
});
describe('single observer', () => {
// arrange
let observer: ObserverMock;
beforeEach(() => {
observer = new ObserverMock(sut);
});
describe('multiple observers', () => {
// arrange
let observers: ObserverMock[];
beforeEach(() => {
observers = [
new ObserverMock(sut), new ObserverMock(sut),
new ObserverMock(sut), new ObserverMock(sut),
];
});
it('notify() should execute all callbacks', () => {
// act
sut.notify(5);
// assert
observers.forEach((observer) => {
expect(observer.onReceiveCalls).to.have.length(1);
});
});
it('notify() should execute all callbacks with payload', () => {
const expected = 5;
// act
sut.notify(expected);
// assert
observers.forEach((observer) => {
expect(observer.onReceiveCalls).to.deep.equal([expected]);
});
});
it('notify() executes in FIFO order', () => {
// arrange
const expectedSequence = [0, 1, 2, 3];
const actualSequence = new Array<number>();
for (let i = 0; i < observers.length; i++) {
observers[i].callbacks.push(() => actualSequence.push(i));
}
// act
sut.notify(5);
// assert
expect(actualSequence).to.deep.equal(expectedSequence);
});
it('notify() executes the callback', () => {
// act
sut.notify(5);
// assert
expect(observer.onReceiveCalls).to.have.length(1);
});
it('notify() executes the callback with the payload', () => {
const expected = 5;
// act
sut.notify(expected);
// assert
expect(observer.onReceiveCalls).to.deep.equal([expected]);
});
it('notify() does not call callback when unsubscribed', () => {
// act
observer.subscription.unsubscribe();
sut.notify(5);
// assert
expect(observer.onReceiveCalls).to.have.lengthOf(0);
});
});
describe('multiple observers', () => {
// arrange
let observers: ObserverMock[];
beforeEach(() => {
observers = [
new ObserverMock(sut), new ObserverMock(sut),
new ObserverMock(sut), new ObserverMock(sut),
];
});
it('notify() should execute all callbacks', () => {
// act
sut.notify(5);
// assert
observers.forEach((observer) => {
expect(observer.onReceiveCalls).to.have.length(1);
});
});
it('notify() should execute all callbacks with payload', () => {
const expected = 5;
// act
sut.notify(expected);
// assert
observers.forEach((observer) => {
expect(observer.onReceiveCalls).to.deep.equal([expected]);
});
});
it('notify() executes in FIFO order', () => {
// arrange
const expectedSequence = [0, 1, 2, 3];
const actualSequence = new Array<number>();
for (let i = 0; i < observers.length; i++) {
observers[i].callbacks.push(() => actualSequence.push(i));
}
// act
sut.notify(5);
// assert
expect(actualSequence).to.deep.equal(expectedSequence);
});
});
});

View File

@@ -4,19 +4,19 @@ import { EventSubscriptionCollection } from '@/infrastructure/Events/EventSubscr
import { IEventSubscription } from '@/infrastructure/Events/IEventSource';
describe('EventSubscriptionCollection', () => {
it('unsubscribeAll unsubscribes from all registered subscriptions', () => {
// arrange
const sut = new EventSubscriptionCollection();
const expected = [ 'unsubscribed1', 'unsubscribed2'];
const actual = new Array<string>();
const subscriptions: IEventSubscription[] = [
{ unsubscribe: () => actual.push(expected[0]) },
{ unsubscribe: () => actual.push(expected[1]) },
];
// act
sut.register(...subscriptions);
sut.unsubscribeAll();
// assert
expect(actual).to.deep.equal(expected);
});
it('unsubscribeAll unsubscribes from all registered subscriptions', () => {
// arrange
const sut = new EventSubscriptionCollection();
const expected = ['unsubscribed1', 'unsubscribed2'];
const actual = new Array<string>();
const subscriptions: IEventSubscription[] = [
{ unsubscribe: () => actual.push(expected[0]) },
{ unsubscribe: () => actual.push(expected[1]) },
];
// act
sut.register(...subscriptions);
sut.unsubscribeAll();
// assert
expect(actual).to.deep.equal(expected);
});
});

View File

@@ -4,118 +4,123 @@ import { NumericEntityStub } from '@tests/unit/stubs/NumericEntityStub';
import { InMemoryRepository } from '@/infrastructure/Repository/InMemoryRepository';
describe('InMemoryRepository', () => {
describe('exists', () => {
const sut = new InMemoryRepository<number, NumericEntityStub>(
[new NumericEntityStub(1), new NumericEntityStub(2), new NumericEntityStub(3)]);
describe('exists', () => {
const sut = new InMemoryRepository<number, NumericEntityStub>(
[new NumericEntityStub(1), new NumericEntityStub(2), new NumericEntityStub(3)],
);
describe('item exists', () => {
const actual = sut.exists(1);
it('returns true', () => expect(actual).to.be.true);
});
describe('item does not exist', () => {
const actual = sut.exists(99);
it('returns false', () => expect(actual).to.be.false);
});
describe('item exists', () => {
const actual = sut.exists(1);
it('returns true', () => expect(actual).to.be.true);
});
it('getItems gets initial items', () => {
// arrange
const expected = [
new NumericEntityStub(1), new NumericEntityStub(2), new NumericEntityStub(3), new NumericEntityStub(4)];
// act
const sut = new InMemoryRepository<number, NumericEntityStub>(expected);
const actual = sut.getItems();
// assert
expect(actual).to.deep.equal(expected);
describe('item does not exist', () => {
const actual = sut.exists(99);
it('returns false', () => expect(actual).to.be.false);
});
it('addItem adds', () => {
// arrange
const sut = new InMemoryRepository<number, NumericEntityStub>();
const expected = {
length: 1,
item: new NumericEntityStub(1),
};
});
it('getItems gets initial items', () => {
// arrange
const expected = [
new NumericEntityStub(1), new NumericEntityStub(2),
new NumericEntityStub(3), new NumericEntityStub(4),
];
// act
sut.addItem(expected.item);
const actual = {
length: sut.length,
item: sut.getItems()[0],
};
// act
const sut = new InMemoryRepository<number, NumericEntityStub>(expected);
const actual = sut.getItems();
// assert
expect(actual.length).to.equal(expected.length);
expect(actual.item).to.deep.equal(expected.item);
});
it('removeItem removes', () => {
// arrange
const initialItems = [
new NumericEntityStub(1), new NumericEntityStub(2), new NumericEntityStub(3), new NumericEntityStub(4)];
const idToDelete = 3;
const expected = {
length: 3,
items: [new NumericEntityStub(1), new NumericEntityStub(2), new NumericEntityStub(4)],
};
const sut = new InMemoryRepository<number, NumericEntityStub>(initialItems);
// assert
expect(actual).to.deep.equal(expected);
});
it('addItem adds', () => {
// arrange
const sut = new InMemoryRepository<number, NumericEntityStub>();
const expected = {
length: 1,
item: new NumericEntityStub(1),
};
// act
sut.removeItem(idToDelete);
const actual = {
length: sut.length,
items: sut.getItems(),
};
// act
sut.addItem(expected.item);
const actual = {
length: sut.length,
item: sut.getItems()[0],
};
// assert
expect(actual.length).to.equal(expected.length);
expect(actual.items).to.deep.equal(expected.items);
// assert
expect(actual.length).to.equal(expected.length);
expect(actual.item).to.deep.equal(expected.item);
});
it('removeItem removes', () => {
// arrange
const initialItems = [
new NumericEntityStub(1), new NumericEntityStub(2),
new NumericEntityStub(3), new NumericEntityStub(4),
];
const idToDelete = 3;
const expected = {
length: 3,
items: [new NumericEntityStub(1), new NumericEntityStub(2), new NumericEntityStub(4)],
};
const sut = new InMemoryRepository<number, NumericEntityStub>(initialItems);
// act
sut.removeItem(idToDelete);
const actual = {
length: sut.length,
items: sut.getItems(),
};
// assert
expect(actual.length).to.equal(expected.length);
expect(actual.items).to.deep.equal(expected.items);
});
describe('addOrUpdateItem', () => {
it('adds when item does not exist', () => {
// arrange
const initialItems = [new NumericEntityStub(1), new NumericEntityStub(2)];
const newItem = new NumericEntityStub(3);
const expected = [...initialItems, newItem];
const sut = new InMemoryRepository<number, NumericEntityStub>(initialItems);
// act
sut.addOrUpdateItem(newItem);
// assert
const actual = sut.getItems();
expect(actual).to.deep.equal(expected);
});
describe('addOrUpdateItem', () => {
it('adds when item does not exist', () => {
// arrange
const initialItems = [ new NumericEntityStub(1), new NumericEntityStub(2) ];
const newItem = new NumericEntityStub(3);
const expected = [ ...initialItems, newItem ];
const sut = new InMemoryRepository<number, NumericEntityStub>(initialItems);
// act
sut.addOrUpdateItem(newItem);
// assert
const actual = sut.getItems();
expect(actual).to.deep.equal(expected);
});
it('updates when item exists', () => {
// arrange
const initialItems = [ new NumericEntityStub(1).withCustomProperty('bca') ];
const updatedItem = new NumericEntityStub(1).withCustomProperty('abc');
const expected = [ updatedItem ];
const sut = new InMemoryRepository<number, NumericEntityStub>(initialItems);
// act
sut.addOrUpdateItem(updatedItem);
// assert
const actual = sut.getItems();
expect(actual).to.deep.equal(expected);
});
it('updates when item exists', () => {
// arrange
const initialItems = [new NumericEntityStub(1).withCustomProperty('bca')];
const updatedItem = new NumericEntityStub(1).withCustomProperty('abc');
const expected = [updatedItem];
const sut = new InMemoryRepository<number, NumericEntityStub>(initialItems);
// act
sut.addOrUpdateItem(updatedItem);
// assert
const actual = sut.getItems();
expect(actual).to.deep.equal(expected);
});
describe('getById', () => {
it('gets entity if it exists', () => {
// arrange
const expected = new NumericEntityStub(1).withCustomProperty('bca');
const sut = new InMemoryRepository<number, NumericEntityStub>([
expected, new NumericEntityStub(2).withCustomProperty('bca'),
new NumericEntityStub(3).withCustomProperty('bca'), new NumericEntityStub(4).withCustomProperty('bca'),
]);
// act
const actual = sut.getById(expected.id);
// assert
expect(actual).to.deep.equal(expected);
});
it('gets undefined if it does not exist', () => {
// arrange
const sut = new InMemoryRepository<number, NumericEntityStub>([]);
// act
const actual = sut.getById(31);
// assert
expect(actual).to.equal(undefined);
});
});
describe('getById', () => {
it('gets entity if it exists', () => {
// arrange
const expected = new NumericEntityStub(1).withCustomProperty('bca');
const sut = new InMemoryRepository<number, NumericEntityStub>([
expected, new NumericEntityStub(2).withCustomProperty('bca'),
new NumericEntityStub(3).withCustomProperty('bca'), new NumericEntityStub(4).withCustomProperty('bca'),
]);
// act
const actual = sut.getById(expected.id);
// assert
expect(actual).to.deep.equal(expected);
});
it('gets undefined if it does not exist', () => {
// arrange
const sut = new InMemoryRepository<number, NumericEntityStub>([]);
// act
const actual = sut.getById(31);
// assert
expect(actual).to.equal(undefined);
});
});
});

View File

@@ -4,50 +4,53 @@ import { AsyncLazy } from '@/infrastructure/Threading/AsyncLazy';
import { sleep } from '@/infrastructure/Threading/AsyncSleep';
describe('AsyncLazy', () => {
it('returns value from lambda', async () => {
// arrange
const expected = 'test';
const lambda = () => Promise.resolve(expected);
const sut = new AsyncLazy(lambda);
// act
const actual = await sut.getValue();
// assert
expect(actual).to.equal(expected);
it('returns value from lambda', async () => {
// arrange
const expected = 'test';
const lambda = () => Promise.resolve(expected);
const sut = new AsyncLazy(lambda);
// act
const actual = await sut.getValue();
// assert
expect(actual).to.equal(expected);
});
describe('when running multiple times', () => {
// arrange
let totalExecuted = 0;
beforeEach(() => {
totalExecuted = 0;
});
describe('when running multiple times', () => {
// arrange
let totalExecuted: number = 0;
beforeEach(() => totalExecuted = 0);
it('when running sync', async () => {
// act
const sut = new AsyncLazy(() => {
totalExecuted++;
return Promise.resolve(totalExecuted);
});
const results = new Array<number>();
for (let i = 0; i < 5; i++) {
results.push(await sut.getValue());
}
// assert
expect(totalExecuted).to.equal(1);
expect(results).to.deep.equal([1, 1, 1, 1, 1]);
});
it('when running long-running task in parallel', async () => {
// act
const sut = new AsyncLazy(async () => {
await sleep(100);
totalExecuted++;
return Promise.resolve(totalExecuted);
});
const results = await Promise.all([
sut.getValue(),
sut.getValue(),
sut.getValue(),
sut.getValue(),
sut.getValue()]);
// assert
expect(totalExecuted).to.equal(1);
expect(results).to.deep.equal([1, 1, 1, 1, 1]);
});
it('when running sync', async () => {
// act
const sut = new AsyncLazy(() => {
totalExecuted++;
return Promise.resolve(totalExecuted);
});
const results = new Array<number>();
for (let i = 0; i < 5; i++) {
// eslint-disable-next-line no-await-in-loop
results.push(await sut.getValue());
}
// assert
expect(totalExecuted).to.equal(1);
expect(results).to.deep.equal([1, 1, 1, 1, 1]);
});
it('when running long-running task in parallel', async () => {
// act
const sut = new AsyncLazy(async () => {
await sleep(100);
totalExecuted++;
return Promise.resolve(totalExecuted);
});
const results = await Promise.all([
sut.getValue(),
sut.getValue(),
sut.getValue(),
sut.getValue(),
sut.getValue()]);
// assert
expect(totalExecuted).to.equal(1);
expect(results).to.deep.equal([1, 1, 1, 1, 1]);
});
});
});

View File

@@ -1,81 +1,85 @@
import 'mocha';
import { expect } from 'chai';
import { sleep, SchedulerType } from '@/infrastructure/Threading/AsyncSleep';
import { sleep, SchedulerType, SchedulerCallbackType } from '@/infrastructure/Threading/AsyncSleep';
describe('AsyncSleep', () => {
describe('sleep', () => {
it('fulfills after delay', async () => {
// arrange
const delayInMs = 10;
const scheduler = new SchedulerMock();
// act
const promise = sleep(delayInMs, scheduler.mock);
const promiseState = watchPromiseState(promise);
scheduler.tickNext(delayInMs);
await flushPromiseResolutionQueue();
// assert
const actual = promiseState.isFulfilled();
expect(actual).to.equal(true);
});
it('pending before delay', async () => {
// arrange
const delayInMs = 10;
const scheduler = new SchedulerMock();
// act
const promise = sleep(delayInMs, scheduler.mock);
const promiseState = watchPromiseState(promise);
scheduler.tickNext(delayInMs / 5);
await flushPromiseResolutionQueue();
// assert
const actual = promiseState.isPending();
expect(actual).to.equal(true);
});
describe('sleep', () => {
it('fulfills after delay', async () => {
// arrange
const delayInMs = 10;
const scheduler = new SchedulerMock();
// act
const promise = sleep(delayInMs, scheduler.mock);
const promiseState = watchPromiseState(promise);
scheduler.tickNext(delayInMs);
await flushPromiseResolutionQueue();
// assert
const actual = promiseState.isFulfilled();
expect(actual).to.equal(true);
});
it('pending before delay', async () => {
// arrange
const delayInMs = 10;
const scheduler = new SchedulerMock();
// act
const promise = sleep(delayInMs, scheduler.mock);
const promiseState = watchPromiseState(promise);
scheduler.tickNext(delayInMs / 5);
await flushPromiseResolutionQueue();
// assert
const actual = promiseState.isPending();
expect(actual).to.equal(true);
});
});
});
function flushPromiseResolutionQueue() {
return Promise.resolve();
return Promise.resolve();
}
class SchedulerMock {
public readonly mock: SchedulerType;
private currentTime = 0;
private scheduledActions = new Array<{time: number, action: (...args: any[]) => void}>();
constructor() {
this.mock = (callback: (...args: any[]) => void, ms: number) => {
this.scheduledActions.push({ time: this.currentTime + ms, action: callback });
};
}
public tickNext(ms: number) {
const newTime = this.currentTime + ms;
let newActions = this.scheduledActions;
for (const action of this.scheduledActions) {
if (newTime >= action.time) {
newActions = newActions.filter((a) => a !== action);
action.action();
}
}
this.scheduledActions = newActions;
public readonly mock: SchedulerType;
private currentTime = 0;
private scheduledActions = new Array<{time: number, action: SchedulerCallbackType}>();
constructor() {
this.mock = (callback: SchedulerCallbackType, ms: number) => {
this.scheduledActions.push({ time: this.currentTime + ms, action: callback });
};
}
public tickNext(ms: number) {
const newTime = this.currentTime + ms;
let newActions = this.scheduledActions;
for (const action of this.scheduledActions) {
if (newTime >= action.time) {
newActions = newActions.filter((a) => a !== action);
action.action();
}
}
this.scheduledActions = newActions;
}
}
function watchPromiseState<T>(promise: Promise<T>) {
let isPending = true;
let isRejected = false;
let isFulfilled = false;
promise.then(
() => {
isFulfilled = true;
isPending = false;
},
() => {
isRejected = true;
isPending = false;
},
);
return {
isFulfilled: () => isFulfilled,
isPending: () => isPending,
isRejected: () => isRejected,
};
let isPending = true;
let isRejected = false;
let isFulfilled = false;
promise.then(
() => {
isFulfilled = true;
isPending = false;
},
() => {
isRejected = true;
isPending = false;
},
);
return {
isFulfilled: () => isFulfilled,
isPending: () => isPending,
isRejected: () => isRejected,
};
}