Team Ai
Apppublic

Ratankumar10/code-execution-engine

sourceHugging Faceupdated 8mo agoView on Hugging Face
0likes
test.js366 linesDownload Raw Back to test
1// ─── Test Script ─────────────────────────────2// Run: node test/test.js3// Make sure the server is running on port 30004 5const http = require("http");6 7const BASE_URL = "http://localhost:3000";8 9function request(method, path, body = null) {10  return new Promise((resolve, reject) => {11    const url = new URL(path, BASE_URL);12    const options = {13      hostname: url.hostname,14      port: url.port,15      path: url.pathname,16      method,17      headers: { "Content-Type": "application/json" },18    };19 20    const req = http.request(options, (res) => {21      let data = "";22      res.on("data", (chunk) => (data += chunk));23      res.on("end", () => {24        try {25          resolve({ status: res.statusCode, body: JSON.parse(data) });26        } catch {27          resolve({ status: res.statusCode, body: data });28        }29      });30    });31 32    req.on("error", reject);33    if (body) req.write(JSON.stringify(body));34    req.end();35  });36}37 38async function test(name, fn) {39  try {40    await fn();41    console.log(`  ✅ ${name}`);42  } catch (err) {43    console.log(`  ❌ ${name}: ${err.message}`);44  }45}46 47function assert(condition, message) {48  if (!condition) throw new Error(message);49}50 51async function runTests() {52  console.log("\n═══════════════════════════════════════════════");53  console.log("  Code Execution Engine — Test Suite");54  console.log("═══════════════════════════════════════════════\n");55 56  // ─── Health Check ────────────────────────57  console.log("📋 Health & Info:");58 59  await test("GET /api/health returns ok", async () => {60    const res = await request("GET", "/api/health");61    assert(res.status === 200, `Expected 200, got ${res.status}`);62    assert(res.body.data.status === "ok", "Status should be ok");63  });64 65  await test("GET /api/languages returns supported languages", async () => {66    const res = await request("GET", "/api/languages");67    assert(res.status === 200, `Expected 200, got ${res.status}`);68    assert(res.body.data.languages.c, "Should support C");69    assert(res.body.data.languages.cpp, "Should support C++");70    assert(res.body.data.languages.python, "Should support Python");71  });72 73  // ─── C++ Tests ───────────────────────────74  console.log("\n🔧 C++ Execution:");75 76  await test("C++ Hello World", async () => {77    const res = await request("POST", "/api/execute", {78      language: "cpp",79      code: '#include <iostream>\nusing namespace std;\nint main() {\n    cout << "Hello, World!" << endl;\n    return 0;\n}\n',80      input: "",81    });82    assert(83      res.body.data.verdict === "OK",84      `Expected OK, got ${res.body.data.verdict}`,85    );86    assert(res.body.data.output.trim() === "Hello, World!", "Output mismatch");87    console.log(88      `    → Time: ${res.body.data.executionTime}ms, Memory: ${res.body.data.memoryUsed}KB`,89    );90  });91 92  await test("C++ with stdin (sum of array)", async () => {93    const code = `#include <bits/stdc++.h>94using namespace std;95int main() {96    int n; cin >> n;97    int sum = 0;98    for (int i = 0; i < n; i++) {99        int x; cin >> x;100        sum += x;101    }102    cout << sum << endl;103    return 0;104}`;105    const res = await request("POST", "/api/execute", {106      language: "cpp",107      code,108      input: "5\n1 2 3 4 5\n",109    });110    assert(111      res.body.data.verdict === "OK",112      `Expected OK, got ${res.body.data.verdict}`,113    );114    assert(115      res.body.data.output.trim() === "15",116      `Expected 15, got ${res.body.data.output.trim()}`,117    );118    console.log(119      `    → Time: ${res.body.data.executionTime}ms, Memory: ${res.body.data.memoryUsed}KB`,120    );121  });122 123  await test("C++ Compilation Error", async () => {124    const res = await request("POST", "/api/execute", {125      language: "cpp",126      code: '#include <iostream>\nint main() { cout << "test" }',127      input: "",128    });129    assert(130      res.body.data.verdict === "CE",131      `Expected CE, got ${res.body.data.verdict}`,132    );133  });134 135  await test("C++ Runtime Error (segfault)", async () => {136    const res = await request("POST", "/api/execute", {137      language: "cpp",138      code: "#include <cstdlib>\nint main() { int *p = nullptr; *p = 42; return 0; }",139      input: "",140    });141    assert(142      res.body.data.verdict === "RE",143      `Expected RE, got ${res.body.data.verdict}`,144    );145  });146 147  await test("C++ Time Limit Exceeded", async () => {148    const res = await request("POST", "/api/execute", {149      language: "cpp",150      code: "#include <iostream>\nint main() { while(true); return 0; }",151      input: "",152      timeLimit: 2,153    });154    assert(155      res.body.data.verdict === "TLE",156      `Expected TLE, got ${res.body.data.verdict}`,157    );158  });159 160  // ─── C Tests ─────────────────────────────161  console.log("\n🔧 C Execution:");162 163  await test("C Hello World", async () => {164    const res = await request("POST", "/api/execute", {165      language: "c",166      code: '#include <stdio.h>\nint main() {\n    printf("Hello from C!\\n");\n    return 0;\n}\n',167      input: "",168    });169    assert(170      res.body.data.verdict === "OK",171      `Expected OK, got ${res.body.data.verdict}`,172    );173    assert(res.body.data.output.trim() === "Hello from C!", "Output mismatch");174    console.log(175      `    → Time: ${res.body.data.executionTime}ms, Memory: ${res.body.data.memoryUsed}KB`,176    );177  });178 179  await test("C with stdin (factorial)", async () => {180    const code = `#include <stdio.h>181int main() {182    int n;183    scanf("%d", &n);184    long long fact = 1;185    for (int i = 2; i <= n; i++) fact *= i;186    printf("%lld\\n", fact);187    return 0;188}`;189    const res = await request("POST", "/api/execute", {190      language: "c",191      code,192      input: "10\n",193    });194    assert(195      res.body.data.verdict === "OK",196      `Expected OK, got ${res.body.data.verdict}`,197    );198    assert(199      res.body.data.output.trim() === "3628800",200      `Expected 3628800, got ${res.body.data.output.trim()}`,201    );202    console.log(203      `    → Time: ${res.body.data.executionTime}ms, Memory: ${res.body.data.memoryUsed}KB`,204    );205  });206 207  // ─── Python Tests ────────────────────────208  console.log("\n🐍 Python Execution:");209 210  await test("Python Hello World", async () => {211    const res = await request("POST", "/api/execute", {212      language: "python",213      code: 'print("Hello from Python!")\n',214      input: "",215    });216    assert(217      res.body.data.verdict === "OK",218      `Expected OK, got ${res.body.data.verdict}`,219    );220    assert(221      res.body.data.output.trim() === "Hello from Python!",222      "Output mismatch",223    );224    console.log(225      `    → Time: ${res.body.data.executionTime}ms, Memory: ${res.body.data.memoryUsed}KB`,226    );227  });228 229  await test("Python with stdin", async () => {230    const code = `n = int(input())231nums = list(map(int, input().split()))232print(sum(nums))`;233    const res = await request("POST", "/api/execute", {234      language: "python",235      code,236      input: "5\n1 2 3 4 5\n",237    });238    assert(239      res.body.data.verdict === "OK",240      `Expected OK, got ${res.body.data.verdict}`,241    );242    assert(243      res.body.data.output.trim() === "15",244      `Expected 15, got ${res.body.data.output.trim()}`,245    );246    console.log(247      `    → Time: ${res.body.data.executionTime}ms, Memory: ${res.body.data.memoryUsed}KB`,248    );249  });250 251  await test("Python Syntax Error", async () => {252    const res = await request("POST", "/api/execute", {253      language: "python",254      code: 'def foo(\n  print("broken")',255      input: "",256    });257    assert(258      res.body.data.verdict === "CE",259      `Expected CE, got ${res.body.data.verdict}`,260    );261  });262 263  await test("Python Runtime Error (division by zero)", async () => {264    const res = await request("POST", "/api/execute", {265      language: "python",266      code: "print(1 / 0)",267      input: "",268    });269    assert(270      res.body.data.verdict === "RE",271      `Expected RE, got ${res.body.data.verdict}`,272    );273  });274 275  // ─── Judge Tests ─────────────────────────276  console.log("\n⚖️  Judge Mode:");277 278  await test("Judge: All test cases pass (AC)", async () => {279    const code = `#include <bits/stdc++.h>280using namespace std;281int main() {282    int a, b; cin >> a >> b;283    cout << a + b << endl;284    return 0;285}`;286    const res = await request("POST", "/api/judge", {287      language: "cpp",288      code,289      testCases: [290        { input: "1 2\n", expectedOutput: "3" },291        { input: "10 20\n", expectedOutput: "30" },292        { input: "0 0\n", expectedOutput: "0" },293        { input: "-5 5\n", expectedOutput: "0" },294      ],295    });296    assert(297      res.body.data.overallVerdict === "AC",298      `Expected AC, got ${res.body.data.overallVerdict}`,299    );300    assert(301      res.body.data.passed === 4,302      `Expected 4 passed, got ${res.body.data.passed}`,303    );304    console.log(305      `    → Total time: ${res.body.data.totalTime}ms, Max memory: ${res.body.data.maxMemory}KB`,306    );307  });308 309  await test("Judge: Wrong Answer (WA)", async () => {310    const code = `#include <iostream>311using namespace std;312int main() {313    int a, b; cin >> a >> b;314    cout << a - b << endl;  // Bug: subtraction instead of addition315    return 0;316}`;317    const res = await request("POST", "/api/judge", {318      language: "cpp",319      code,320      testCases: [321        { input: "5 3\n", expectedOutput: "8" },322        { input: "0 0\n", expectedOutput: "0" },323      ],324    });325    assert(326      res.body.data.overallVerdict === "WA",327      `Expected WA, got ${res.body.data.overallVerdict}`,328    );329  });330 331  // ─── Validation Tests ────────────────────332  console.log("\n🛡️  Validation:");333 334  await test("Rejects unsupported language", async () => {335    const res = await request("POST", "/api/execute", {336      language: "java",337      code: 'System.out.println("test");',338      input: "",339    });340    assert(res.status === 400, `Expected 400, got ${res.status}`);341  });342 343  await test("Rejects empty code", async () => {344    const res = await request("POST", "/api/execute", {345      language: "python",346      code: "",347      input: "",348    });349    assert(res.status === 400, `Expected 400, got ${res.status}`);350  });351 352  await test("Rejects missing language", async () => {353    const res = await request("POST", "/api/execute", {354      code: 'print("test")',355      input: "",356    });357    assert(res.status === 400, `Expected 400, got ${res.status}`);358  });359 360  console.log("\n═══════════════════════════════════════════════");361  console.log("  Tests complete!");362  console.log("═══════════════════════════════════════════════\n");363}364 365runTests().catch(console.error);366