Fix handling special chars in script paths
This commit improves the handling of paths with spaces or special characters during script execution in the desktop application. Key improvements: - Paths are now quoted for macOS/Linux, addressing issues with whitespace or single quotes. - Windows paths are enclosed in double quotes to handle special characters. Other supporting changes: - Add more documentation for terminal execution commands. - Refactor terminal script file execution into a dedicated file for improved separation of concerns. - Refactor naming of `RuntimeEnvironment` to align with naming conventions (no interface with I prefix) and for clarity. - Refactor `TemporaryFileCodeRunner` to simplify it by removing the `os` parameter and handling OS-specific logic within the filename generator instead. - Refactor `fileName` to `filename` for consistency.
This commit is contained in:
@@ -0,0 +1,203 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
||||
import { VisibleTerminalScriptExecutor } from '@/infrastructure/CodeRunner/Execution/VisibleTerminalScriptFileExecutor';
|
||||
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { CommandOpsStub } from '@tests/unit/shared/Stubs/CommandOpsStub';
|
||||
import { SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
|
||||
describe('VisibleTerminalScriptFileExecutor', () => {
|
||||
describe('executeScriptFile', () => {
|
||||
describe('throws error for invalid operating systems', () => {
|
||||
const testScenarios: ReadonlyArray<{
|
||||
readonly description: string;
|
||||
readonly invalidOs?: OperatingSystem;
|
||||
readonly expectedError: string;
|
||||
}> = [
|
||||
(() => {
|
||||
const unsupportedOs = OperatingSystem.Android;
|
||||
return {
|
||||
description: 'unsupported OS',
|
||||
invalidOs: unsupportedOs,
|
||||
expectedError: `Unsupported operating system: ${OperatingSystem[unsupportedOs]}`,
|
||||
};
|
||||
})(),
|
||||
{
|
||||
description: 'undefined OS',
|
||||
invalidOs: undefined,
|
||||
expectedError: 'Unknown operating system',
|
||||
},
|
||||
];
|
||||
testScenarios.forEach(({ description, invalidOs, expectedError }) => {
|
||||
it(description, async () => {
|
||||
// arrange
|
||||
const context = new ScriptFileTestSetup()
|
||||
.withOs(invalidOs);
|
||||
// act
|
||||
const act = async () => { await context.executeScriptFile(); };
|
||||
// assert
|
||||
await expectThrowsAsync(act, expectedError);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('command execution', () => {
|
||||
// arrange
|
||||
const testScenarios: Record<SupportedOperatingSystem, readonly {
|
||||
readonly filePath: string;
|
||||
readonly expectedCommand: string;
|
||||
readonly description: string;
|
||||
}[]> = {
|
||||
[OperatingSystem.Windows]: [
|
||||
{
|
||||
description: 'encloses path in quotes',
|
||||
filePath: 'file',
|
||||
expectedCommand: '"file"',
|
||||
},
|
||||
],
|
||||
[OperatingSystem.macOS]: [
|
||||
{
|
||||
description: 'encloses path in quotes',
|
||||
filePath: 'file',
|
||||
expectedCommand: 'open -a Terminal.app \'file\'',
|
||||
},
|
||||
{
|
||||
description: 'escapes single quotes in path',
|
||||
filePath: 'f\'i\'le',
|
||||
expectedCommand: 'open -a Terminal.app \'f\'\\\'\'i\'\\\'\'le\'',
|
||||
},
|
||||
],
|
||||
[OperatingSystem.Linux]: [
|
||||
{
|
||||
description: 'encloses path in quotes',
|
||||
filePath: 'file',
|
||||
expectedCommand: 'x-terminal-emulator -e \'file\'',
|
||||
},
|
||||
{
|
||||
description: 'escapes single quotes in path',
|
||||
filePath: 'f\'i\'le',
|
||||
expectedCommand: 'x-terminal-emulator -e \'f\'\\\'\'i\'\\\'\'le\'',
|
||||
},
|
||||
],
|
||||
};
|
||||
AllSupportedOperatingSystems.forEach((operatingSystem) => {
|
||||
describe(`on ${OperatingSystem[operatingSystem]}`, () => {
|
||||
testScenarios[operatingSystem].forEach((
|
||||
{ description, filePath, expectedCommand },
|
||||
) => {
|
||||
it(description, async () => {
|
||||
// arrange
|
||||
const command = new CommandOpsStub();
|
||||
const context = new ScriptFileTestSetup()
|
||||
.withOs(operatingSystem)
|
||||
.withFilePath(filePath)
|
||||
.withSystemOperations(new SystemOperationsStub().withCommand(command));
|
||||
|
||||
// act
|
||||
await context.executeScriptFile();
|
||||
|
||||
// assert
|
||||
const calls = command.callHistory.filter((c) => c.methodName === 'exec');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualCommand] = calls[0].args;
|
||||
expect(actualCommand).to.equal(expectedCommand);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('file permissions', () => {
|
||||
it('sets permissions before execution', async () => {
|
||||
// arrange
|
||||
let isExecutedAfterPermissions = false;
|
||||
let isPermissionsSet = false;
|
||||
const fileSystemMock = new FileSystemOpsStub();
|
||||
fileSystemMock.setFilePermissions = () => {
|
||||
isPermissionsSet = true;
|
||||
return Promise.resolve();
|
||||
};
|
||||
const commandMock = new CommandOpsStub();
|
||||
commandMock.exec = () => {
|
||||
isExecutedAfterPermissions = isPermissionsSet;
|
||||
return Promise.resolve();
|
||||
};
|
||||
const context = new ScriptFileTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withFileSystem(fileSystemMock)
|
||||
.withCommand(commandMock));
|
||||
|
||||
// act
|
||||
await context.executeScriptFile();
|
||||
|
||||
// assert
|
||||
expect(isExecutedAfterPermissions).to.equal(true);
|
||||
});
|
||||
it('applies correct permissions', async () => {
|
||||
// arrange
|
||||
const expectedMode = '755';
|
||||
const fileSystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub().withFileSystem(fileSystem));
|
||||
|
||||
// act
|
||||
await context.executeScriptFile();
|
||||
|
||||
// assert
|
||||
const calls = fileSystem.callHistory.filter((call) => call.methodName === 'setFilePermissions');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [, actualMode] = calls[0].args;
|
||||
expect(actualMode).to.equal(expectedMode);
|
||||
});
|
||||
it('sets permissions on the correct file', async () => {
|
||||
// arrange
|
||||
const expectedFilePath = 'expected-file-path';
|
||||
const fileSystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileTestSetup()
|
||||
.withFilePath(expectedFilePath)
|
||||
.withSystemOperations(new SystemOperationsStub().withFileSystem(fileSystem));
|
||||
|
||||
// act
|
||||
await context.executeScriptFile();
|
||||
|
||||
// assert
|
||||
const calls = fileSystem.callHistory.filter((call) => call.methodName === 'setFilePermissions');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
expect(actualFilePath).to.equal(expectedFilePath);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class ScriptFileTestSetup {
|
||||
private os?: OperatingSystem = OperatingSystem.Windows;
|
||||
|
||||
private filePath = `[${ScriptFileTestSetup.name}] file path`;
|
||||
|
||||
private system: SystemOperations = new SystemOperationsStub();
|
||||
|
||||
public withOs(os: OperatingSystem | undefined): this {
|
||||
this.os = os;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withSystemOperations(system: SystemOperations): this {
|
||||
this.system = system;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFilePath(filePath: string): this {
|
||||
this.filePath = filePath;
|
||||
return this;
|
||||
}
|
||||
|
||||
public executeScriptFile(): Promise<void> {
|
||||
const environment = new RuntimeEnvironmentStub().withOs(this.os);
|
||||
const logger = new LoggerStub();
|
||||
const executor = new VisibleTerminalScriptExecutor(this.system, logger, environment);
|
||||
return executor.executeScriptFile(this.filePath);
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { generateOsTimestampedFileName } from '@/infrastructure/CodeRunner/FileNameGenerator';
|
||||
import { OsTimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Filename/OsTimestampedFilenameGenerator';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
|
||||
|
||||
describe('FileNameGenerator', () => {
|
||||
describe('generateOsTimestampedFileName', () => {
|
||||
describe('OsTimestampedFilenameGenerator', () => {
|
||||
describe('generateFilename', () => {
|
||||
it('generates correct prefix', () => {
|
||||
// arrange
|
||||
const expectedPrefix = 'run';
|
||||
// act
|
||||
const fileName = generateFileNamePartsForTesting();
|
||||
const filename = generateFilenamePartsForTesting();
|
||||
// assert
|
||||
expect(fileName.prefix).to.equal(expectedPrefix);
|
||||
expect(filename.prefix).to.equal(expectedPrefix);
|
||||
});
|
||||
it('generates correct timestamp', () => {
|
||||
// arrange
|
||||
@@ -20,10 +21,10 @@ describe('FileNameGenerator', () => {
|
||||
const expectedTimestamp = '2023-01-01_12-00-00';
|
||||
const date = new Date(currentDate);
|
||||
// act
|
||||
const fileName = generateFileNamePartsForTesting({ date });
|
||||
const filename = generateFilenamePartsForTesting({ date });
|
||||
// assert
|
||||
expect(fileName.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[
|
||||
`Generated file name: ${fileName.generatedFileName}`
|
||||
expect(filename.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[
|
||||
`Generated file name: ${filename.generatedFileName}`
|
||||
]);
|
||||
});
|
||||
describe('generates correct extension', () => {
|
||||
@@ -37,21 +38,37 @@ describe('FileNameGenerator', () => {
|
||||
// arrange
|
||||
const expectedExtension = testScenarios[operatingSystem];
|
||||
// act
|
||||
const fileName = generateFileNamePartsForTesting({ operatingSystem });
|
||||
const filename = generateFilenamePartsForTesting({ operatingSystem });
|
||||
// assert
|
||||
expect(fileName.extension).to.equal(expectedExtension, formatAssertionMessage[
|
||||
`Generated file name: ${fileName.generatedFileName}`
|
||||
expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[
|
||||
`Generated file name: ${filename.generatedFileName}`
|
||||
]);
|
||||
});
|
||||
});
|
||||
});
|
||||
it('generates filename without extension for unknown OS', () => {
|
||||
describe('generates filename without extension for unknown OS', () => {
|
||||
// arrange
|
||||
const unknownOs = 'Unknown' as unknown as OperatingSystem;
|
||||
// act
|
||||
const fileName = generateFileNamePartsForTesting({ operatingSystem: unknownOs });
|
||||
// assert
|
||||
expect(fileName.extension).toBeUndefined();
|
||||
const testScenarios: ReadonlyArray<{
|
||||
readonly description: string;
|
||||
readonly unknownOs?: OperatingSystem;
|
||||
}> = [
|
||||
{
|
||||
description: 'unsupported OS',
|
||||
unknownOs: 'Unsupported' as unknown as OperatingSystem,
|
||||
},
|
||||
{
|
||||
description: 'undefined OS',
|
||||
unknownOs: undefined,
|
||||
},
|
||||
];
|
||||
testScenarios.forEach(({ description, unknownOs }) => {
|
||||
it(description, () => {
|
||||
// act
|
||||
const filename = generateFilenamePartsForTesting({ operatingSystem: unknownOs });
|
||||
// assert
|
||||
expect(filename.extension).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -63,20 +80,22 @@ interface TestFileNameComponents {
|
||||
readonly generatedFileName: string;
|
||||
}
|
||||
|
||||
function generateFileNamePartsForTesting(testScenario?: {
|
||||
function generateFilenamePartsForTesting(testScenario?: {
|
||||
operatingSystem?: OperatingSystem,
|
||||
date?: Date,
|
||||
}): TestFileNameComponents {
|
||||
const operatingSystem = testScenario?.operatingSystem ?? OperatingSystem.Windows;
|
||||
const date = testScenario?.date ?? new Date();
|
||||
const fileName = generateOsTimestampedFileName(operatingSystem, date);
|
||||
const sut = new OsTimestampedFilenameGenerator(
|
||||
new RuntimeEnvironmentStub().withOs(testScenario?.operatingSystem),
|
||||
);
|
||||
const filename = sut.generateFilename(date);
|
||||
const pattern = /^(?<prefix>[^-]+)-(?<timestamp>[^.]+)(?:\.(?<extension>[^.]+))?$/; // prefix-timestamp.extension
|
||||
const match = fileName.match(pattern);
|
||||
const match = filename.match(pattern);
|
||||
if (!match?.groups?.prefix || !match?.groups?.timestamp) {
|
||||
throw new Error(`Failed to parse prefix or timestamp: ${fileName}`);
|
||||
throw new Error(`Failed to parse prefix or timestamp: ${filename}`);
|
||||
}
|
||||
return {
|
||||
generatedFileName: fileName,
|
||||
generatedFileName: filename,
|
||||
prefix: match.groups.prefix,
|
||||
timestamp: match.groups.timestamp,
|
||||
extension: match.groups.extension,
|
||||
@@ -1,18 +1,18 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { FileSystemOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
import { FileNameGenerator, TemporaryFileCodeRunner } from '@/infrastructure/CodeRunner/TemporaryFileCodeRunner';
|
||||
import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
||||
import { TemporaryFileCodeRunner } from '@/infrastructure/CodeRunner/TemporaryFileCodeRunner';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub';
|
||||
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
import { CommandOpsStub } from '@tests/unit/shared/Stubs/CommandOpsStub';
|
||||
import { FunctionKeys } from '@/TypeHelpers';
|
||||
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { FilenameGenerator } from '@/infrastructure/CodeRunner/Filename/FilenameGenerator';
|
||||
import { FilenameGeneratorStub } from '@tests/unit/shared/Stubs/FilenameGeneratorStub';
|
||||
import { ScriptFileExecutor } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
|
||||
import { ScriptFileExecutorStub } from '@tests/unit/shared/Stubs/ScriptFileExecutorStub';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
|
||||
describe('TemporaryFileCodeRunner', () => {
|
||||
describe('runCode', () => {
|
||||
@@ -69,26 +69,6 @@ describe('TemporaryFileCodeRunner', () => {
|
||||
const [, actualData] = calls[0].args;
|
||||
expect(actualData).to.equal(expectedCode);
|
||||
});
|
||||
it('generates file name for correct operating system', async () => {
|
||||
// arrange
|
||||
const expectedOperatingSystem = OperatingSystem.macOS;
|
||||
const calls = new Array<OperatingSystem>();
|
||||
const fileNameGenerator: FileNameGenerator = (operatingSystem) => {
|
||||
calls.push(operatingSystem);
|
||||
return 'unimportant file name';
|
||||
};
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withOs(expectedOperatingSystem)
|
||||
.withFileNameGenerator(fileNameGenerator);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
expect(calls).to.have.lengthOf(1);
|
||||
const [actualOperatingSystem] = calls;
|
||||
expect(actualOperatingSystem).to.equal(expectedOperatingSystem);
|
||||
});
|
||||
it('creates file in expected directory', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
@@ -128,9 +108,9 @@ describe('TemporaryFileCodeRunner', () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const expectedFileName = 'expected-script-file-name';
|
||||
const expectedFilename = 'expected-script-file-name';
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileNameGenerator(() => expectedFileName)
|
||||
.withFileNameGenerator(new FilenameGeneratorStub().withFilename(expectedFilename))
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withFileSystem(filesystem)
|
||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator)));
|
||||
@@ -149,99 +129,10 @@ describe('TemporaryFileCodeRunner', () => {
|
||||
`Actual file path: ${actualFilePath}`,
|
||||
]));
|
||||
});
|
||||
});
|
||||
describe('file permissions', () => {
|
||||
it('sets correct permissions', async () => {
|
||||
// arrange
|
||||
const expectedMode = '755';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'setFilePermissions');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [, actualMode] = calls[0].args;
|
||||
expect(actualMode).to.equal(expectedMode);
|
||||
});
|
||||
it('sets correct permissions on correct file', async () => {
|
||||
// arrange
|
||||
const expectedFilePath = 'expected-file-path';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const extension = '.sh';
|
||||
const expectedName = `run.${extension}`;
|
||||
const folderName = 'privacy.sexy';
|
||||
const temporaryDirName = 'tmp';
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withOperatingSystem(
|
||||
new OperatingSystemOpsStub()
|
||||
.withTemporaryDirectoryResult(temporaryDirName),
|
||||
)
|
||||
.withLocation(
|
||||
new LocationOpsStub()
|
||||
.withJoinResult('folder', temporaryDirName, folderName)
|
||||
.withJoinResult(expectedFilePath, 'folder', expectedName),
|
||||
)
|
||||
.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
await context
|
||||
.withFolderName(folderName)
|
||||
.withFileNameGenerator(() => expectedName)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'setFilePermissions');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
expect(actualFilePath).to.equal(expectedFilePath);
|
||||
});
|
||||
});
|
||||
describe('file execution', () => {
|
||||
describe('executes correct command', () => {
|
||||
// arrange
|
||||
const filePath = 'executed-file-path';
|
||||
const testScenarios: Record<SupportedOperatingSystem, string> = {
|
||||
[OperatingSystem.Windows]: filePath,
|
||||
[OperatingSystem.macOS]: `open -a Terminal.app ${filePath}`,
|
||||
[OperatingSystem.Linux]: `x-terminal-emulator -e '${filePath}'`,
|
||||
};
|
||||
AllSupportedOperatingSystems.forEach((operatingSystem) => {
|
||||
it(`returns correctly for ${OperatingSystem[operatingSystem]}`, async () => {
|
||||
// arrange
|
||||
const expectedCommand = testScenarios[operatingSystem];
|
||||
const command = new CommandOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileNameGenerator(() => filePath)
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withLocation(
|
||||
new LocationOpsStub()
|
||||
.withJoinResultSequence('non-important-folder-name', filePath),
|
||||
)
|
||||
.withCommand(command));
|
||||
|
||||
// act
|
||||
await context
|
||||
.withOs(operatingSystem)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = command.callHistory.filter((c) => c.methodName === 'execute');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualCommand] = calls[0].args;
|
||||
expect(actualCommand).to.equal(expectedCommand);
|
||||
});
|
||||
});
|
||||
});
|
||||
it('runs in expected order', async () => { // verifies correct `async`, `await` usage.
|
||||
it('creates file after creating the directory', async () => {
|
||||
const expectedOrder: readonly FunctionKeys<FileSystemOps>[] = [
|
||||
'createDirectory',
|
||||
'writeToFile',
|
||||
'setFilePermissions',
|
||||
];
|
||||
const fileSystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
@@ -258,31 +149,50 @@ describe('TemporaryFileCodeRunner', () => {
|
||||
expect(expectedOrder).to.deep.equal(actualOrder);
|
||||
});
|
||||
});
|
||||
describe('throws with invalid OS', () => {
|
||||
const testScenarios: ReadonlyArray<{
|
||||
readonly description: string;
|
||||
readonly invalidOs: OperatingSystem;
|
||||
readonly expectedError: string;
|
||||
}> = [
|
||||
(() => {
|
||||
const unsupportedOs = OperatingSystem.Android;
|
||||
return {
|
||||
description: 'unsupported OS',
|
||||
invalidOs: unsupportedOs,
|
||||
expectedError: `unsupported os: ${OperatingSystem[unsupportedOs]}`,
|
||||
};
|
||||
})(),
|
||||
];
|
||||
testScenarios.forEach(({ description, invalidOs, expectedError }) => {
|
||||
it(description, async () => {
|
||||
// arrange
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withOs(invalidOs);
|
||||
// act
|
||||
const act = async () => { await context.runCode(); };
|
||||
// assert
|
||||
await expectThrowsAsync(act, expectedError);
|
||||
});
|
||||
describe('file execution', () => {
|
||||
it('executes correct file', async () => {
|
||||
// arrange
|
||||
const fileSystem = new FileSystemOpsStub();
|
||||
const fileExecutor = new ScriptFileExecutorStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops.withFileSystem(fileSystem))
|
||||
.withFileExecutor(fileExecutor);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const writeFileCalls = fileSystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(writeFileCalls.length).to.equal(1);
|
||||
const [expectedFilePath] = writeFileCalls[0].args;
|
||||
const execFileCalls = fileExecutor.callHistory.filter((call) => call.methodName === 'executeScriptFile');
|
||||
expect(execFileCalls.length).to.equal(1);
|
||||
const [actualPath] = execFileCalls[0].args;
|
||||
expect(actualPath).to.equal(expectedFilePath);
|
||||
});
|
||||
it('executes after creating the file', async () => {
|
||||
// arrange
|
||||
let isFileCreated = false;
|
||||
let isExecutedAfterCreation = false;
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
filesystem.writeToFile = () => {
|
||||
isFileCreated = true;
|
||||
return Promise.resolve();
|
||||
};
|
||||
const fileExecutor = new ScriptFileExecutorStub();
|
||||
fileExecutor.executeScriptFile = () => {
|
||||
isExecutedAfterCreation = isFileCreated;
|
||||
return Promise.resolve();
|
||||
};
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops.withFileSystem(filesystem))
|
||||
.withFileExecutor(fileExecutor);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
expect(isExecutedAfterCreation).to.equal(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -293,21 +203,22 @@ class CodeRunnerTestSetup {
|
||||
|
||||
private folderName = `[${CodeRunnerTestSetup.name}]folderName`;
|
||||
|
||||
private fileNameGenerator: FileNameGenerator = () => `[${CodeRunnerTestSetup.name}]file-name-stub`;
|
||||
|
||||
private os: OperatingSystem = OperatingSystem.Windows;
|
||||
private filenameGenerator: FilenameGenerator = new FilenameGeneratorStub();
|
||||
|
||||
private systemOperations: SystemOperations = new SystemOperationsStub();
|
||||
|
||||
private fileExecutor: ScriptFileExecutor = new ScriptFileExecutorStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
public async runCode(): Promise<void> {
|
||||
const runner = new TemporaryFileCodeRunner(
|
||||
this.systemOperations,
|
||||
this.fileNameGenerator,
|
||||
this.filenameGenerator,
|
||||
this.logger,
|
||||
this.fileExecutor,
|
||||
);
|
||||
await runner.runCode(this.code, this.folderName, this.os);
|
||||
await runner.runCode(this.code, this.folderName);
|
||||
}
|
||||
|
||||
public withSystemOperations(
|
||||
@@ -324,13 +235,13 @@ class CodeRunnerTestSetup {
|
||||
return this.withSystemOperations(stub);
|
||||
}
|
||||
|
||||
public withOs(os: OperatingSystem): this {
|
||||
this.os = os;
|
||||
public withFolderName(folderName: string): this {
|
||||
this.folderName = folderName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFolderName(folderName: string): this {
|
||||
this.folderName = folderName;
|
||||
public withFileExecutor(fileExecutor: ScriptFileExecutor): this {
|
||||
this.fileExecutor = fileExecutor;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -339,8 +250,8 @@ class CodeRunnerTestSetup {
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFileNameGenerator(fileNameGenerator: FileNameGenerator): this {
|
||||
this.fileNameGenerator = fileNameGenerator;
|
||||
public withFileNameGenerator(fileNameGenerator: FilenameGenerator): this {
|
||||
this.filenameGenerator = fileNameGenerator;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,14 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||
import { itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
|
||||
import { BrowserOsDetectorStub } from '@tests/unit/shared/Stubs/BrowserOsDetectorStub';
|
||||
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
||||
import { EnvironmentVariablesStub } from '@tests/unit/shared/Stubs/EnvironmentVariablesStub';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
|
||||
describe('RuntimeEnvironment', () => {
|
||||
describe('HostRuntimeEnvironment', () => {
|
||||
describe('ctor', () => {
|
||||
describe('throws if window is absent', () => {
|
||||
itEachAbsentObjectValue((absentValue) => {
|
||||
@@ -190,7 +190,7 @@ function createEnvironment(options: Partial<EnvironmentOptions> = {}): TestableR
|
||||
return new TestableRuntimeEnvironment({ ...defaultOptions, ...options });
|
||||
}
|
||||
|
||||
class TestableRuntimeEnvironment extends RuntimeEnvironment {
|
||||
class TestableRuntimeEnvironment extends HostRuntimeEnvironment {
|
||||
/* Using a separate object instead of `ConstructorParameter<..>` */
|
||||
public constructor(options: Required<EnvironmentOptions>) {
|
||||
super(
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import {
|
||||
describe, it, beforeEach, afterEach,
|
||||
} from 'vitest';
|
||||
import { IRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/IRuntimeEnvironment';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { ClientLoggerFactory } from '@/presentation/bootstrapping/ClientLoggerFactory';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { WindowInjectedLogger } from '@/infrastructure/Log/WindowInjectedLogger';
|
||||
@@ -30,7 +30,7 @@ describe('ClientLoggerFactory', () => {
|
||||
const testCases: Array<{
|
||||
readonly description: string,
|
||||
readonly expectedType: Constructible<Logger>,
|
||||
readonly environment: IRuntimeEnvironment,
|
||||
readonly environment: RuntimeEnvironment,
|
||||
}> = [
|
||||
{
|
||||
description: 'desktop environment',
|
||||
@@ -74,7 +74,7 @@ describe('ClientLoggerFactory', () => {
|
||||
});
|
||||
|
||||
class TestableClientLoggerFactory extends ClientLoggerFactory {
|
||||
public constructor(environment: IRuntimeEnvironment) {
|
||||
public constructor(environment: RuntimeEnvironment) {
|
||||
super(environment);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
export class CommandOpsStub
|
||||
extends StubWithObservableMethodCalls<CommandOps>
|
||||
implements CommandOps {
|
||||
public execute(command: string): Promise<void> {
|
||||
public exec(command: string): Promise<void> {
|
||||
this.registerMethodCall({
|
||||
methodName: 'execute',
|
||||
methodName: 'exec',
|
||||
args: [command],
|
||||
});
|
||||
return Promise.resolve();
|
||||
|
||||
14
tests/unit/shared/Stubs/FilenameGeneratorStub.ts
Normal file
14
tests/unit/shared/Stubs/FilenameGeneratorStub.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { FilenameGenerator } from '@/infrastructure/CodeRunner/Filename/FilenameGenerator';
|
||||
|
||||
export class FilenameGeneratorStub implements FilenameGenerator {
|
||||
private filename = `[${FilenameGeneratorStub.name}]file-name-stub`;
|
||||
|
||||
public generateFilename(): string {
|
||||
return this.filename;
|
||||
}
|
||||
|
||||
public withFilename(filename: string): this {
|
||||
this.filename = filename;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { IRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/IRuntimeEnvironment';
|
||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
|
||||
export class RuntimeEnvironmentStub implements IRuntimeEnvironment {
|
||||
export class RuntimeEnvironmentStub implements RuntimeEnvironment {
|
||||
public isNonProduction = true;
|
||||
|
||||
public isDesktop = true;
|
||||
|
||||
14
tests/unit/shared/Stubs/ScriptFileExecutorStub.ts
Normal file
14
tests/unit/shared/Stubs/ScriptFileExecutorStub.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ScriptFileExecutor } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
|
||||
import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
||||
|
||||
export class ScriptFileExecutorStub
|
||||
extends StubWithObservableMethodCalls<ScriptFileExecutor>
|
||||
implements ScriptFileExecutor {
|
||||
public executeScriptFile(filePath: string): Promise<void> {
|
||||
this.registerMethodCall({
|
||||
methodName: 'executeScriptFile',
|
||||
args: [filePath],
|
||||
});
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user