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:
@@ -1,9 +1,6 @@
|
|||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
|
||||||
|
|
||||||
export interface CodeRunner {
|
export interface CodeRunner {
|
||||||
runCode(
|
runCode(
|
||||||
code: string,
|
code: string,
|
||||||
tempScriptFolderName: string,
|
tempScriptFolderName: string,
|
||||||
os: OperatingSystem,
|
|
||||||
): Promise<void>;
|
): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import { IApplicationContext } from '@/application/Context/IApplicationContext';
|
import { IApplicationContext } from '@/application/Context/IApplicationContext';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
import { IApplication } from '@/domain/IApplication';
|
import { IApplication } from '@/domain/IApplication';
|
||||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||||
import { IApplicationFactory } from '../IApplicationFactory';
|
import { IApplicationFactory } from '../IApplicationFactory';
|
||||||
import { ApplicationFactory } from '../ApplicationFactory';
|
import { ApplicationFactory } from '../ApplicationFactory';
|
||||||
import { ApplicationContext } from './ApplicationContext';
|
import { ApplicationContext } from './ApplicationContext';
|
||||||
|
|
||||||
export async function buildContext(
|
export async function buildContext(
|
||||||
factory: IApplicationFactory = ApplicationFactory.Current,
|
factory: IApplicationFactory = ApplicationFactory.Current,
|
||||||
environment = RuntimeEnvironment.CurrentEnvironment,
|
environment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||||
): Promise<IApplicationContext> {
|
): Promise<IApplicationContext> {
|
||||||
const app = await factory.getApp();
|
const app = await factory.getApp();
|
||||||
const os = getInitialOs(app, environment.os);
|
const os = getInitialOs(app, environment.os);
|
||||||
|
|||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export interface ScriptFileExecutor {
|
||||||
|
executeScriptFile(filePath: string): Promise<void>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
|
import { CommandOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||||
|
import { Logger } from '@/application/Common/Log/Logger';
|
||||||
|
import { ElectronLogger } from '@/infrastructure/Log/ElectronLogger';
|
||||||
|
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||||
|
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||||
|
import { createNodeSystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/NodeSystemOperations';
|
||||||
|
import { ScriptFileExecutor } from './ScriptFileExecutor';
|
||||||
|
|
||||||
|
export class VisibleTerminalScriptExecutor implements ScriptFileExecutor {
|
||||||
|
constructor(
|
||||||
|
private readonly system: SystemOperations = createNodeSystemOperations(),
|
||||||
|
private readonly logger: Logger = ElectronLogger,
|
||||||
|
private readonly environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||||
|
) { }
|
||||||
|
|
||||||
|
public async executeScriptFile(filePath: string): Promise<void> {
|
||||||
|
const { os } = this.environment;
|
||||||
|
if (os === undefined) {
|
||||||
|
throw new Error('Unknown operating system');
|
||||||
|
}
|
||||||
|
await this.setFileExecutablePermissions(filePath);
|
||||||
|
await this.runFileWithRunner(filePath, os);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async setFileExecutablePermissions(filePath: string): Promise<void> {
|
||||||
|
this.logger.info(`Setting execution permissions for file at ${filePath}`);
|
||||||
|
await this.system.fileSystem.setFilePermissions(filePath, '755');
|
||||||
|
this.logger.info(`Execution permissions set successfully for ${filePath}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async runFileWithRunner(filePath: string, os: OperatingSystem): Promise<void> {
|
||||||
|
this.logger.info(`Executing script file: ${filePath} on ${OperatingSystem[os]}.`);
|
||||||
|
const runner = TerminalRunners[os];
|
||||||
|
if (!runner) {
|
||||||
|
throw new Error(`Unsupported operating system: ${OperatingSystem[os]}`);
|
||||||
|
}
|
||||||
|
const context: TerminalExecutionContext = {
|
||||||
|
scriptFilePath: filePath,
|
||||||
|
commandOps: this.system.command,
|
||||||
|
logger: this.logger,
|
||||||
|
};
|
||||||
|
await runner(context);
|
||||||
|
this.logger.info('Command script file successfully.');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface TerminalExecutionContext {
|
||||||
|
readonly scriptFilePath: string;
|
||||||
|
readonly commandOps: CommandOps;
|
||||||
|
readonly logger: Logger;
|
||||||
|
}
|
||||||
|
|
||||||
|
type TerminalRunner = (context: TerminalExecutionContext) => Promise<void>;
|
||||||
|
|
||||||
|
const TerminalRunners: Partial<Record<OperatingSystem, TerminalRunner>> = {
|
||||||
|
[OperatingSystem.Windows]: async (context) => {
|
||||||
|
/*
|
||||||
|
Options:
|
||||||
|
"path":
|
||||||
|
✅ Launches the script within `cmd.exe`.
|
||||||
|
✅ Uses user-friendly GUI sudo prompt.
|
||||||
|
*/
|
||||||
|
const command = cmdShellPathArgumentEscape(context.scriptFilePath);
|
||||||
|
await runCommand(command, context);
|
||||||
|
},
|
||||||
|
[OperatingSystem.Linux]: async (context) => {
|
||||||
|
const command = `x-terminal-emulator -e ${posixShellPathArgumentEscape(context.scriptFilePath)}`;
|
||||||
|
/*
|
||||||
|
Options:
|
||||||
|
`x-terminal-emulator -e`:
|
||||||
|
✅ Launches the script within the default terminal emulator.
|
||||||
|
❌ Requires terminal-based (not GUI) sudo prompt, which may not be very user friendly.
|
||||||
|
*/
|
||||||
|
await runCommand(command, context);
|
||||||
|
},
|
||||||
|
[OperatingSystem.macOS]: async (context) => {
|
||||||
|
const command = `open -a Terminal.app ${posixShellPathArgumentEscape(context.scriptFilePath)}`;
|
||||||
|
/*
|
||||||
|
Options:
|
||||||
|
`open -a Terminal.app`:
|
||||||
|
✅ Launches the script within Terminal app, that exists natively in all modern macOS
|
||||||
|
versions.
|
||||||
|
❌ Requires terminal-based (not GUI) sudo prompt, which may not be very user friendly.
|
||||||
|
❌ Terminal app requires many privileges to execute the script, this would prompt user
|
||||||
|
to grant privileges to the Terminal app.
|
||||||
|
|
||||||
|
`osascript -e "do shell script \\"${scriptPath}\\" with administrator privileges"`:
|
||||||
|
✅ Uses user-friendly GUI sudo prompt.
|
||||||
|
❌ Executes the script in the background, which does not provide the user with immediate
|
||||||
|
visual feedback or allow interaction with the script as it runs.
|
||||||
|
*/
|
||||||
|
await runCommand(command, context);
|
||||||
|
},
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
async function runCommand(command: string, context: TerminalExecutionContext): Promise<void> {
|
||||||
|
context.logger.info(`Executing command:\n${command}`);
|
||||||
|
await context.commandOps.exec(command);
|
||||||
|
context.logger.info('Executed command successfully.');
|
||||||
|
}
|
||||||
|
|
||||||
|
function posixShellPathArgumentEscape(pathArgument: string): string {
|
||||||
|
// - Wraps the path in single quotes, which is a standard practice in POSIX shells
|
||||||
|
// (like bash and zsh) found on macOS/Linux to ensure that characters like spaces, '*', and
|
||||||
|
// '?' are treated as literals, not as special characters.
|
||||||
|
// - Escapes any single quotes within the path itself. This allows paths containing single
|
||||||
|
// quotes to be correctly interpreted in POSIX-compliant systems, such as Linux and macOS.
|
||||||
|
return `'${pathArgument.replaceAll('\'', '\'\\\'\'')}'`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cmdShellPathArgumentEscape(pathArgument: string): string {
|
||||||
|
// - Encloses the path in double quotes, which is necessary for Windows command line (cmd.exe)
|
||||||
|
// to correctly handle paths containing spaces.
|
||||||
|
// - Paths in Windows cannot include double quotes `"` themselves, so these are not escaped.
|
||||||
|
return `"${pathArgument}"`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export interface FilenameGenerator {
|
||||||
|
generateFilename(): string;
|
||||||
|
}
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
|
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||||
|
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||||
|
import { FilenameGenerator } from './FilenameGenerator';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates a timestamped filename specific to the given operating system.
|
* Generates a timestamped filename specific to the given operating system.
|
||||||
@@ -7,13 +10,22 @@ import { OperatingSystem } from '@/domain/OperatingSystem';
|
|||||||
* - A timestamp for uniqueness and easier auditability.
|
* - A timestamp for uniqueness and easier auditability.
|
||||||
* - File extension based on the operating system.
|
* - File extension based on the operating system.
|
||||||
*/
|
*/
|
||||||
export function generateOsTimestampedFileName(
|
export class OsTimestampedFilenameGenerator implements FilenameGenerator {
|
||||||
currentOs: OperatingSystem,
|
private readonly currentOs?: OperatingSystem;
|
||||||
date = new Date(),
|
|
||||||
): string {
|
constructor(
|
||||||
const baseFileName = `run-${createTimeStampForFile(date)}`;
|
environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||||
const extension = FileExtensions[currentOs];
|
) {
|
||||||
return extension ? `${baseFileName}.${extension}` : baseFileName;
|
this.currentOs = environment.os;
|
||||||
|
}
|
||||||
|
|
||||||
|
public generateFilename(
|
||||||
|
date = new Date(),
|
||||||
|
): string {
|
||||||
|
const baseFileName = `run-${createTimeStampForFile(date)}`;
|
||||||
|
const extension = this.currentOs === undefined ? undefined : FileExtensions[this.currentOs];
|
||||||
|
return extension ? `${baseFileName}.${extension}` : baseFileName;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const FileExtensions: Partial<Record<OperatingSystem, string>> = {
|
const FileExtensions: Partial<Record<OperatingSystem, string>> = {
|
||||||
@@ -33,7 +33,7 @@ export function createNodeSystemOperations(): SystemOperations {
|
|||||||
) => writeFile(filePath, data),
|
) => writeFile(filePath, data),
|
||||||
},
|
},
|
||||||
command: {
|
command: {
|
||||||
execute: (command) => new Promise((resolve, reject) => {
|
exec: (command) => new Promise((resolve, reject) => {
|
||||||
exec(command, (error) => {
|
exec(command, (error) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
reject(error);
|
reject(error);
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ export interface LocationOps {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface CommandOps {
|
export interface CommandOps {
|
||||||
execute(command: string): Promise<void>;
|
exec(command: string): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FileSystemOps {
|
export interface FileSystemOps {
|
||||||
|
|||||||
@@ -1,30 +1,30 @@
|
|||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
|
||||||
import { CodeRunner } from '@/application/CodeRunner';
|
import { CodeRunner } from '@/application/CodeRunner';
|
||||||
import { Logger } from '@/application/Common/Log/Logger';
|
import { Logger } from '@/application/Common/Log/Logger';
|
||||||
import { ElectronLogger } from '../Log/ElectronLogger';
|
import { ElectronLogger } from '../Log/ElectronLogger';
|
||||||
import { SystemOperations } from './SystemOperations/SystemOperations';
|
import { SystemOperations } from './SystemOperations/SystemOperations';
|
||||||
import { createNodeSystemOperations } from './SystemOperations/NodeSystemOperations';
|
import { createNodeSystemOperations } from './SystemOperations/NodeSystemOperations';
|
||||||
import { generateOsTimestampedFileName } from './FileNameGenerator';
|
import { FilenameGenerator } from './Filename/FilenameGenerator';
|
||||||
|
import { ScriptFileExecutor } from './Execution/ScriptFileExecutor';
|
||||||
export type FileNameGenerator = (os: OperatingSystem) => string;
|
import { VisibleTerminalScriptExecutor } from './Execution/VisibleTerminalScriptFileExecutor';
|
||||||
|
import { OsTimestampedFilenameGenerator } from './Filename/OsTimestampedFilenameGenerator';
|
||||||
|
|
||||||
export class TemporaryFileCodeRunner implements CodeRunner {
|
export class TemporaryFileCodeRunner implements CodeRunner {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly system: SystemOperations = createNodeSystemOperations(),
|
private readonly system: SystemOperations = createNodeSystemOperations(),
|
||||||
private readonly fileNameGenerator: FileNameGenerator = generateOsTimestampedFileName,
|
private readonly filenameGenerator: FilenameGenerator = new OsTimestampedFilenameGenerator(),
|
||||||
private readonly logger: Logger = ElectronLogger,
|
private readonly logger: Logger = ElectronLogger,
|
||||||
|
private readonly scriptFileExecutor: ScriptFileExecutor = new VisibleTerminalScriptExecutor(),
|
||||||
) { }
|
) { }
|
||||||
|
|
||||||
public async runCode(
|
public async runCode(
|
||||||
code: string,
|
code: string,
|
||||||
tempScriptFolderName: string,
|
tempScriptFolderName: string,
|
||||||
os: OperatingSystem,
|
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
this.logger.info(`Starting running code for OS: ${OperatingSystem[os]}`);
|
this.logger.info('Starting running code.');
|
||||||
try {
|
try {
|
||||||
const fileName = this.fileNameGenerator(os);
|
const filename = this.filenameGenerator.generateFilename();
|
||||||
const filePath = await this.createTemporaryFile(fileName, tempScriptFolderName, code);
|
const filePath = await this.createTemporaryFile(filename, tempScriptFolderName, code);
|
||||||
await this.executeFile(filePath, os);
|
await this.scriptFileExecutor.executeScriptFile(filePath);
|
||||||
this.logger.info(`Successfully executed script at ${filePath}`);
|
this.logger.info(`Successfully executed script at ${filePath}`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.logger.error(`Error executing script: ${error.message}`, error);
|
this.logger.error(`Error executing script: ${error.message}`, error);
|
||||||
@@ -33,7 +33,7 @@ export class TemporaryFileCodeRunner implements CodeRunner {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private async createTemporaryFile(
|
private async createTemporaryFile(
|
||||||
fileName: string,
|
filename: string,
|
||||||
tempScriptFolderName: string,
|
tempScriptFolderName: string,
|
||||||
contents: string,
|
contents: string,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
@@ -42,7 +42,7 @@ export class TemporaryFileCodeRunner implements CodeRunner {
|
|||||||
tempScriptFolderName,
|
tempScriptFolderName,
|
||||||
);
|
);
|
||||||
await this.createDirectoryIfNotExists(directoryPath);
|
await this.createDirectoryIfNotExists(directoryPath);
|
||||||
const filePath = this.system.location.combinePaths(directoryPath, fileName);
|
const filePath = this.system.location.combinePaths(directoryPath, filename);
|
||||||
await this.createFile(filePath, contents);
|
await this.createFile(filePath, contents);
|
||||||
return filePath;
|
return filePath;
|
||||||
}
|
}
|
||||||
@@ -58,41 +58,4 @@ export class TemporaryFileCodeRunner implements CodeRunner {
|
|||||||
await this.system.fileSystem.createDirectory(directoryPath, true);
|
await this.system.fileSystem.createDirectory(directoryPath, true);
|
||||||
this.logger.info(`Directory confirmed at: ${directoryPath}`);
|
this.logger.info(`Directory confirmed at: ${directoryPath}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async executeFile(filePath: string, os: OperatingSystem): Promise<void> {
|
|
||||||
await this.setFileExecutablePermissions(filePath);
|
|
||||||
const command = getExecuteCommand(filePath, os);
|
|
||||||
await this.executeCommand(command);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async setFileExecutablePermissions(filePath: string): Promise<void> {
|
|
||||||
this.logger.info(`Setting execution permissions for file at ${filePath}`);
|
|
||||||
await this.system.fileSystem.setFilePermissions(filePath, '755');
|
|
||||||
this.logger.info(`Execution permissions set successfully for ${filePath}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
private async executeCommand(command: string): Promise<void> {
|
|
||||||
this.logger.info(`Executing command: ${command}`);
|
|
||||||
await this.system.command.execute(command);
|
|
||||||
this.logger.info('Command executed successfully.');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getExecuteCommand(
|
|
||||||
scriptPath: string,
|
|
||||||
os: OperatingSystem,
|
|
||||||
): string {
|
|
||||||
switch (os) {
|
|
||||||
case OperatingSystem.Linux:
|
|
||||||
return `x-terminal-emulator -e '${scriptPath}'`;
|
|
||||||
case OperatingSystem.macOS:
|
|
||||||
return `open -a Terminal.app ${scriptPath}`;
|
|
||||||
// Another option with graphical sudo would be
|
|
||||||
// `osascript -e "do shell script \\"${scriptPath}\\" with administrator privileges"`
|
|
||||||
// However it runs in background
|
|
||||||
case OperatingSystem.Windows:
|
|
||||||
return scriptPath;
|
|
||||||
default:
|
|
||||||
throw Error(`unsupported os: ${OperatingSystem[os]}`);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
|
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
|
||||||
|
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
||||||
|
import { EnvironmentVariablesFactory } from '@/infrastructure/EnvironmentVariables/EnvironmentVariablesFactory';
|
||||||
|
import { ConditionBasedOsDetector } from './BrowserOs/ConditionBasedOsDetector';
|
||||||
|
import { BrowserEnvironment, BrowserOsDetector } from './BrowserOs/BrowserOsDetector';
|
||||||
|
import { RuntimeEnvironment } from './RuntimeEnvironment';
|
||||||
|
import { isTouchEnabledDevice } from './TouchSupportDetection';
|
||||||
|
|
||||||
|
export class HostRuntimeEnvironment implements RuntimeEnvironment {
|
||||||
|
public static readonly CurrentEnvironment
|
||||||
|
: RuntimeEnvironment = new HostRuntimeEnvironment(window);
|
||||||
|
|
||||||
|
public readonly isDesktop: boolean;
|
||||||
|
|
||||||
|
public readonly os: OperatingSystem | undefined;
|
||||||
|
|
||||||
|
public readonly isNonProduction: boolean;
|
||||||
|
|
||||||
|
protected constructor(
|
||||||
|
window: Partial<Window>,
|
||||||
|
environmentVariables: IEnvironmentVariables = EnvironmentVariablesFactory.Current.instance,
|
||||||
|
browserOsDetector: BrowserOsDetector = new ConditionBasedOsDetector(),
|
||||||
|
touchDetector = isTouchEnabledDevice,
|
||||||
|
) {
|
||||||
|
if (!window) { throw new Error('missing window'); } // do not trust strictNullChecks for global objects
|
||||||
|
this.isNonProduction = environmentVariables.isNonProduction;
|
||||||
|
this.isDesktop = isDesktop(window);
|
||||||
|
if (this.isDesktop) {
|
||||||
|
this.os = window?.os;
|
||||||
|
} else {
|
||||||
|
this.os = undefined;
|
||||||
|
const userAgent = getUserAgent(window);
|
||||||
|
if (userAgent) {
|
||||||
|
const browserEnvironment: BrowserEnvironment = {
|
||||||
|
userAgent,
|
||||||
|
isTouchSupported: touchDetector(),
|
||||||
|
};
|
||||||
|
this.os = browserOsDetector.detect(browserEnvironment);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function getUserAgent(window: Partial<Window>): string | undefined {
|
||||||
|
return window?.navigator?.userAgent;
|
||||||
|
}
|
||||||
|
|
||||||
|
function isDesktop(window: Partial<WindowVariables>): boolean {
|
||||||
|
return window?.isDesktop === true;
|
||||||
|
}
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
|
||||||
|
|
||||||
export interface IRuntimeEnvironment {
|
|
||||||
readonly isDesktop: boolean;
|
|
||||||
readonly os: OperatingSystem | undefined;
|
|
||||||
readonly isNonProduction: boolean;
|
|
||||||
}
|
|
||||||
@@ -1,50 +1,7 @@
|
|||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
import { WindowVariables } from '@/infrastructure/WindowVariables/WindowVariables';
|
|
||||||
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
|
||||||
import { EnvironmentVariablesFactory } from '@/infrastructure/EnvironmentVariables/EnvironmentVariablesFactory';
|
|
||||||
import { ConditionBasedOsDetector } from './BrowserOs/ConditionBasedOsDetector';
|
|
||||||
import { BrowserEnvironment, BrowserOsDetector } from './BrowserOs/BrowserOsDetector';
|
|
||||||
import { IRuntimeEnvironment } from './IRuntimeEnvironment';
|
|
||||||
import { isTouchEnabledDevice } from './TouchSupportDetection';
|
|
||||||
|
|
||||||
export class RuntimeEnvironment implements IRuntimeEnvironment {
|
export interface RuntimeEnvironment {
|
||||||
public static readonly CurrentEnvironment: IRuntimeEnvironment = new RuntimeEnvironment(window);
|
readonly isDesktop: boolean;
|
||||||
|
readonly os: OperatingSystem | undefined;
|
||||||
public readonly isDesktop: boolean;
|
readonly isNonProduction: boolean;
|
||||||
|
|
||||||
public readonly os: OperatingSystem | undefined;
|
|
||||||
|
|
||||||
public readonly isNonProduction: boolean;
|
|
||||||
|
|
||||||
protected constructor(
|
|
||||||
window: Partial<Window>,
|
|
||||||
environmentVariables: IEnvironmentVariables = EnvironmentVariablesFactory.Current.instance,
|
|
||||||
browserOsDetector: BrowserOsDetector = new ConditionBasedOsDetector(),
|
|
||||||
touchDetector = isTouchEnabledDevice,
|
|
||||||
) {
|
|
||||||
if (!window) { throw new Error('missing window'); } // do not trust strictNullChecks for global objects
|
|
||||||
this.isNonProduction = environmentVariables.isNonProduction;
|
|
||||||
this.isDesktop = isDesktop(window);
|
|
||||||
if (this.isDesktop) {
|
|
||||||
this.os = window?.os;
|
|
||||||
} else {
|
|
||||||
this.os = undefined;
|
|
||||||
const userAgent = getUserAgent(window);
|
|
||||||
if (userAgent) {
|
|
||||||
const browserEnvironment: BrowserEnvironment = {
|
|
||||||
userAgent,
|
|
||||||
isTouchSupported: touchDetector(),
|
|
||||||
};
|
|
||||||
this.os = browserOsDetector.detect(browserEnvironment);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function getUserAgent(window: Partial<Window>): string | undefined {
|
|
||||||
return window?.navigator?.userAgent;
|
|
||||||
}
|
|
||||||
|
|
||||||
function isDesktop(window: Partial<WindowVariables>): boolean {
|
|
||||||
return window?.isDesktop === true;
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
|
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||||
import { IRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/IRuntimeEnvironment';
|
|
||||||
import { ConsoleLogger } from '@/infrastructure/Log/ConsoleLogger';
|
import { ConsoleLogger } from '@/infrastructure/Log/ConsoleLogger';
|
||||||
import { Logger } from '@/application/Common/Log/Logger';
|
import { Logger } from '@/application/Common/Log/Logger';
|
||||||
import { LoggerFactory } from '@/application/Common/Log/LoggerFactory';
|
import { LoggerFactory } from '@/application/Common/Log/LoggerFactory';
|
||||||
@@ -11,7 +11,9 @@ export class ClientLoggerFactory implements LoggerFactory {
|
|||||||
|
|
||||||
public readonly logger: Logger;
|
public readonly logger: Logger;
|
||||||
|
|
||||||
protected constructor(environment: IRuntimeEnvironment = RuntimeEnvironment.CurrentEnvironment) {
|
protected constructor(
|
||||||
|
environment: RuntimeEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||||
|
) {
|
||||||
if (environment.isDesktop) {
|
if (environment.isDesktop) {
|
||||||
this.logger = new WindowInjectedLogger();
|
this.logger = new WindowInjectedLogger();
|
||||||
return;
|
return;
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import { useAutoUnsubscribedEvents } from '@/presentation/components/Shared/Hook
|
|||||||
import { useClipboard } from '@/presentation/components/Shared/Hooks/Clipboard/UseClipboard';
|
import { useClipboard } from '@/presentation/components/Shared/Hooks/Clipboard/UseClipboard';
|
||||||
import { useCurrentCode } from '@/presentation/components/Shared/Hooks/UseCurrentCode';
|
import { useCurrentCode } from '@/presentation/components/Shared/Hooks/UseCurrentCode';
|
||||||
import { IApplicationContext } from '@/application/Context/IApplicationContext';
|
import { IApplicationContext } from '@/application/Context/IApplicationContext';
|
||||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
|
||||||
import {
|
import {
|
||||||
AnyLifetimeInjectionKey, InjectionKeySelector, InjectionKeys, SingletonKey,
|
AnyLifetimeInjectionKey, InjectionKeySelector, InjectionKeys, SingletonKey,
|
||||||
TransientKey, injectKey,
|
TransientKey, injectKey,
|
||||||
@@ -14,6 +13,7 @@ import { PropertyKeys } from '@/TypeHelpers';
|
|||||||
import { useUserSelectionState } from '@/presentation/components/Shared/Hooks/UseUserSelectionState';
|
import { useUserSelectionState } from '@/presentation/components/Shared/Hooks/UseUserSelectionState';
|
||||||
import { useLogger } from '@/presentation/components/Shared/Hooks/UseLogger';
|
import { useLogger } from '@/presentation/components/Shared/Hooks/UseLogger';
|
||||||
import { useCodeRunner } from '@/presentation/components/Shared/Hooks/UseCodeRunner';
|
import { useCodeRunner } from '@/presentation/components/Shared/Hooks/UseCodeRunner';
|
||||||
|
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||||
|
|
||||||
export function provideDependencies(
|
export function provideDependencies(
|
||||||
context: IApplicationContext,
|
context: IApplicationContext,
|
||||||
@@ -33,7 +33,7 @@ export function provideDependencies(
|
|||||||
),
|
),
|
||||||
useRuntimeEnvironment: (di) => di.provide(
|
useRuntimeEnvironment: (di) => di.provide(
|
||||||
InjectionKeys.useRuntimeEnvironment,
|
InjectionKeys.useRuntimeEnvironment,
|
||||||
RuntimeEnvironment.CurrentEnvironment,
|
HostRuntimeEnvironment.CurrentEnvironment,
|
||||||
),
|
),
|
||||||
useAutoUnsubscribedEvents: (di) => di.provide(
|
useAutoUnsubscribedEvents: (di) => di.provide(
|
||||||
InjectionKeys.useAutoUnsubscribedEvents,
|
InjectionKeys.useAutoUnsubscribedEvents,
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { IRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/IRuntimeEnvironment';
|
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
|
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||||
import { Bootstrapper } from '../Bootstrapper';
|
import { Bootstrapper } from '../Bootstrapper';
|
||||||
|
|
||||||
export class MobileSafariActivePseudoClassEnabler implements Bootstrapper {
|
export class MobileSafariActivePseudoClassEnabler implements Bootstrapper {
|
||||||
constructor(
|
constructor(
|
||||||
private readonly currentEnvironment = RuntimeEnvironment.CurrentEnvironment,
|
private readonly currentEnvironment = HostRuntimeEnvironment.CurrentEnvironment,
|
||||||
private readonly browser: BrowserAccessor = GlobalBrowserAccessor,
|
private readonly browser: BrowserAccessor = GlobalBrowserAccessor,
|
||||||
) {
|
) {
|
||||||
|
|
||||||
@@ -42,14 +42,14 @@ export interface BrowserAccessor {
|
|||||||
addWindowEventListener(...args: Parameters<typeof window.addEventListener>): void;
|
addWindowEventListener(...args: Parameters<typeof window.addEventListener>): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function isMobileSafari(environment: IRuntimeEnvironment, userAgent: string): boolean {
|
function isMobileSafari(environment: RuntimeEnvironment, userAgent: string): boolean {
|
||||||
if (!isMobileAppleOperatingSystem(environment)) {
|
if (!isMobileAppleOperatingSystem(environment)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
return isSafari(userAgent);
|
return isSafari(userAgent);
|
||||||
}
|
}
|
||||||
|
|
||||||
function isMobileAppleOperatingSystem(environment: IRuntimeEnvironment): boolean {
|
function isMobileAppleOperatingSystem(environment: RuntimeEnvironment): boolean {
|
||||||
if (environment.os === undefined) {
|
if (environment.os === undefined) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,11 +26,9 @@ export default defineComponent({
|
|||||||
|
|
||||||
async function executeCode() {
|
async function executeCode() {
|
||||||
if (!codeRunner) { throw new Error('missing code runner'); }
|
if (!codeRunner) { throw new Error('missing code runner'); }
|
||||||
if (os === undefined) { throw new Error('unidentified host operating system'); }
|
|
||||||
await codeRunner.runCode(
|
await codeRunner.runCode(
|
||||||
currentContext.state.code.current,
|
currentContext.state.code.current,
|
||||||
currentContext.app.info.name,
|
currentContext.app.info.name,
|
||||||
os,
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { IRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/IRuntimeEnvironment';
|
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||||
|
|
||||||
export function useRuntimeEnvironment(environment: IRuntimeEnvironment) {
|
export function useRuntimeEnvironment(environment: RuntimeEnvironment) {
|
||||||
return environment;
|
return environment;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ import { OperatingSystem } from '@/domain/OperatingSystem';
|
|||||||
import { MobileSafariActivePseudoClassEnabler } from '@/presentation/bootstrapping/Modules/MobileSafariActivePseudoClassEnabler';
|
import { MobileSafariActivePseudoClassEnabler } from '@/presentation/bootstrapping/Modules/MobileSafariActivePseudoClassEnabler';
|
||||||
import { EventName, createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
|
import { EventName, createWindowEventSpies } from '@tests/shared/Spies/WindowEventSpies';
|
||||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||||
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
|
||||||
import { isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/TouchSupportDetection';
|
import { isTouchEnabledDevice } from '@/infrastructure/RuntimeEnvironment/TouchSupportDetection';
|
||||||
|
import { HostRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/HostRuntimeEnvironment';
|
||||||
import { MobileSafariDetectionTestCases } from './MobileSafariDetectionTestCases';
|
import { MobileSafariDetectionTestCases } from './MobileSafariDetectionTestCases';
|
||||||
|
|
||||||
describe('MobileSafariActivePseudoClassEnabler', () => {
|
describe('MobileSafariActivePseudoClassEnabler', () => {
|
||||||
@@ -59,7 +59,7 @@ function getTouchDetectorMock(
|
|||||||
return () => isTouchEnabled;
|
return () => isTouchEnabled;
|
||||||
}
|
}
|
||||||
|
|
||||||
class ConstructibleRuntimeEnvironment extends RuntimeEnvironment {
|
class ConstructibleRuntimeEnvironment extends HostRuntimeEnvironment {
|
||||||
public constructor(isTouchEnabled: boolean) {
|
public constructor(isTouchEnabled: boolean) {
|
||||||
super(window, undefined, undefined, getTouchDetectorMock(isTouchEnabled));
|
super(window, undefined, undefined, getTouchDetectorMock(isTouchEnabled));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 { describe, it, expect } from 'vitest';
|
||||||
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
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 { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||||
|
import { RuntimeEnvironmentStub } from '@tests/unit/shared/Stubs/RuntimeEnvironmentStub';
|
||||||
|
|
||||||
describe('FileNameGenerator', () => {
|
describe('OsTimestampedFilenameGenerator', () => {
|
||||||
describe('generateOsTimestampedFileName', () => {
|
describe('generateFilename', () => {
|
||||||
it('generates correct prefix', () => {
|
it('generates correct prefix', () => {
|
||||||
// arrange
|
// arrange
|
||||||
const expectedPrefix = 'run';
|
const expectedPrefix = 'run';
|
||||||
// act
|
// act
|
||||||
const fileName = generateFileNamePartsForTesting();
|
const filename = generateFilenamePartsForTesting();
|
||||||
// assert
|
// assert
|
||||||
expect(fileName.prefix).to.equal(expectedPrefix);
|
expect(filename.prefix).to.equal(expectedPrefix);
|
||||||
});
|
});
|
||||||
it('generates correct timestamp', () => {
|
it('generates correct timestamp', () => {
|
||||||
// arrange
|
// arrange
|
||||||
@@ -20,10 +21,10 @@ describe('FileNameGenerator', () => {
|
|||||||
const expectedTimestamp = '2023-01-01_12-00-00';
|
const expectedTimestamp = '2023-01-01_12-00-00';
|
||||||
const date = new Date(currentDate);
|
const date = new Date(currentDate);
|
||||||
// act
|
// act
|
||||||
const fileName = generateFileNamePartsForTesting({ date });
|
const filename = generateFilenamePartsForTesting({ date });
|
||||||
// assert
|
// assert
|
||||||
expect(fileName.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[
|
expect(filename.timestamp).to.equal(expectedTimestamp, formatAssertionMessage[
|
||||||
`Generated file name: ${fileName.generatedFileName}`
|
`Generated file name: ${filename.generatedFileName}`
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
describe('generates correct extension', () => {
|
describe('generates correct extension', () => {
|
||||||
@@ -37,21 +38,37 @@ describe('FileNameGenerator', () => {
|
|||||||
// arrange
|
// arrange
|
||||||
const expectedExtension = testScenarios[operatingSystem];
|
const expectedExtension = testScenarios[operatingSystem];
|
||||||
// act
|
// act
|
||||||
const fileName = generateFileNamePartsForTesting({ operatingSystem });
|
const filename = generateFilenamePartsForTesting({ operatingSystem });
|
||||||
// assert
|
// assert
|
||||||
expect(fileName.extension).to.equal(expectedExtension, formatAssertionMessage[
|
expect(filename.extension).to.equal(expectedExtension, formatAssertionMessage[
|
||||||
`Generated file name: ${fileName.generatedFileName}`
|
`Generated file name: ${filename.generatedFileName}`
|
||||||
]);
|
]);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
it('generates filename without extension for unknown OS', () => {
|
describe('generates filename without extension for unknown OS', () => {
|
||||||
// arrange
|
// arrange
|
||||||
const unknownOs = 'Unknown' as unknown as OperatingSystem;
|
const testScenarios: ReadonlyArray<{
|
||||||
// act
|
readonly description: string;
|
||||||
const fileName = generateFileNamePartsForTesting({ operatingSystem: unknownOs });
|
readonly unknownOs?: OperatingSystem;
|
||||||
// assert
|
}> = [
|
||||||
expect(fileName.extension).toBeUndefined();
|
{
|
||||||
|
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;
|
readonly generatedFileName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateFileNamePartsForTesting(testScenario?: {
|
function generateFilenamePartsForTesting(testScenario?: {
|
||||||
operatingSystem?: OperatingSystem,
|
operatingSystem?: OperatingSystem,
|
||||||
date?: Date,
|
date?: Date,
|
||||||
}): TestFileNameComponents {
|
}): TestFileNameComponents {
|
||||||
const operatingSystem = testScenario?.operatingSystem ?? OperatingSystem.Windows;
|
|
||||||
const date = testScenario?.date ?? new Date();
|
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 pattern = /^(?<prefix>[^-]+)-(?<timestamp>[^.]+)(?:\.(?<extension>[^.]+))?$/; // prefix-timestamp.extension
|
||||||
const match = fileName.match(pattern);
|
const match = filename.match(pattern);
|
||||||
if (!match?.groups?.prefix || !match?.groups?.timestamp) {
|
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 {
|
return {
|
||||||
generatedFileName: fileName,
|
generatedFileName: filename,
|
||||||
prefix: match.groups.prefix,
|
prefix: match.groups.prefix,
|
||||||
timestamp: match.groups.timestamp,
|
timestamp: match.groups.timestamp,
|
||||||
extension: match.groups.extension,
|
extension: match.groups.extension,
|
||||||
@@ -1,18 +1,18 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
|
||||||
import { FileSystemOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
import { FileSystemOps, SystemOperations } from '@/infrastructure/CodeRunner/SystemOperations/SystemOperations';
|
||||||
import { FileNameGenerator, TemporaryFileCodeRunner } from '@/infrastructure/CodeRunner/TemporaryFileCodeRunner';
|
import { TemporaryFileCodeRunner } from '@/infrastructure/CodeRunner/TemporaryFileCodeRunner';
|
||||||
import { expectThrowsAsync } from '@tests/shared/Assertions/ExpectThrowsAsync';
|
|
||||||
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
import { SystemOperationsStub } from '@tests/unit/shared/Stubs/SystemOperationsStub';
|
||||||
import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub';
|
import { OperatingSystemOpsStub } from '@tests/unit/shared/Stubs/OperatingSystemOpsStub';
|
||||||
import { LocationOpsStub } from '@tests/unit/shared/Stubs/LocationOpsStub';
|
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 { FunctionKeys } from '@/TypeHelpers';
|
||||||
import { AllSupportedOperatingSystems, SupportedOperatingSystem } from '@tests/shared/TestCases/SupportedOperatingSystems';
|
|
||||||
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
import { formatAssertionMessage } from '@tests/shared/FormatAssertionMessage';
|
||||||
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
import { LoggerStub } from '@tests/unit/shared/Stubs/LoggerStub';
|
||||||
import { Logger } from '@/application/Common/Log/Logger';
|
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('TemporaryFileCodeRunner', () => {
|
||||||
describe('runCode', () => {
|
describe('runCode', () => {
|
||||||
@@ -69,26 +69,6 @@ describe('TemporaryFileCodeRunner', () => {
|
|||||||
const [, actualData] = calls[0].args;
|
const [, actualData] = calls[0].args;
|
||||||
expect(actualData).to.equal(expectedCode);
|
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 () => {
|
it('creates file in expected directory', async () => {
|
||||||
// arrange
|
// arrange
|
||||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||||
@@ -128,9 +108,9 @@ describe('TemporaryFileCodeRunner', () => {
|
|||||||
// arrange
|
// arrange
|
||||||
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
const pathSegmentSeparator = '/PATH-SEGMENT-SEPARATOR/';
|
||||||
const filesystem = new FileSystemOpsStub();
|
const filesystem = new FileSystemOpsStub();
|
||||||
const expectedFileName = 'expected-script-file-name';
|
const expectedFilename = 'expected-script-file-name';
|
||||||
const context = new CodeRunnerTestSetup()
|
const context = new CodeRunnerTestSetup()
|
||||||
.withFileNameGenerator(() => expectedFileName)
|
.withFileNameGenerator(new FilenameGeneratorStub().withFilename(expectedFilename))
|
||||||
.withSystemOperationsStub((ops) => ops
|
.withSystemOperationsStub((ops) => ops
|
||||||
.withFileSystem(filesystem)
|
.withFileSystem(filesystem)
|
||||||
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator)));
|
.withLocation(new LocationOpsStub().withDefaultSeparator(pathSegmentSeparator)));
|
||||||
@@ -149,99 +129,10 @@ describe('TemporaryFileCodeRunner', () => {
|
|||||||
`Actual file path: ${actualFilePath}`,
|
`Actual file path: ${actualFilePath}`,
|
||||||
]));
|
]));
|
||||||
});
|
});
|
||||||
});
|
it('creates file after creating the directory', async () => {
|
||||||
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.
|
|
||||||
const expectedOrder: readonly FunctionKeys<FileSystemOps>[] = [
|
const expectedOrder: readonly FunctionKeys<FileSystemOps>[] = [
|
||||||
'createDirectory',
|
'createDirectory',
|
||||||
'writeToFile',
|
'writeToFile',
|
||||||
'setFilePermissions',
|
|
||||||
];
|
];
|
||||||
const fileSystem = new FileSystemOpsStub();
|
const fileSystem = new FileSystemOpsStub();
|
||||||
const context = new CodeRunnerTestSetup()
|
const context = new CodeRunnerTestSetup()
|
||||||
@@ -258,31 +149,50 @@ describe('TemporaryFileCodeRunner', () => {
|
|||||||
expect(expectedOrder).to.deep.equal(actualOrder);
|
expect(expectedOrder).to.deep.equal(actualOrder);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
describe('throws with invalid OS', () => {
|
describe('file execution', () => {
|
||||||
const testScenarios: ReadonlyArray<{
|
it('executes correct file', async () => {
|
||||||
readonly description: string;
|
// arrange
|
||||||
readonly invalidOs: OperatingSystem;
|
const fileSystem = new FileSystemOpsStub();
|
||||||
readonly expectedError: string;
|
const fileExecutor = new ScriptFileExecutorStub();
|
||||||
}> = [
|
const context = new CodeRunnerTestSetup()
|
||||||
(() => {
|
.withSystemOperationsStub((ops) => ops.withFileSystem(fileSystem))
|
||||||
const unsupportedOs = OperatingSystem.Android;
|
.withFileExecutor(fileExecutor);
|
||||||
return {
|
|
||||||
description: 'unsupported OS',
|
// act
|
||||||
invalidOs: unsupportedOs,
|
await context.runCode();
|
||||||
expectedError: `unsupported os: ${OperatingSystem[unsupportedOs]}`,
|
|
||||||
};
|
// assert
|
||||||
})(),
|
const writeFileCalls = fileSystem.callHistory.filter((call) => call.methodName === 'writeToFile');
|
||||||
];
|
expect(writeFileCalls.length).to.equal(1);
|
||||||
testScenarios.forEach(({ description, invalidOs, expectedError }) => {
|
const [expectedFilePath] = writeFileCalls[0].args;
|
||||||
it(description, async () => {
|
const execFileCalls = fileExecutor.callHistory.filter((call) => call.methodName === 'executeScriptFile');
|
||||||
// arrange
|
expect(execFileCalls.length).to.equal(1);
|
||||||
const context = new CodeRunnerTestSetup()
|
const [actualPath] = execFileCalls[0].args;
|
||||||
.withOs(invalidOs);
|
expect(actualPath).to.equal(expectedFilePath);
|
||||||
// act
|
});
|
||||||
const act = async () => { await context.runCode(); };
|
it('executes after creating the file', async () => {
|
||||||
// assert
|
// arrange
|
||||||
await expectThrowsAsync(act, expectedError);
|
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 folderName = `[${CodeRunnerTestSetup.name}]folderName`;
|
||||||
|
|
||||||
private fileNameGenerator: FileNameGenerator = () => `[${CodeRunnerTestSetup.name}]file-name-stub`;
|
private filenameGenerator: FilenameGenerator = new FilenameGeneratorStub();
|
||||||
|
|
||||||
private os: OperatingSystem = OperatingSystem.Windows;
|
|
||||||
|
|
||||||
private systemOperations: SystemOperations = new SystemOperationsStub();
|
private systemOperations: SystemOperations = new SystemOperationsStub();
|
||||||
|
|
||||||
|
private fileExecutor: ScriptFileExecutor = new ScriptFileExecutorStub();
|
||||||
|
|
||||||
private logger: Logger = new LoggerStub();
|
private logger: Logger = new LoggerStub();
|
||||||
|
|
||||||
public async runCode(): Promise<void> {
|
public async runCode(): Promise<void> {
|
||||||
const runner = new TemporaryFileCodeRunner(
|
const runner = new TemporaryFileCodeRunner(
|
||||||
this.systemOperations,
|
this.systemOperations,
|
||||||
this.fileNameGenerator,
|
this.filenameGenerator,
|
||||||
this.logger,
|
this.logger,
|
||||||
|
this.fileExecutor,
|
||||||
);
|
);
|
||||||
await runner.runCode(this.code, this.folderName, this.os);
|
await runner.runCode(this.code, this.folderName);
|
||||||
}
|
}
|
||||||
|
|
||||||
public withSystemOperations(
|
public withSystemOperations(
|
||||||
@@ -324,13 +235,13 @@ class CodeRunnerTestSetup {
|
|||||||
return this.withSystemOperations(stub);
|
return this.withSystemOperations(stub);
|
||||||
}
|
}
|
||||||
|
|
||||||
public withOs(os: OperatingSystem): this {
|
public withFolderName(folderName: string): this {
|
||||||
this.os = os;
|
this.folderName = folderName;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public withFolderName(folderName: string): this {
|
public withFileExecutor(fileExecutor: ScriptFileExecutor): this {
|
||||||
this.folderName = folderName;
|
this.fileExecutor = fileExecutor;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -339,8 +250,8 @@ class CodeRunnerTestSetup {
|
|||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
|
|
||||||
public withFileNameGenerator(fileNameGenerator: FileNameGenerator): this {
|
public withFileNameGenerator(fileNameGenerator: FilenameGenerator): this {
|
||||||
this.fileNameGenerator = fileNameGenerator;
|
this.filenameGenerator = fileNameGenerator;
|
||||||
return this;
|
return this;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,14 +2,14 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
|
import { BrowserOsDetector } from '@/infrastructure/RuntimeEnvironment/BrowserOs/BrowserOsDetector';
|
||||||
import { OperatingSystem } from '@/domain/OperatingSystem';
|
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 { itEachAbsentObjectValue } from '@tests/unit/shared/TestCases/AbsentTests';
|
||||||
import { BrowserOsDetectorStub } from '@tests/unit/shared/Stubs/BrowserOsDetectorStub';
|
import { BrowserOsDetectorStub } from '@tests/unit/shared/Stubs/BrowserOsDetectorStub';
|
||||||
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
import { IEnvironmentVariables } from '@/infrastructure/EnvironmentVariables/IEnvironmentVariables';
|
||||||
import { EnvironmentVariablesStub } from '@tests/unit/shared/Stubs/EnvironmentVariablesStub';
|
import { EnvironmentVariablesStub } from '@tests/unit/shared/Stubs/EnvironmentVariablesStub';
|
||||||
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
import { expectExists } from '@tests/shared/Assertions/ExpectExists';
|
||||||
|
|
||||||
describe('RuntimeEnvironment', () => {
|
describe('HostRuntimeEnvironment', () => {
|
||||||
describe('ctor', () => {
|
describe('ctor', () => {
|
||||||
describe('throws if window is absent', () => {
|
describe('throws if window is absent', () => {
|
||||||
itEachAbsentObjectValue((absentValue) => {
|
itEachAbsentObjectValue((absentValue) => {
|
||||||
@@ -190,7 +190,7 @@ function createEnvironment(options: Partial<EnvironmentOptions> = {}): TestableR
|
|||||||
return new TestableRuntimeEnvironment({ ...defaultOptions, ...options });
|
return new TestableRuntimeEnvironment({ ...defaultOptions, ...options });
|
||||||
}
|
}
|
||||||
|
|
||||||
class TestableRuntimeEnvironment extends RuntimeEnvironment {
|
class TestableRuntimeEnvironment extends HostRuntimeEnvironment {
|
||||||
/* Using a separate object instead of `ConstructorParameter<..>` */
|
/* Using a separate object instead of `ConstructorParameter<..>` */
|
||||||
public constructor(options: Required<EnvironmentOptions>) {
|
public constructor(options: Required<EnvironmentOptions>) {
|
||||||
super(
|
super(
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
import {
|
import {
|
||||||
describe, it, beforeEach, afterEach,
|
describe, it, beforeEach, afterEach,
|
||||||
} from 'vitest';
|
} from 'vitest';
|
||||||
import { IRuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/IRuntimeEnvironment';
|
import { RuntimeEnvironment } from '@/infrastructure/RuntimeEnvironment/RuntimeEnvironment';
|
||||||
import { ClientLoggerFactory } from '@/presentation/bootstrapping/ClientLoggerFactory';
|
import { ClientLoggerFactory } from '@/presentation/bootstrapping/ClientLoggerFactory';
|
||||||
import { Logger } from '@/application/Common/Log/Logger';
|
import { Logger } from '@/application/Common/Log/Logger';
|
||||||
import { WindowInjectedLogger } from '@/infrastructure/Log/WindowInjectedLogger';
|
import { WindowInjectedLogger } from '@/infrastructure/Log/WindowInjectedLogger';
|
||||||
@@ -30,7 +30,7 @@ describe('ClientLoggerFactory', () => {
|
|||||||
const testCases: Array<{
|
const testCases: Array<{
|
||||||
readonly description: string,
|
readonly description: string,
|
||||||
readonly expectedType: Constructible<Logger>,
|
readonly expectedType: Constructible<Logger>,
|
||||||
readonly environment: IRuntimeEnvironment,
|
readonly environment: RuntimeEnvironment,
|
||||||
}> = [
|
}> = [
|
||||||
{
|
{
|
||||||
description: 'desktop environment',
|
description: 'desktop environment',
|
||||||
@@ -74,7 +74,7 @@ describe('ClientLoggerFactory', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
class TestableClientLoggerFactory extends ClientLoggerFactory {
|
class TestableClientLoggerFactory extends ClientLoggerFactory {
|
||||||
public constructor(environment: IRuntimeEnvironment) {
|
public constructor(environment: RuntimeEnvironment) {
|
||||||
super(environment);
|
super(environment);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import { StubWithObservableMethodCalls } from './StubWithObservableMethodCalls';
|
|||||||
export class CommandOpsStub
|
export class CommandOpsStub
|
||||||
extends StubWithObservableMethodCalls<CommandOps>
|
extends StubWithObservableMethodCalls<CommandOps>
|
||||||
implements CommandOps {
|
implements CommandOps {
|
||||||
public execute(command: string): Promise<void> {
|
public exec(command: string): Promise<void> {
|
||||||
this.registerMethodCall({
|
this.registerMethodCall({
|
||||||
methodName: 'execute',
|
methodName: 'exec',
|
||||||
args: [command],
|
args: [command],
|
||||||
});
|
});
|
||||||
return Promise.resolve();
|
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';
|
import { OperatingSystem } from '@/domain/OperatingSystem';
|
||||||
|
|
||||||
export class RuntimeEnvironmentStub implements IRuntimeEnvironment {
|
export class RuntimeEnvironmentStub implements RuntimeEnvironment {
|
||||||
public isNonProduction = true;
|
public isNonProduction = true;
|
||||||
|
|
||||||
public isDesktop = 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