Fix script deletion during execution on desktop
This commit fixes an issue seen on certain Windows environments (Windows 10 22H2 and 11 23H2 Pro Azure VMs) where scripts were being deleted during execution due to temporary directory usage. To resolve this, scripts are now stored in a persistent directory, enhancing reliability for long-running scripts and improving auditability along with troubleshooting. Key changes: - Move script execution logic to the `main` process from `preloader` to utilize Electron's `app.getPath`. - Improve runtime environment detection for non-browser environments to allow its usage in Electron main process. - Introduce a secure module to expose IPC channels from the main process to the renderer via the preloader process. Supporting refactorings include: - Simplify `CodeRunner` interface by removing the `tempScriptFolderName` parameter. - Rename `NodeSystemOperations` to `NodeElectronSystemOperations` as it now wraps electron APIs too, and convert it to class for simplicity. - Rename `TemporaryFileCodeRunner` to `ScriptFileCodeRunner` to reflect its new functinoality. - Rename `SystemOperations` folder to `System` for simplicity. - Rename `HostRuntimeEnvironment` to `BrowserRuntimeEnvironment` for clarity. - Refactor main Electron process configuration to align with latest Electron documentation/recommendations. - Refactor unit tests `BrowserRuntimeEnvironment` to simplify singleton workaround. - Use alias imports like `electron/main` and `electron/common` for better clarity.
This commit is contained in:
@@ -0,0 +1,155 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ExecutionSubdirectory, PersistentDirectoryProvider } from '@/infrastructure/CodeRunner/Creation/Directory/PersistentDirectoryProvider';
|
||||
import { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
||||
|
||||
describe('PersistentDirectoryProvider', () => {
|
||||
describe('createDirectory', () => {
|
||||
describe('path generation', () => {
|
||||
it('uses user directory as base', async () => {
|
||||
// arrange
|
||||
const expectedBaseDirectory = 'base-directory';
|
||||
const pathSegmentSeparator = '/STUB-SEGMENT-SEPARATOR/';
|
||||
const locationOps = new LocationOpsStub()
|
||||
.withDefaultSeparator(pathSegmentSeparator);
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub()
|
||||
.withOperatingSystem(new OperatingSystemOpsStub()
|
||||
.withUserDirectoryResult(expectedBaseDirectory))
|
||||
.withLocation(locationOps));
|
||||
|
||||
// act
|
||||
const actualDirectoryResult = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
const actualBaseDirectory = actualDirectoryResult.split(pathSegmentSeparator)[0];
|
||||
expect(actualBaseDirectory).to.equal(expectedBaseDirectory);
|
||||
const calls = locationOps.callHistory.filter((call) => call.methodName === 'combinePaths');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [combinedBaseDirectory] = calls[0].args;
|
||||
expect(combinedBaseDirectory).to.equal(expectedBaseDirectory);
|
||||
});
|
||||
it('appends execution subdirectory', async () => {
|
||||
// arrange
|
||||
const expectedSubdirectory = ExecutionSubdirectory;
|
||||
const pathSegmentSeparator = '/STUB-SEGMENT-SEPARATOR/';
|
||||
const locationOps = new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator);
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub()
|
||||
.withLocation(locationOps));
|
||||
|
||||
// act
|
||||
const actualDirectoryResult = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
const actualSubdirectory = actualDirectoryResult
|
||||
.split(pathSegmentSeparator)
|
||||
.pop();
|
||||
expect(actualSubdirectory).to.equal(expectedSubdirectory);
|
||||
const calls = locationOps.callHistory.filter((call) => call.methodName === 'combinePaths');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [,combinedSubdirectory] = calls[0].args;
|
||||
expect(combinedSubdirectory).to.equal(expectedSubdirectory);
|
||||
});
|
||||
it('correctly forms the full path', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/';
|
||||
const baseDirectory = 'base-directory';
|
||||
const expectedDirectory = [baseDirectory, ExecutionSubdirectory].join(pathSegmentSeparator);
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub()
|
||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator))
|
||||
.withOperatingSystem(
|
||||
new OperatingSystemOpsStub().withUserDirectoryResult(baseDirectory),
|
||||
));
|
||||
|
||||
// act
|
||||
const actualDirectory = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
expect(actualDirectory).to.equal(expectedDirectory);
|
||||
});
|
||||
});
|
||||
describe('directory creation', () => {
|
||||
it('creates directory recursively', async () => {
|
||||
// arrange
|
||||
const expectedIsRecursive = true;
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub().withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
const expectedDir = await context.createDirectory();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'createDirectory');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualPath, actualIsRecursive] = calls[0].args;
|
||||
expect(actualPath).to.equal(expectedDir);
|
||||
expect(actualIsRecursive).to.equal(expectedIsRecursive);
|
||||
});
|
||||
it('logs error when creation fails', async () => {
|
||||
// arrange
|
||||
const logger = new LoggerStub();
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
filesystem.createDirectory = () => { throw new Error(); };
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withLogger(logger)
|
||||
.withSystem(new SystemOperationsStub().withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
try {
|
||||
await context.createDirectory();
|
||||
} catch {
|
||||
// swallow
|
||||
}
|
||||
|
||||
// assert
|
||||
const errorCall = logger.callHistory.find((c) => c.methodName === 'error');
|
||||
expectExists(errorCall);
|
||||
});
|
||||
it('throws error on creation failure', async () => {
|
||||
// arrange
|
||||
const expectedError = 'expected file system error';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
filesystem.createDirectory = () => { throw new Error(expectedError); };
|
||||
const context = new PersistentDirectoryProviderTestSetup()
|
||||
.withSystem(new SystemOperationsStub().withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
const act = () => context.createDirectory();
|
||||
|
||||
// assert
|
||||
await expectThrowsAsync(act, expectedError);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class PersistentDirectoryProviderTestSetup {
|
||||
private system: SystemOperations = new SystemOperationsStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
public withSystem(system: SystemOperations): this {
|
||||
this.system = system;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withLogger(logger: Logger): this {
|
||||
this.logger = logger;
|
||||
return this;
|
||||
}
|
||||
|
||||
public createDirectory(): ReturnType<PersistentDirectoryProvider['provideScriptDirectory']> {
|
||||
const provider = new PersistentDirectoryProvider(this.system, this.logger);
|
||||
return provider.provideScriptDirectory();
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||
import { OsTimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Filename/OsTimestampedFilenameGenerator';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
|
||||
import { OsTimestampedFilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/OsTimestampedFilenameGenerator';
|
||||
|
||||
describe('OsTimestampedFilenameGenerator', () => {
|
||||
describe('generateFilename', () => {
|
||||
@@ -0,0 +1,165 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ScriptFileCreationOrchestrator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreationOrchestrator';
|
||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { ScriptDirectoryProvider } from '@/infrastructure/CodeRunner/Creation/Directory/ScriptDirectoryProvider';
|
||||
import { ScriptDirectoryProviderStub } from '@tests/unit/shared/Stubs/ScriptDirectoryProviderStub';
|
||||
import { FilenameGenerator } from '@/infrastructure/CodeRunner/Creation/Filename/FilenameGenerator';
|
||||
import { FilenameGeneratorStub } from '@tests/unit/shared/Stubs/FilenameGeneratorStub';
|
||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||
import { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
|
||||
|
||||
describe('ScriptFileCreationOrchestrator', () => {
|
||||
describe('createScriptFile', () => {
|
||||
describe('path generation', () => {
|
||||
it('generates correct directory path', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const expectedScriptDirectory = '/expected-script-directory';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withLocation(
|
||||
new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator),
|
||||
)
|
||||
.withFileSystem(filesystem))
|
||||
.withDirectoryProvider(
|
||||
new ScriptDirectoryProviderStub().withDirectoryPath(expectedScriptDirectory),
|
||||
);
|
||||
|
||||
// act
|
||||
const actualFilePath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const actualDirectory = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.slice(0, -1)
|
||||
.join(pathSegmentSeparator);
|
||||
expect(actualDirectory).to.equal(expectedScriptDirectory, formatAssertionMessage([
|
||||
`Actual file path: ${actualFilePath}`,
|
||||
]));
|
||||
});
|
||||
it('generates correct file name', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const expectedFilename = 'expected-script-file-name';
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withFilenameGenerator(new FilenameGeneratorStub().withFilename(expectedFilename))
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withFileSystem(filesystem)
|
||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator)));
|
||||
|
||||
// act
|
||||
const actualFilePath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const actualFileName = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.pop();
|
||||
expect(actualFileName).to.equal(expectedFilename);
|
||||
});
|
||||
it('generates complete file path', async () => {
|
||||
// arrange
|
||||
const expectedPath = 'expected-script-path';
|
||||
const fileName = 'file-name';
|
||||
const directoryPath = 'directory-path';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withFilenameGenerator(new FilenameGeneratorStub().withFilename(fileName))
|
||||
.withDirectoryProvider(new ScriptDirectoryProviderStub().withDirectoryPath(directoryPath))
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withFileSystem(filesystem)
|
||||
.withLocation(
|
||||
new LocationOpsStub().withJoinResult(expectedPath, directoryPath, fileName),
|
||||
));
|
||||
|
||||
// act
|
||||
const actualFilePath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
expect(actualFilePath).to.equal(expectedPath);
|
||||
});
|
||||
});
|
||||
describe('writing file to system', () => {
|
||||
it('writes file to the generated path', async () => {
|
||||
// arrange
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub()
|
||||
.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
const expectedPath = await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
expect(actualFilePath).to.equal(expectedPath);
|
||||
});
|
||||
it('writes provided script content to file', async () => {
|
||||
// arrange
|
||||
const expectedCode = 'expected-code';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new ScriptFileCreationOrchestratorTestSetup()
|
||||
.withSystemOperations(new SystemOperationsStub().withFileSystem(filesystem))
|
||||
.withFileContents(expectedCode);
|
||||
|
||||
// act
|
||||
await context.createScriptFile();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [, actualData] = calls[0].args;
|
||||
expect(actualData).to.equal(expectedCode);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class ScriptFileCreationOrchestratorTestSetup {
|
||||
private system: SystemOperations = new SystemOperationsStub();
|
||||
|
||||
private filenameGenerator: FilenameGenerator = new FilenameGeneratorStub();
|
||||
|
||||
private directoryProvider: ScriptDirectoryProvider = new ScriptDirectoryProviderStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
private fileContents = `[${ScriptFileCreationOrchestratorTestSetup.name}] script file contents`;
|
||||
|
||||
public withFileContents(fileContents: string): this {
|
||||
this.fileContents = fileContents;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withDirectoryProvider(directoryProvider: ScriptDirectoryProvider): this {
|
||||
this.directoryProvider = directoryProvider;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFilenameGenerator(generator: FilenameGenerator): this {
|
||||
this.filenameGenerator = generator;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withSystemOperations(system: SystemOperations): this {
|
||||
this.system = system;
|
||||
return this;
|
||||
}
|
||||
|
||||
public createScriptFile(): ReturnType<ScriptFileCreationOrchestrator['createScriptFile']> {
|
||||
const creator = new ScriptFileCreationOrchestrator(
|
||||
this.system,
|
||||
this.filenameGenerator,
|
||||
this.directoryProvider,
|
||||
this.logger,
|
||||
);
|
||||
return creator.createScriptFile(this.fileContents);
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironm
|
||||
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 { SystemOperations } from '@/infrastructure/CodeRunner/System/SystemOperations';
|
||||
import { FileSystemOpsStub } from '@tests/unit/shared/Stubs/FileSystemOpsStub';
|
||||
|
||||
describe('VisibleTerminalScriptFileExecutor', () => {
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ScriptFileCodeRunner } from '@/infrastructure/CodeRunner/ScriptFileCodeRunner';
|
||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||
import { Logger } from '@/application/Common/Log/Logger';
|
||||
import { ScriptFileExecutor } from '@/infrastructure/CodeRunner/Execution/ScriptFileExecutor';
|
||||
import { ScriptFileExecutorStub } from '@tests/unit/shared/Stubs/ScriptFileExecutorStub';
|
||||
import { ScriptFileCreator } from '@/infrastructure/CodeRunner/Creation/ScriptFileCreator';
|
||||
import { ScriptFileCreatorStub } from '@tests/unit/shared/Stubs/ScriptFileCreatorStub';
|
||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||
import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
||||
|
||||
describe('ScriptFileCodeRunner', () => {
|
||||
describe('runCode', () => {
|
||||
it('executes the script file as expected', async () => {
|
||||
// arrange
|
||||
const expectedFilePath = 'expected script path';
|
||||
const fileExecutor = new ScriptFileExecutorStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileCreator(new ScriptFileCreatorStub().withCreatedFilePath(expectedFilePath))
|
||||
.withFileExecutor(fileExecutor);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const executeCalls = fileExecutor.callHistory.filter((call) => call.methodName === 'executeScriptFile');
|
||||
expect(executeCalls.length).to.equal(1);
|
||||
const [actualPath] = executeCalls[0].args;
|
||||
expect(actualPath).to.equal(expectedFilePath);
|
||||
});
|
||||
it('creates script file with provided code', async () => {
|
||||
// arrange
|
||||
const expectedCode = 'expected code';
|
||||
const fileCreator = new ScriptFileCreatorStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileCreator(fileCreator)
|
||||
.withCode(expectedCode);
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const createCalls = fileCreator.callHistory.filter((call) => call.methodName === 'createScriptFile');
|
||||
expect(createCalls.length).to.equal(1);
|
||||
const [actualCode] = createCalls[0].args;
|
||||
expect(actualCode).to.equal(expectedCode);
|
||||
});
|
||||
describe('error handling', () => {
|
||||
const testScenarios: ReadonlyArray<{
|
||||
readonly description: string;
|
||||
readonly injectedException: Error;
|
||||
readonly faultyContext: CodeRunnerTestSetup;
|
||||
}> = [
|
||||
(() => {
|
||||
const error = new Error('script file execution failed');
|
||||
const executor = new ScriptFileExecutorStub();
|
||||
executor.executeScriptFile = () => {
|
||||
throw error;
|
||||
};
|
||||
return {
|
||||
description: 'fails to execute script file',
|
||||
injectedException: error,
|
||||
faultyContext: new CodeRunnerTestSetup().withFileExecutor(executor),
|
||||
};
|
||||
})(),
|
||||
(() => {
|
||||
const error = new Error('script file creation failed');
|
||||
const creator = new ScriptFileCreatorStub();
|
||||
creator.createScriptFile = () => {
|
||||
throw error;
|
||||
};
|
||||
return {
|
||||
description: 'fails to create script file',
|
||||
injectedException: error,
|
||||
faultyContext: new CodeRunnerTestSetup().withFileCreator(creator),
|
||||
};
|
||||
})(),
|
||||
];
|
||||
describe('logs errors correctly', () => {
|
||||
testScenarios.forEach(({ description, faultyContext }) => {
|
||||
it(`logs error when ${description}`, async () => {
|
||||
// arrange
|
||||
const logger = new LoggerStub();
|
||||
faultyContext.withLogger(logger);
|
||||
// act
|
||||
try {
|
||||
await faultyContext.runCode();
|
||||
} catch {
|
||||
// Swallow
|
||||
}
|
||||
// assert
|
||||
const errorCall = logger.callHistory.find((c) => c.methodName === 'error');
|
||||
expectExists(errorCall);
|
||||
});
|
||||
});
|
||||
});
|
||||
describe('correctly rethrows errors', () => {
|
||||
testScenarios.forEach(({ description, injectedException, faultyContext }) => {
|
||||
it(`rethrows error when ${description}`, async () => {
|
||||
// act
|
||||
const act = () => faultyContext.runCode();
|
||||
// assert
|
||||
await expectThrowsAsync(act, injectedException.message);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class CodeRunnerTestSetup {
|
||||
private code = `[${CodeRunnerTestSetup.name}]code`;
|
||||
|
||||
private fileCreator: ScriptFileCreator = new ScriptFileCreatorStub();
|
||||
|
||||
private fileExecutor: ScriptFileExecutor = new ScriptFileExecutorStub();
|
||||
|
||||
private logger: Logger = new LoggerStub();
|
||||
|
||||
public async runCode(): Promise<void> {
|
||||
const runner = new ScriptFileCodeRunner(
|
||||
this.fileExecutor,
|
||||
this.fileCreator,
|
||||
this.logger,
|
||||
);
|
||||
await runner.runCode(this.code);
|
||||
}
|
||||
|
||||
public withFileExecutor(fileExecutor: ScriptFileExecutor): this {
|
||||
this.fileExecutor = fileExecutor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withCode(code: string): this {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withLogger(logger: Logger): this {
|
||||
this.logger = logger;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFileCreator(fileCreator: ScriptFileCreator): this {
|
||||
this.fileCreator = fileCreator;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
@@ -1,257 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { FileSystemOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||
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 { FunctionKeys } from '@/TypeHelpers';
|
||||
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', () => {
|
||||
describe('directory creation', () => {
|
||||
it('creates temporary directory recursively', async () => {
|
||||
// arrange
|
||||
const expectedDir = 'expected-dir';
|
||||
const expectedIsRecursive = true;
|
||||
|
||||
const folderName = 'privacy.sexy';
|
||||
const temporaryDirName = 'tmp';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withOperatingSystem(
|
||||
new OperatingSystemOpsStub()
|
||||
.withTemporaryDirectoryResult(temporaryDirName),
|
||||
)
|
||||
.withLocation(
|
||||
new LocationOpsStub()
|
||||
.withJoinResult(expectedDir, temporaryDirName, folderName),
|
||||
)
|
||||
.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
await context
|
||||
.withFolderName(folderName)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'createDirectory');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualPath, actualIsRecursive] = calls[0].args;
|
||||
expect(actualPath).to.equal(expectedDir);
|
||||
expect(actualIsRecursive).to.equal(expectedIsRecursive);
|
||||
});
|
||||
});
|
||||
describe('file creation', () => {
|
||||
it('creates a file with expected code', async () => {
|
||||
// arrange
|
||||
const expectedCode = 'expected-code';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withFileSystem(filesystem));
|
||||
// act
|
||||
await context
|
||||
.withCode(expectedCode)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [, actualData] = calls[0].args;
|
||||
expect(actualData).to.equal(expectedCode);
|
||||
});
|
||||
it('creates file in expected directory', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const temporaryDirName = '/tmp';
|
||||
const folderName = 'privacy.sexy';
|
||||
const expectedDirectory = [temporaryDirName, folderName].join(pathSegmentSeparator);
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withOperatingSystem(
|
||||
new OperatingSystemOpsStub()
|
||||
.withTemporaryDirectoryResult(temporaryDirName),
|
||||
)
|
||||
.withLocation(
|
||||
new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator),
|
||||
)
|
||||
.withFileSystem(filesystem));
|
||||
|
||||
// act
|
||||
await context
|
||||
.withFolderName(folderName)
|
||||
.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
const actualDirectory = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.slice(0, -1)
|
||||
.join(pathSegmentSeparator);
|
||||
expect(actualDirectory).to.equal(expectedDirectory, formatAssertionMessage([
|
||||
`Actual file path: ${actualFilePath}`,
|
||||
]));
|
||||
});
|
||||
it('creates file with expected file name', async () => {
|
||||
// arrange
|
||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||
const filesystem = new FileSystemOpsStub();
|
||||
const expectedFilename = 'expected-script-file-name';
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withFileNameGenerator(new FilenameGeneratorStub().withFilename(expectedFilename))
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withFileSystem(filesystem)
|
||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator)));
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const calls = filesystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||
expect(calls.length).to.equal(1);
|
||||
const [actualFilePath] = calls[0].args;
|
||||
const actualFileName = actualFilePath
|
||||
.split(pathSegmentSeparator)
|
||||
.pop();
|
||||
expect(actualFileName).to.equal(actualFileName, formatAssertionMessage([
|
||||
`Actual file path: ${actualFilePath}`,
|
||||
]));
|
||||
});
|
||||
it('creates file after creating the directory', async () => {
|
||||
const expectedOrder: readonly FunctionKeys<FileSystemOps>[] = [
|
||||
'createDirectory',
|
||||
'writeToFile',
|
||||
];
|
||||
const fileSystem = new FileSystemOpsStub();
|
||||
const context = new CodeRunnerTestSetup()
|
||||
.withSystemOperationsStub((ops) => ops
|
||||
.withFileSystem(fileSystem));
|
||||
|
||||
// act
|
||||
await context.runCode();
|
||||
|
||||
// assert
|
||||
const actualOrder = fileSystem.callHistory
|
||||
.map((c) => c.methodName)
|
||||
.filter((command) => expectedOrder.includes(command));
|
||||
expect(expectedOrder).to.deep.equal(actualOrder);
|
||||
});
|
||||
});
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
class CodeRunnerTestSetup {
|
||||
private code = `[${CodeRunnerTestSetup.name}]code`;
|
||||
|
||||
private folderName = `[${CodeRunnerTestSetup.name}]folderName`;
|
||||
|
||||
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.logger,
|
||||
this.fileExecutor,
|
||||
);
|
||||
await runner.runCode(this.code, this.folderName);
|
||||
}
|
||||
|
||||
public withSystemOperations(
|
||||
systemOperations: SystemOperations,
|
||||
): this {
|
||||
this.systemOperations = systemOperations;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withSystemOperationsStub(
|
||||
setup: (stub: SystemOperationsStub) => SystemOperationsStub,
|
||||
): this {
|
||||
const stub = setup(new SystemOperationsStub());
|
||||
return this.withSystemOperations(stub);
|
||||
}
|
||||
|
||||
public withFolderName(folderName: string): this {
|
||||
this.folderName = folderName;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFileExecutor(fileExecutor: ScriptFileExecutor): this {
|
||||
this.fileExecutor = fileExecutor;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withCode(code: string): this {
|
||||
this.code = code;
|
||||
return this;
|
||||
}
|
||||
|
||||
public withFileNameGenerator(fileNameGenerator: FilenameGenerator): this {
|
||||
this.filenameGenerator = fileNameGenerator;
|
||||
return this;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user