openai.test.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import { expect, test } from "bun:test"
  2. import { DEFAULT_BASE_URL, PATH } from "@opencode-ai/ai/protocols/openai-chat"
  3. import { Effect, Stream } from "effect"
  4. import { HttpClientRequest } from "effect/unstable/http"
  5. import { HttpClientError } from "effect/unstable/http/HttpClientError"
  6. import { SimulationOpenAI } from "../src/backend/openai"
  7. import { SimulatedProvider } from "../src/backend/simulated-provider"
  8. test("encodes every simulated provider event as OpenAI SSE", async () => {
  9. const provider: SimulatedProvider.Interface = {
  10. stream: () =>
  11. Stream.make(
  12. { type: "textDelta", text: "Hello " },
  13. { type: "textDelta", text: "from Drive" },
  14. { type: "finish", reason: "stop" },
  15. ),
  16. }
  17. const url = new URL(DEFAULT_BASE_URL + PATH)
  18. const request = HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe({ model: "gpt-5" }))
  19. const matched = SimulationOpenAI.route(provider).match(request, url)
  20. if (!matched) throw new Error("The simulated OpenAI route did not match")
  21. const body = await Effect.runPromise(matched.pipe(Effect.flatMap((response) => response.text)))
  22. expect(body).toBe(
  23. [
  24. 'data: {"choices":[{"delta":{"content":"Hello "}}]}',
  25. 'data: {"choices":[{"delta":{"content":"from Drive"}}]}',
  26. 'data: {"choices":[{"delta":{},"finish_reason":"stop"}]}',
  27. "data: [DONE]",
  28. "",
  29. ].join("\n\n"),
  30. )
  31. })
  32. test("rejects malformed intercepted OpenAI JSON as an HTTP client error", async () => {
  33. const provider: SimulatedProvider.Interface = { stream: () => Stream.empty }
  34. const url = new URL(DEFAULT_BASE_URL + PATH)
  35. const request = HttpClientRequest.post(url).pipe(HttpClientRequest.bodyText("{"))
  36. const matched = SimulationOpenAI.route(provider).match(request, url)
  37. if (!matched) throw new Error("The simulated OpenAI route did not match")
  38. const error = await Effect.runPromise(matched.pipe(Effect.flip))
  39. expect(error).toBeInstanceOf(HttpClientError)
  40. expect(error.reason._tag).toBe("TransportError")
  41. })