From 5b3d9861b1657134aee25e6a8256c4280bf0a9cd Mon Sep 17 00:00:00 2001 From: mikemikimike <13286568797@163.com> Date: Thu, 27 Aug 2026 22:59:33 +0800 Subject: [PATCH 1/3] test: use configured API when available Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- typescript/tests/model.test.mjs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/typescript/tests/model.test.mjs b/typescript/tests/model.test.mjs index e7607d2b..8dfac96d 100644 --- a/typescript/tests/model.test.mjs +++ b/typescript/tests/model.test.mjs @@ -699,6 +699,14 @@ describe("createOpenAILanguageModel (Responses API path)", () => { describe("createLanguageModel environment variable routing", () => { after(teardownFetch); + test("calls the configured API when credentials are available", { skip: !process.env.OPENAI_API_KEY || !process.env.OPENAI_MODEL }, async () => { + const model = createLanguageModel(process.env); + const result = await model.complete("Reply with the single word: pong"); + assert.equal(result.success, true, result.message); + assert.equal(typeof result.data, "string"); + assert.notEqual(result.data.trim(), ""); + }); + test("defaults to Chat Completions API", async () => { setupFetch([makeChatCompletionsResponse("OK")]); const model = createLanguageModel({ From f99fef845657abd108500dacef1e31037e174c14 Mon Sep 17 00:00:00 2001 From: mikemikimike <13286568797@163.com> Date: Sat, 29 Aug 2026 08:56:13 +0800 Subject: [PATCH 2/3] test: isolate opt-in live API integration Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- typescript/tests/model.test.mjs | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/typescript/tests/model.test.mjs b/typescript/tests/model.test.mjs index 8dfac96d..e90e11cb 100644 --- a/typescript/tests/model.test.mjs +++ b/typescript/tests/model.test.mjs @@ -105,6 +105,7 @@ function makeErrorResponse(status, statusText, retryAfterSec = null) { let capturedRequests = []; let mockResponses = []; +const nativeFetch = globalThis.fetch; function setupFetch(responses) { capturedRequests = []; @@ -118,7 +119,7 @@ function setupFetch(responses) { } function teardownFetch() { - delete globalThis.fetch; + globalThis.fetch = nativeFetch; capturedRequests = []; mockResponses = []; } @@ -696,16 +697,22 @@ describe("createOpenAILanguageModel (Responses API path)", () => { // createLanguageModel env-var routing // --------------------------------------------------------------------------- -describe("createLanguageModel environment variable routing", () => { - after(teardownFetch); - - test("calls the configured API when credentials are available", { skip: !process.env.OPENAI_API_KEY || !process.env.OPENAI_MODEL }, async () => { +describe("createLanguageModel live API integration", () => { + test("calls the configured API when live tests are explicitly enabled", { + skip: process.env.TYPECHAT_LIVE_TESTS !== "1" || !process.env.OPENAI_API_KEY || !process.env.OPENAI_MODEL, + }, async () => { const model = createLanguageModel(process.env); + model.timeoutMs = 30_000; + model.retryMaxAttempts = 0; const result = await model.complete("Reply with the single word: pong"); assert.equal(result.success, true, result.message); assert.equal(typeof result.data, "string"); assert.notEqual(result.data.trim(), ""); }); +}); + +describe("createLanguageModel environment variable routing", () => { + after(teardownFetch); test("defaults to Chat Completions API", async () => { setupFetch([makeChatCompletionsResponse("OK")]); From 6964be7423804acbfb7ac02a3346beda3d44e0fc Mon Sep 17 00:00:00 2001 From: Robert Gruen Date: Mon, 23 Nov 2026 11:55:26 -0800 Subject: [PATCH 3/3] test: isolate live API smoke tests and verify opt-in behavior Continue the implementation from #430 with process-isolated live tests, explicit configuration failures, offline HTTP regression coverage, and usage documentation. Co-authored-by: mikemikimike <13286568797@163.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- typescript/README.md | 34 ++++ typescript/tests/model-live-runner.test.mjs | 167 ++++++++++++++++++++ typescript/tests/model-live.test.mjs | 17 ++ typescript/tests/model.test.mjs | 14 -- 4 files changed, 218 insertions(+), 14 deletions(-) create mode 100644 typescript/tests/model-live-runner.test.mjs create mode 100644 typescript/tests/model-live.test.mjs diff --git a/typescript/README.md b/typescript/README.md index 07d613ea..1538f41d 100644 --- a/typescript/README.md +++ b/typescript/README.md @@ -79,6 +79,40 @@ for syntax errors and unresolved type references. Node.js CI runs this suite across its Node.js matrix after a clean dependency installation and workspace build. +### Optional live model tests + +Mocked regression tests always run. The separate live API smoke test is skipped +unless `TYPECHAT_LIVE_TESTS` is exactly `1`, even when credentials are available. +Live requests may incur provider charges; do not enable them in ordinary CI. + +Configure either `OPENAI_API_KEY` and `OPENAI_MODEL`, or `AZURE_OPENAI_API_KEY` +and `AZURE_OPENAI_ENDPOINT`. OpenAI configuration takes precedence if both keys +are set. `OPENAI_ENDPOINT` is optional and supports OpenAI-compatible servers; +an endpoint whose path ends in `/responses` selects the Responses API. +Tests read the process environment directly and do not load `.env` files. + +With the desired credentials already configured, enable the live test: + +```sh +TYPECHAT_LIVE_TESTS=1 npm test +``` + +In PowerShell: + +```powershell +$env:TYPECHAT_LIVE_TESTS = "1" +npm test +Remove-Item Env:\TYPECHAT_LIVE_TESTS +``` + +The live suite runs in a separate test process from fetch mocks. It makes one +completion request with a 30-second request timeout, no retries, and a 35-second +test timeout. Missing configuration, request errors, and empty completions fail +the run instead of silently skipping or falling back to mocks. Offline regression +tests exercise this behavior against deterministic loopback HTTP fixtures. + +### Schema validation tests + The TypeScript-backed JSON validator checks its schema and target export before a translator makes its first model request. Schema configuration errors are returned without asking the model to repair them. This preflight uses the same minimal diff --git a/typescript/tests/model-live-runner.test.mjs b/typescript/tests/model-live-runner.test.mjs new file mode 100644 index 00000000..be32be3b --- /dev/null +++ b/typescript/tests/model-live-runner.test.mjs @@ -0,0 +1,167 @@ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { once } from "node:events"; +import { createServer } from "node:http"; +import { test } from "node:test"; +import { fileURLToPath } from "node:url"; + +const liveTestFile = fileURLToPath(new URL("./model-live.test.mjs", import.meta.url)); +const prompt = "Reply with the single word: pong"; +const chatResponse = { choices: [{ message: { role: "assistant", content: "pong" } }] }; + +function liveOpenAIEnv(url) { + return { + TYPECHAT_LIVE_TESTS: "1", + OPENAI_API_KEY: "test-key", + OPENAI_MODEL: "test-model", + OPENAI_ENDPOINT: `${url}/v1/chat/completions`, + }; +} + +async function runLiveTests(variables, ...otherFiles) { + const env = { ...process.env }; + for (const name of Object.keys(env)) { + if (/^(?:OPENAI_|AZURE_OPENAI_)/i.test(name) || + /^(?:TYPECHAT_LIVE_TESTS|NODE_TEST_CONTEXT|NODE_OPTIONS|VSCODE_INSPECTOR_OPTIONS|HTTPS?_PROXY|ALL_PROXY|NO_PROXY)$/i.test(name)) { + delete env[name]; + } + } + Object.assign(env, variables); + const child = spawn(process.execPath, ["--test", "--test-reporter=tap", liveTestFile, ...otherFiles], { + env, + timeout: 45_000, + }); + let stdout = ""; + let stderr = ""; + child.stdout.setEncoding("utf8").on("data", chunk => stdout += chunk); + child.stderr.setEncoding("utf8").on("data", chunk => stderr += chunk); + const [status, signal] = await once(child, "close"); + const output = `${stdout}\n${stderr}`; + assert.equal(signal, null, output); + return { status, output }; +} + +async function serve(t, { status = 200, body = chatResponse, stall = false } = {}) { + const requests = []; + const server = createServer((request, response) => { + const captured = { method: request.method, url: request.url, headers: request.headers, body: "" }; + requests.push(captured); + request.setEncoding("utf8").on("data", chunk => captured.body += chunk); + request.on("end", () => { + if (!stall) { + response.writeHead(status, { "content-type": "application/json" }); + response.end(JSON.stringify(body)); + } + }); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + t.after(() => { + server.closeAllConnections(); + return new Promise((resolve, reject) => { + server.close(error => error ? reject(error) : resolve()); + }); + }); + return { url: `http://127.0.0.1:${server.address().port}`, requests }; +} + +test("live tests stay offline unless TYPECHAT_LIVE_TESTS is exactly 1", async t => { + const { url, requests } = await serve(t); + const configurations = [ + {}, + ...[undefined, "0", "true"].map(flag => ({ ...liveOpenAIEnv(url), TYPECHAT_LIVE_TESTS: flag })), + ]; + for (const variables of configurations) { + const result = await runLiveTests(variables); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /# SKIP Set TYPECHAT_LIVE_TESTS=1/); + } + assert.equal(requests.length, 0); +}); + +for (const [name, variables, message] of [ + ["credentials", {}, /Missing environment variable: OPENAI_API_KEY or AZURE_OPENAI_API_KEY/], + ["OpenAI model", { OPENAI_API_KEY: "test-key" }, /Missing environment variable: OPENAI_MODEL/], + ["Azure endpoint", { AZURE_OPENAI_API_KEY: "test-key" }, /Missing environment variable: AZURE_OPENAI_ENDPOINT/], +]) { + test(`enabled live tests fail visibly for missing ${name}`, async t => { + const { url, requests } = await serve(t); + const result = await runLiveTests({ + TYPECHAT_LIVE_TESTS: "1", + OPENAI_ENDPOINT: `${url}/v1/chat/completions`, + ...variables, + }); + assert.equal(result.status, 1, result.output); + assert.match(result.output, message); + assert.equal(requests.length, 0); + }); +} + +for (const api of ["chat", "responses", "azure"]) { + test(`enabled live tests call the configured ${api} API through native fetch`, async t => { + const body = api === "responses" + ? { output: [{ type: "message", content: [{ type: "output_text", text: "pong" }] }] } + : chatResponse; + const { url, requests } = await serve(t, { body }); + const path = api === "azure" ? "/openai/deployments/test/chat/completions?api-version=test" + : api === "responses" ? "/v1/responses" : "/v1/chat/completions"; + const variables = api === "azure" + ? { TYPECHAT_LIVE_TESTS: "1", AZURE_OPENAI_API_KEY: "test-key", AZURE_OPENAI_ENDPOINT: `${url}${path}` } + : { ...liveOpenAIEnv(url), OPENAI_ENDPOINT: `${url}${path}` }; + const result = await runLiveTests(variables); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /^# pass 1$/m); + assert.equal(requests.length, 1); + assert.equal(requests[0].method, "POST"); + assert.equal(requests[0].url, path); + const request = JSON.parse(requests[0].body); + if (api === "responses") { + assert.equal(request.input, prompt); + } else { + assert.deepEqual(request.messages, [{ role: "user", content: prompt }]); + } + assert.equal(request.model, api === "azure" ? undefined : "test-model"); + }); +} + +test("live and mocked suites remain isolated when run together", async t => { + const { url, requests } = await serve(t); + const result = await runLiveTests( + liveOpenAIEnv(url), + fileURLToPath(new URL("./model.test.mjs", import.meta.url)), + ); + assert.equal(result.status, 0, result.output); + assert.match(result.output, /token-provider authentication/); + assert.match(result.output, /createLanguageModel live API integration/); + assert.equal(requests.length, 1); +}); + +for (const status of [401, 503]) { + test(`live HTTP ${status} errors fail without retries or mock fallback`, async t => { + const { url, requests } = await serve(t, { status, body: { error: { message: "test failure" } } }); + const result = await runLiveTests(liveOpenAIEnv(url)); + assert.equal(result.status, 1, result.output); + assert.match(result.output, new RegExp(`REST API error ${status}:`)); + assert.equal(requests.length, 1); + }); +} + +for (const content of ["", " \n"]) { + test(`live tests reject blank completion ${JSON.stringify(content)}`, async t => { + const { url, requests } = await serve(t, { body: { choices: [{ message: { content } }] } }); + const result = await runLiveTests(liveOpenAIEnv(url)); + assert.equal(result.status, 1, result.output); + assert.equal(requests.length, 1); + }); +} + +test("live requests time out after 30 seconds without retrying", { timeout: 40_000 }, async t => { + const { url, requests } = await serve(t, { stall: true }); + const started = performance.now(); + const result = await runLiveTests(liveOpenAIEnv(url)); + const elapsed = performance.now() - started; + assert.equal(result.status, 1, result.output); + assert.match(result.output, /REST API fetch error:.*(?:timeout|timed out)/i); + assert.equal(requests.length, 1); + assert.ok(elapsed >= 29_000 && elapsed < 35_000, `Expected a 30-second request limit, observed ${elapsed}ms`); +}); diff --git a/typescript/tests/model-live.test.mjs b/typescript/tests/model-live.test.mjs new file mode 100644 index 00000000..8d98bf71 --- /dev/null +++ b/typescript/tests/model-live.test.mjs @@ -0,0 +1,17 @@ +import assert from "node:assert/strict"; +import { describe, test } from "node:test"; +import { createLanguageModel } from "../dist/index.js"; + +describe("createLanguageModel live API integration", { + skip: process.env.TYPECHAT_LIVE_TESTS === "1" ? false : "Set TYPECHAT_LIVE_TESTS=1 to enable live API requests.", +}, () => { + test("calls the configured API when live tests are explicitly enabled", { timeout: 35_000 }, async () => { + const model = createLanguageModel(process.env); + model.timeoutMs = 30_000; + model.retryMaxAttempts = 0; + const result = await model.complete("Reply with the single word: pong"); + assert.equal(result.success, true, result.message); + assert.equal(typeof result.data, "string"); + assert.notEqual(result.data.trim(), ""); + }); +}); diff --git a/typescript/tests/model.test.mjs b/typescript/tests/model.test.mjs index e90e11cb..b840737b 100644 --- a/typescript/tests/model.test.mjs +++ b/typescript/tests/model.test.mjs @@ -697,20 +697,6 @@ describe("createOpenAILanguageModel (Responses API path)", () => { // createLanguageModel env-var routing // --------------------------------------------------------------------------- -describe("createLanguageModel live API integration", () => { - test("calls the configured API when live tests are explicitly enabled", { - skip: process.env.TYPECHAT_LIVE_TESTS !== "1" || !process.env.OPENAI_API_KEY || !process.env.OPENAI_MODEL, - }, async () => { - const model = createLanguageModel(process.env); - model.timeoutMs = 30_000; - model.retryMaxAttempts = 0; - const result = await model.complete("Reply with the single word: pong"); - assert.equal(result.success, true, result.message); - assert.equal(typeof result.data, "string"); - assert.notEqual(result.data.trim(), ""); - }); -}); - describe("createLanguageModel environment variable routing", () => { after(teardownFetch);