From 268729bb625a89cc4cb56da40c207c6242ee8370 Mon Sep 17 00:00:00 2001 From: hyperion Date: Sun, 23 Aug 2026 06:39:37 +0200 Subject: [PATCH] WRITE UNIT TESTS!!! first async command working, no unit tests done AGAING --- src/core/command_registry.ts | 2 + src/core/commands/cd.ts | 8 ++- src/core/commands/echo.ts | 12 +++- src/core/commands/testasync.ts | 44 +++++++++++++ src/core/util/errors.ts | 1 + src/index.ts | 6 +- src/shell/db_manager.ts | 17 ----- src/shell/event_emitter.ts | 18 +++--- src/shell/process.ts | 26 ++++++-- src/shell/process_manager.ts | 28 ++++++-- src/shell/serializer.ts | 8 ++- src/shell/shell.ts | 96 ++++++++++++++++++++-------- src/util/cache_manager.ts | 3 +- src/util/hash.ts | 6 +- test/core/commands/cd.test.ts | 36 ++++++++--- test/core/commands/echo.test.ts | 22 ++++++- test/core/commands/testasync.test.ts | 79 +++++++++++++++++++++++ test/shell/shell.test.ts | 12 +++- 18 files changed, 331 insertions(+), 93 deletions(-) create mode 100644 src/core/commands/testasync.ts delete mode 100644 src/shell/db_manager.ts create mode 100644 test/core/commands/testasync.test.ts diff --git a/src/core/command_registry.ts b/src/core/command_registry.ts index 53da34f..96e7f6b 100644 --- a/src/core/command_registry.ts +++ b/src/core/command_registry.ts @@ -1,11 +1,13 @@ import type { CommandDescriptor } from "./command"; import { descriptor as cd } from "./commands/cd"; import { descriptor as echo } from "./commands/echo"; +import { descriptor as testasync } from "./commands/testasync"; const reg = new Map(); //reg.set(descriptor.name, descriptor <- imported const from command implementation file); reg.set(echo.name, echo); reg.set(cd.name, cd); +reg.set(testasync.name, testasync); Object.freeze(reg); export const COMMAND_REGISTRY: ReadonlyMap = reg; diff --git a/src/core/commands/cd.ts b/src/core/commands/cd.ts index 8a8c912..bac04a8 100644 --- a/src/core/commands/cd.ts +++ b/src/core/commands/cd.ts @@ -1,4 +1,5 @@ import type { CommandDescriptor, CommandOutput } from "@core/command"; +import type { CommandIO } from "@core/command_io"; import type { FileSystem } from "@core/filesystem/filesystem"; import { createErrorResult, createSuccessResult } from "@core/result"; import { getCurrentSession } from "@core/session_manager"; @@ -14,7 +15,12 @@ import { resolveInode, resolvePath } from "@core/util/path_resolver"; export const COMMAND_NAME = "cd"; -function main(state: ShellState, __flags: string[], args: string[]): CommandOutput { +async function main( + __io: CommandIO, + state: ShellState, + __flags: string[], + args: string[], +): Promise> { if (args.length > 1) { return { state, diff --git a/src/core/commands/echo.ts b/src/core/commands/echo.ts index c38bd08..97e901f 100644 --- a/src/core/commands/echo.ts +++ b/src/core/commands/echo.ts @@ -1,4 +1,5 @@ import type { CommandDescriptor, CommandOutput } from "@core/command"; +import type { CommandIO } from "@core/command_io"; import type { ResultSuccess } from "@core/result"; import type { ShellState } from "@core/shell_state"; import type { ShellError } from "@core/util/errors"; @@ -7,16 +8,21 @@ import { createImmutableBuffer } from "@core/util/immutable_buffer"; export const COMMAND_NAME = "echo"; //Need to implement escape sequences -function main(state: ShellState, flags: string[], args: string[]): CommandOutput { +async function main( + io: CommandIO, + state: ShellState, + __flags: string[], + args: string[], +): Promise> { const joined = args.join(" "); const encoded = new TextEncoder().encode(joined); - const stdout = createImmutableBuffer(encoded); + io.writeStdout(encoded); const result: ResultSuccess = { type: "success", exitCode: 0, - stdout, + stdout: createImmutableBuffer(new Uint8Array()), stderr: createImmutableBuffer(new Uint8Array()), commandName: COMMAND_NAME, }; diff --git a/src/core/commands/testasync.ts b/src/core/commands/testasync.ts new file mode 100644 index 0000000..1be9f0e --- /dev/null +++ b/src/core/commands/testasync.ts @@ -0,0 +1,44 @@ +import type { CommandDescriptor, CommandOutput } from "@core/command"; +import type { CommandIO } from "@core/command_io"; +import type { ResultSuccess } from "@core/result"; +import type { ShellState } from "@core/shell_state"; +import type { ShellError } from "@core/util/errors"; +import { createImmutableBuffer } from "@core/util/immutable_buffer"; + +const COMMAND_NAME = "async"; + +async function main( + io: CommandIO, + state: ShellState, + __flags: string[], + __args: string[], +): Promise> { + while (true) { + const out = await io.getSignal(); + + if (out.type === "INPUT") { + const encoded = new TextEncoder().encode(("user pressed: " + out.payload + "\n") as string); + io.writeStdout(encoded); + + if (out.payload === "ctrl+c") { + const result: ResultSuccess = { + type: "success", + exitCode: 0, + stdout: createImmutableBuffer(new Uint8Array()), + stderr: createImmutableBuffer(new Uint8Array()), + commandName: COMMAND_NAME, + }; + + return { + state: state, + result, + }; + } + } + } +} + +export const descriptor = { + fn: main, + name: COMMAND_NAME, +} satisfies CommandDescriptor; diff --git a/src/core/util/errors.ts b/src/core/util/errors.ts index 4a77954..6033cff 100644 --- a/src/core/util/errors.ts +++ b/src/core/util/errors.ts @@ -38,6 +38,7 @@ const EXIT_CODE_MAP: Record = { GenericError: 1, InvalidArguments: 2, + ParseError: 62, UsageError: 63, PathResolutionError: 64, DataFormatError: 65, diff --git a/src/index.ts b/src/index.ts index 2f235d8..3b7f54d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,4 @@ -import { defaultConfig, TermosConfig } from "./config"; +/* import { defaultConfig, TermosConfig } from "./config"; let config: TermosConfig = { ...defaultConfig }; @@ -8,8 +8,8 @@ namespace Termos { console.log("termos initialized"); } } - + */ const message: string = "Hello, World!"; console.log(message); -export { Termos }; +//export { Termos }; diff --git a/src/shell/db_manager.ts b/src/shell/db_manager.ts deleted file mode 100644 index c6c7493..0000000 --- a/src/shell/db_manager.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - Create an interface for the rest of the library to use to fetch nessesary data. - To do that, implement a termos config that will contain the table and db names, aswell as other relevant information - - maybe a flag for headless mode (uses the built-in console frontend module - need to evaluate this idea more) -*/ - -export async fetchFileSystem(): Promise { - -} - -export async fetchUserGroups(): Promise { - -} - -export async fetchUsers(): Promise { - -} diff --git a/src/shell/event_emitter.ts b/src/shell/event_emitter.ts index 0ee26fe..bd3ee75 100644 --- a/src/shell/event_emitter.ts +++ b/src/shell/event_emitter.ts @@ -1,14 +1,16 @@ +type Listener = (payload: unknown) => void; + export class EventEmitter { - private Handlers: Map> = new Map(); + private Handlers: Map> = new Map(); public on(type: K, handler: (payload: TEvents[K]) => void): () => void { const listeners = this.Handlers.get(type); if (listeners) { - listeners.add(handler); + listeners.add(handler as Listener); } else { - const set: Set = new Set(); - set.add(handler); + const set: Set = new Set(); + set.add(handler as Listener); this.Handlers.set(type, set); } @@ -16,7 +18,7 @@ export class EventEmitter { } public off(type: K, handler: (payload: TEvents[K]) => void): void { - this.Handlers.get(type)?.delete(handler); + this.Handlers.get(type)?.delete(handler as Listener); } public once(type: K, handler: (payload: TEvents[K]) => void): () => void { @@ -28,10 +30,10 @@ export class EventEmitter { }; if (listeners) { - listeners.add(wrapper); + listeners.add(wrapper as Listener); } else { - const set: Set = new Set(); - set.add(wrapper); + const set: Set = new Set(); + set.add(wrapper as Listener); this.Handlers.set(type, set); } diff --git a/src/shell/process.ts b/src/shell/process.ts index 683145b..930535f 100644 --- a/src/shell/process.ts +++ b/src/shell/process.ts @@ -14,6 +14,7 @@ export class Process { private _StdoutChunks: Uint8Array[] = []; private _StderrChunks: Uint8Array[] = []; private _Settled: boolean = false; + private _EventEmitter: EventEmitter; private readonly _MaxChunkByteSize: number; readonly PID: number; @@ -21,7 +22,6 @@ export class Process { readonly State: ShellState; readonly Args: string[]; readonly Flags: string[]; - EventEmitter: EventEmitter; constructor(pid: number, state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]) { this.PID = pid; @@ -31,7 +31,7 @@ export class Process { this.Args = args; // Check if positive later and throw an error if so this._MaxChunkByteSize = 1024; - this.EventEmitter = new EventEmitter(); + this._EventEmitter = new EventEmitter(); } private concatUint8Arrays(arrays: Uint8Array[]): Uint8Array { @@ -67,13 +67,13 @@ export class Process { if (data.length <= this._MaxChunkByteSize) { chunks.push(data); - this.EventEmitter.emit(eventType, { pid: this.PID, data }); + this._EventEmitter.emit(eventType, { pid: this.PID, data }); return; } else { const arr = this.divideToChunks(data); for (const ent of arr) { chunks.push(ent); - this.EventEmitter.emit(eventType, { pid: this.PID, data: ent }); + this._EventEmitter.emit(eventType, { pid: this.PID, data: ent }); } } } @@ -118,7 +118,7 @@ export class Process { }; } - this.EventEmitter.emit("result", { pid: this.PID, result, state: output.state }); + this._EventEmitter.emit("result", { pid: this.PID, result, state: output.state }); this._Settled = true; }) .catch(error => { @@ -137,7 +137,7 @@ export class Process { }, ); - this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State }); + this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State }); }); } @@ -161,7 +161,7 @@ export class Process { this.CommandDescriptor.name, ); - this.EventEmitter.emit("result", { pid: this.PID, result, state: this.State }); + this._EventEmitter.emit("result", { pid: this.PID, result, state: this.State }); return; } else { if (this._SignalHandler !== null) { @@ -172,4 +172,16 @@ export class Process { } } } + + public on(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { + return this._EventEmitter.on(type, handler); + } + + public once(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { + return this._EventEmitter.once(type, handler); + } + + public off(type: K, handler: (payload: ShellEventMap[K]) => void): void { + this._EventEmitter.off(type, handler); + } } diff --git a/src/shell/process_manager.ts b/src/shell/process_manager.ts index 4bcb65f..a566ff9 100644 --- a/src/shell/process_manager.ts +++ b/src/shell/process_manager.ts @@ -9,22 +9,24 @@ export class ProcessManager { private _Processes: Map = new Map(); private _PIDIndex: number = 0; - EventEmitter: EventEmitter = new EventEmitter(); + private _EventEmitter: EventEmitter = new EventEmitter(); - public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): void { + public createProcess(state: ShellState, descriptor: CommandDescriptor, flags: string[], args: string[]): number { const pid = ++this._PIDIndex; const process = new Process(pid, state, descriptor, flags, args); this._Processes.set(pid, process); - process.EventEmitter.on("stdout", payload => this.EventEmitter.emit("stdout", payload)); - process.EventEmitter.on("stderr", payload => this.EventEmitter.emit("stderr", payload)); - process.EventEmitter.on("result", payload => { + process.on("stdout", payload => this._EventEmitter.emit("stdout", payload)); + process.on("stderr", payload => this._EventEmitter.emit("stderr", payload)); + process.on("result", payload => { this._Processes.delete(payload.pid); - this.EventEmitter.emit("result", payload); + this._EventEmitter.emit("result", payload); }); - this.EventEmitter.emit("process", { pid, name: descriptor.name }); + this._EventEmitter.emit("process", { pid, name: descriptor.name }); process.execute(); + + return pid; } public sendSignal(pid: number, signal: Signal): void { @@ -51,4 +53,16 @@ export class ProcessManager { //Make global signals an enum later process.sendSignal({ type: "SIGKILL" } satisfies Signal); } + + public on(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { + return this._EventEmitter.on(type, handler); + } + + public once(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { + return this._EventEmitter.once(type, handler); + } + + public off(type: K, handler: (payload: ShellEventMap[K]) => void): void { + this._EventEmitter.off(type, handler); + } } diff --git a/src/shell/serializer.ts b/src/shell/serializer.ts index 7f8317e..82fddc1 100644 --- a/src/shell/serializer.ts +++ b/src/shell/serializer.ts @@ -27,7 +27,8 @@ const DirectoryNodeSchema = z.object({ ctime: z.number(), atime: z.number(), type: z.literal("directory"), - children: z.array(z.lazy((): any => TreeNodeSchema)), + //eslint-ignore + children: z.array(z.lazy((): any => TreeNodeSchema)), // eslint-disable-line @typescript-eslint/no-explicit-any }); const TreeNodeSchema = z.union([FileNodeSchema, DirectoryNodeSchema]); @@ -40,7 +41,8 @@ export function deserializeFileSystem(json: string): ReadonlyMap(); - function parseNode(tree: any, parent: number): void { + // prettier-ignore + function parseNode(tree: any, parent: number): void { // eslint-disable-line @typescript-eslint/no-explicit-any if (tree.type === "directory") { const children: Record = {}; @@ -75,7 +77,7 @@ export function deserializeFileSystem(json: string): ReadonlyMap | null = null; private _State: Readonly; + private _ProcessManager: ProcessManager = new ProcessManager(); + private _EventEmitter: EventEmitter = new EventEmitter(); + private _GlobalKeyMap: ReadonlyMap; + + public BoundPID: number | null = null; private constructor(state: ShellState) { this._State = Object.freeze(state); + this._GlobalKeyMap = new Map(); + + this._ProcessManager.on("stdout", payload => this._EventEmitter.emit("stdout", payload)); + this._ProcessManager.on("stderr", payload => this._EventEmitter.emit("stderr", payload)); + this._ProcessManager.on("process", payload => this._EventEmitter.emit("process", payload)); + this._ProcessManager.on("result", payload => { + this._State = payload.state; + this._State = withExitCode( + this._State, + payload.result.type === "success" ? payload.result.exitCode : payload.result.error.exitCode, + ); + + if (this.BoundPID === payload.pid) this.BoundPID = null; + this._EventEmitter.emit("result", payload); + }); } static async init(initialState: ShellState): Promise { @@ -35,64 +57,76 @@ export class Shell { return Shell.#Promise; } - public async Execute(input: string): Promise> { + public async execute(input: string): Promise { let parsed; try { parsed = parseCommand(input); } catch { - return createErrorResult( + const result = createErrorResult( "ParseError", `Parsing error - ${input}`, {}, createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()), "", - ) satisfies ResultError; + ); + + this._State = withExitCode(this._State, result.error.exitCode); + this._EventEmitter.emit("result", { pid: 0, result, state: this._State }); + return; } - if (parsed.command === "") { - return createSuccessResult( - "", - 0, - createImmutableBuffer(new Uint8Array()), - createImmutableBuffer(new Uint8Array()), - ); - } + if (parsed.command === "") return; this._State = withHistory(this._State, input); const command = COMMAND_REGISTRY.get(parsed.command); - if (!command) - return createErrorResult( + if (!command) { + const result = createErrorResult( "CommandNotFound", `Command ${parsed.command} not found`, { command: parsed.command }, createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()), parsed.command, - ) satisfies ResultError; + ); + + this._State = withExitCode(this._State, result.error.exitCode); + this._EventEmitter.emit("result", { pid: 0, result, state: this._State }); + return; + } if (command.requiresRoot && getCurrentSession(this._State).user.uid != 0) { - return createErrorResult( + const result = createErrorResult( "PermissionDenied", `Permission Denied`, { resource: `Execution of the ${command.name} command` }, createImmutableBuffer(new Uint8Array()), createImmutableBuffer(new Uint8Array()), parsed.command, - ) satisfies ResultError; + ); + + this._State = withExitCode(this._State, result.error.exitCode); + this._EventEmitter.emit("result", { pid: 0, result, state: this._State }); + return; } - const out = command.fn(this._State, parsed.flags, parsed.args); - this._State = out.state; + const pid = this._ProcessManager.createProcess(this._State, command, parsed.flags, parsed.args); + this.BoundPID = pid; + } - if (out.result.type === "error") { - this._State = withExitCode(this._State, out.result.error.exitCode); + public sendInput(input: string): void { + const signal = this._GlobalKeyMap.get(input); + + if (signal !== undefined) { + if (this.BoundPID !== null) { + this._ProcessManager.sendSignal(this.BoundPID, { type: signal }); + } } else { - this._State = withExitCode(this._State, out.result.exitCode); + if (this.BoundPID !== null) { + this._ProcessManager.sendSignal(this.BoundPID, { type: "INPUT", payload: input }); + } } - - return out.result; } public get State(): Readonly { @@ -106,6 +140,18 @@ export class Shell { } return Shell.#Instance; } + + public on(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { + return this._EventEmitter.on(type, handler); + } + + public once(type: K, handler: (payload: ShellEventMap[K]) => void): () => void { + return this._EventEmitter.once(type, handler); + } + + public off(type: K, handler: (payload: ShellEventMap[K]) => void): void { + this._EventEmitter.off(type, handler); + } } export interface ShellEventMap { diff --git a/src/util/cache_manager.ts b/src/util/cache_manager.ts index c7befed..d882219 100644 --- a/src/util/cache_manager.ts +++ b/src/util/cache_manager.ts @@ -1,4 +1,4 @@ -import { MD5 } from "./hash"; +/* import { MD5 } from "./hash"; //INDEXED DB IS SO FUCKING DOGSHIT ITS INSANE @@ -71,3 +71,4 @@ function isChecksumMatching(json: string, checksum: string): boolean { const resourceChksm = MD5.hash(json); return resourceChksm === checksum; } + */ diff --git a/src/util/hash.ts b/src/util/hash.ts index a8dd179..b59c0d7 100644 --- a/src/util/hash.ts +++ b/src/util/hash.ts @@ -52,7 +52,7 @@ export class MD5 { return (b & d) | (c & ~d); } - let AA = A, + const AA = A, BB = B, CC = C, DD = D; @@ -129,7 +129,7 @@ export class MD5 { return new Uint8Array([...out, ...zeroArray, ...lengthBytes]); } - private static sliceToBlocks(input: Uint8Array): number[][] { + /* private static sliceToBlocks(input: Uint8Array): number[][] { const blocks: number[][] = []; for (let i = 0; i < input.length; i += 64) { @@ -138,7 +138,7 @@ export class MD5 { } return blocks; - } + } */ private static sliceToWords(block: Uint8Array): number[] { const words: number[] = new Array(16); diff --git a/test/core/commands/cd.test.ts b/test/core/commands/cd.test.ts index c733033..a51f527 100644 --- a/test/core/commands/cd.test.ts +++ b/test/core/commands/cd.test.ts @@ -1,3 +1,4 @@ +import type { CommandIO } from "@core/command_io"; import { descriptor as cd } from "@core/commands/cd"; import type { ResultError, ResultSuccess } from "@core/result"; import type { UserInfo } from "@core/session_manager"; @@ -44,6 +45,21 @@ const testTree: FixtureNode = { const fs = buildTestFS(testTree); +const stdout: Uint8Array[] = []; +const stderr: Uint8Array[] = []; + +const io: CommandIO = { + writeStdout: (data: Uint8Array) => { + stdout.push(data); + }, + writeStderr: (data: Uint8Array) => { + stderr.push(data); + }, + getSignal: () => { + return new Promise(() => {}); + }, +}; + const users: Map = new Map(); const user: UserInfo = { username: "root", @@ -56,9 +72,9 @@ users.set(0, user); const state: ShellState = createInitialShellState(fs, users, user); -test("changes cwd to home", () => { +test("changes cwd to home", async () => { let newState = withCwd(state, 2); - const output = cd.fn(newState, [], []); + const output = await cd.fn(io, newState, [], []); newState = output.state; const result = output.result; const session = getCurrentSession(newState); @@ -67,10 +83,10 @@ test("changes cwd to home", () => { expect(session.cwd).toBe(0); expect(session.pwd).toBe(2); }); -test("changes cwd to pwd", () => { +test("changes cwd to pwd", async () => { let newState = withCwd(state, 2); - const output = cd.fn(newState, [], ["-"]); + const output = await cd.fn(io, newState, [], ["-"]); newState = output.state; const result = output.result; const session = getCurrentSession(newState); @@ -79,8 +95,8 @@ test("changes cwd to pwd", () => { expect(session.cwd).toBe(0); expect(session.pwd).toBe(2); }); -test("changes cwd to 4", () => { - const output = cd.fn(state, [], ["/sub/bye"]); +test("changes cwd to 4", async () => { + const output = await cd.fn(io, state, [], ["/sub/bye"]); const newState = output.state; const result = output.result; const session = getCurrentSession(newState); @@ -90,8 +106,8 @@ test("changes cwd to 4", () => { expect(session.pwd).toBe(0); }); -test("returns an error result (tried to enter a non existent location)", () => { - const output = cd.fn(state, [], ["/not/real"]); +test("returns an error result (tried to enter a non existent location)", async () => { + const output = await cd.fn(io, state, [], ["/not/real"]); const newState = output.state; const result = output.result; const session = getCurrentSession(newState); @@ -101,8 +117,8 @@ test("returns an error result (tried to enter a non existent location)", () => { expect(session.pwd).toBe(0); }); -test("returns an error result (tried to enter a file)", () => { - const output = cd.fn(state, [], ["/hello.txt"]); +test("returns an error result (tried to enter a file)", async () => { + const output = await cd.fn(io, state, [], ["/hello.txt"]); const newState = output.state; const result = output.result; const session = getCurrentSession(newState); diff --git a/test/core/commands/echo.test.ts b/test/core/commands/echo.test.ts index be43b95..68b8ea9 100644 --- a/test/core/commands/echo.test.ts +++ b/test/core/commands/echo.test.ts @@ -1,3 +1,4 @@ +import type { CommandIO } from "@core/command_io"; import { descriptor as echo } from "@core/commands/echo"; import type { ResultSuccess } from "@core/result"; import type { UserInfo } from "@core/session_manager"; @@ -42,6 +43,21 @@ const testTree: FixtureNode = { const fs = buildTestFS(testTree); +const stdout: Uint8Array[] = []; +const stderr: Uint8Array[] = []; + +const io: CommandIO = { + writeStdout: (data: Uint8Array) => { + stdout.push(data); + }, + writeStderr: (data: Uint8Array) => { + stderr.push(data); + }, + getSignal: () => { + return new Promise(() => {}); + }, +}; + const users: Map = new Map(); const user: UserInfo = { username: "root", @@ -54,9 +70,9 @@ users.set(0, user); const state: ShellState = createInitialShellState(fs, users, user); -test("returns a Result of type success", () => { - const output = echo.fn(state, [], ["hello", "world"]); - const string = new TextDecoder().decode(output.result.stdout.toArray()); +test("returns a Result of type success", async () => { + const output = await echo.fn(io, state, [], ["hello", "world"]); + const string = new TextDecoder().decode(stdout[0]); expect(output.result.type).toBe("success"); expect((output.result as ResultSuccess).exitCode).toBe(0); diff --git a/test/core/commands/testasync.test.ts b/test/core/commands/testasync.test.ts new file mode 100644 index 0000000..1a8be05 --- /dev/null +++ b/test/core/commands/testasync.test.ts @@ -0,0 +1,79 @@ +import type { UserInfo } from "@core/session_manager"; +import { createInitialShellState, type ShellState } from "@core/shell_state"; +import { Shell } from "@shell/shell"; +import { buildTestFS, type FixtureNode } from "@tests/helpers/filesystems_fixture"; +import { test } from "vitest"; + +const testTree: FixtureNode = { + inode: 0, + name: "root", + type: "Dir", + children: [ + { + inode: 1, + name: "hello.txt", + type: "File", + content: "Goodbye World!", + children: [], + }, + { + inode: 2, + name: "sub", + type: "Dir", + children: [ + { + inode: 3, + name: "world.txt", + type: "File", + content: "Goodbye!", + children: [], + }, + { + inode: 4, + name: "bye", + type: "Dir", + children: [], + }, + ], + }, + ], +}; + +const fs = buildTestFS(testTree); + +const stdout: Uint8Array[] = []; + +const users: Map = new Map(); +const user: UserInfo = { + username: "root", + uid: 0, + gid: 0, + group: [0], + home: 0, +}; +users.set(0, user); + +const state: ShellState = createInitialShellState(fs, users, user); + +test("returns a Result of type success", async () => { + await Shell.init(state); + + let result; + + Shell.Instance?.on("result", payload => { + const decoder = new TextDecoder(); + console.log(decoder.decode(payload.result.stdout.toArray())); + console.log(payload); + result = payload.result; + }); + + await Shell.Instance?.execute("async"); + Shell.Instance?.sendInput("a"); + Shell.Instance?.sendInput("b"); + Shell.Instance?.sendInput("c"); + Shell.Instance?.sendInput("d"); + Shell.Instance?.sendInput( + "right now technically anything goes because its just a plain string however i plan on improving this system a bit later on", + ); + Shell.Instance?.sendInput("ctrl+c"); +}); diff --git a/test/shell/shell.test.ts b/test/shell/shell.test.ts index 91e28ac..b839dfa 100644 --- a/test/shell/shell.test.ts +++ b/test/shell/shell.test.ts @@ -56,10 +56,18 @@ const state: ShellState = createInitialShellState(fs, users, user); describe("Shell tests", () => { test("Successfully executes the cd command", async () => { await Shell.init(state); - const result = await Shell.Instance?.Execute("cd /sub"); + + let result; + + Shell.Instance?.on("result", payload => { + console.log(payload); + result = payload.result; + }); + + await Shell.Instance?.execute("cd /sub"); const statee = Shell.Instance?.State; - expect(result?.type).toEqual("success"); + expect(result!.type).toEqual("success"); expect(getCurrentSession(statee!).history.length).toBe(1); expect(getCurrentSession(statee!).history[0]).toEqual("cd /sub"); expect(getCurrentSession(statee!).cwd).toBe(2);