From 9d72732cfdc8a5235e53113d961db9dfc1d9fff6 Mon Sep 17 00:00:00 2001 From: Leo dev Date: Wed, 6 Aug 2025 13:21:37 -0500 Subject: [PATCH] Javascript tester --- src/extension.ts | 29 +++++++++++++++++++++++++++++ src/tester.ts | 42 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 src/tester.ts diff --git a/src/extension.ts b/src/extension.ts index b36d0fe..20423df 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -1,8 +1,37 @@ import * as vscode from 'vscode'; +import os from 'os'; +import path from 'path'; +import testCode from './tester'; let resetTimer = () => {} +const speedCodePath = path.join(os.homedir(), ".speed-code/"); + +export async function openAndFocusFile(filePath: string) { + const document = await vscode.workspace.openTextDocument(filePath); + await vscode.window.showTextDocument(document, { preview: false, preserveFocus: false }); +} + +const userCode = ` +function isPalindrome(s) { + return s === s.split('').reverse().join(''); +} +`; + export function activate(context: vscode.ExtensionContext) { + const [isValid, res] = testCode(userCode, [{ + input: ["racecar"], + expected: true + },{ + input: ["hello"], + expected: false + },{ + input: ["madam"], + expected: true + },]); + + vscode.window.showInformationMessage('Speedrun info: ' + JSON.stringify(res)); + const statusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Left, 100); statusBarItem.tooltip = 'Speedrun timer'; statusBarItem.text = "No active Speedrun"; diff --git a/src/tester.ts b/src/tester.ts new file mode 100644 index 0000000..ba7fb00 --- /dev/null +++ b/src/tester.ts @@ -0,0 +1,42 @@ +import vm from 'vm'; +import assert from 'assert'; + +export interface TestCase { input: any[], expected: any }; +export interface TestResult extends TestCase { result: any, valid: boolean }; + +export default function testCode(code: string, testCases: TestCase[]): [boolean, TestResult[]] { + const context: Record = {}; + vm.createContext(context); + + const beforeKeys = new Set(Object.keys(context)); + + const script = new vm.Script(code); + script.runInContext(context); + + const afterKeys = Object.keys(context); + const newKeys = afterKeys.filter(k => !beforeKeys.has(k)); + + // Find the last function defined + const funcs = newKeys + .map(k => context[k]) + .filter(v => typeof v === 'function'); + + if (funcs.length === 0) { + throw new Error("No function was defined in the code."); + } + + const targetFn = funcs[funcs.length - 1]; + + const tests = testCases.map((t) => { + const result = targetFn(...t.input); + + try { + assert.strictEqual(result, t.expected); + return { ...t, valid: true, result }; + } catch { + return { ...t, valid: false, result }; + } + }); + + return [tests.every(t => t), tests]; +}