|
| 1 | +import { expect, test, vi } from 'vitest' |
| 2 | +import { withEnv } from '#tests/with-env.ts' |
| 3 | + |
| 4 | +vi.mock('#app/utils/cache.server.ts', () => ({ |
| 5 | + cache: { |
| 6 | + name: 'test-cache', |
| 7 | + get: () => null, |
| 8 | + set: async () => {}, |
| 9 | + delete: async () => {}, |
| 10 | + }, |
| 11 | + cachified: async ({ |
| 12 | + getFreshValue, |
| 13 | + }: { |
| 14 | + getFreshValue: () => Promise<unknown> |
| 15 | + }) => getFreshValue(), |
| 16 | +})) |
| 17 | + |
| 18 | +vi.mock('#app/utils/semantic-search-presentation.server.ts', () => ({ |
| 19 | + getSemanticSearchPresentation: async () => ({}), |
| 20 | +})) |
| 21 | + |
| 22 | +import { semanticSearchKCD } from '../semantic-search.server.ts' |
| 23 | + |
| 24 | +test('semanticSearchKCD routes user query embeddings through CLOUDFLARE_AI_GATEWAY_ID', async () => { |
| 25 | + await withEnv( |
| 26 | + { |
| 27 | + CLOUDFLARE_AI_GATEWAY_ID: 'runtime-search-gateway', |
| 28 | + CLOUDFLARE_AI_EMBEDDING_GATEWAY_ID: 'indexing-only-gateway', |
| 29 | + }, |
| 30 | + async () => { |
| 31 | + const fetchSpy = vi |
| 32 | + .spyOn(globalThis, 'fetch') |
| 33 | + .mockImplementation(async (input) => { |
| 34 | + const url = input instanceof Request ? input.url : String(input) |
| 35 | + |
| 36 | + if (url.includes('/workers-ai/')) { |
| 37 | + return new Response( |
| 38 | + JSON.stringify({ |
| 39 | + result: { |
| 40 | + shape: [1, 3], |
| 41 | + data: [[0.1, 0.2, 0.3]], |
| 42 | + }, |
| 43 | + }), |
| 44 | + { |
| 45 | + status: 200, |
| 46 | + headers: { 'Content-Type': 'application/json' }, |
| 47 | + }, |
| 48 | + ) |
| 49 | + } |
| 50 | + |
| 51 | + if (url.includes('/vectorize/')) { |
| 52 | + return new Response( |
| 53 | + JSON.stringify({ result: { count: 0, matches: [] } }), |
| 54 | + { |
| 55 | + status: 200, |
| 56 | + headers: { 'Content-Type': 'application/json' }, |
| 57 | + }, |
| 58 | + ) |
| 59 | + } |
| 60 | + |
| 61 | + throw new Error(`Unexpected fetch URL in semantic search test: ${url}`) |
| 62 | + }) |
| 63 | + |
| 64 | + try { |
| 65 | + await semanticSearchKCD({ |
| 66 | + query: `Gateway regression test ${Date.now()}`, |
| 67 | + topK: 1, |
| 68 | + }) |
| 69 | + |
| 70 | + const embeddingRequestUrl = fetchSpy.mock.calls |
| 71 | + .map(([input]) => (input instanceof Request ? input.url : String(input))) |
| 72 | + .find((url) => url.includes('/workers-ai/')) |
| 73 | + |
| 74 | + expect(embeddingRequestUrl).toBeDefined() |
| 75 | + expect(embeddingRequestUrl).toContain('/runtime-search-gateway/') |
| 76 | + expect(embeddingRequestUrl).not.toContain('/indexing-only-gateway/') |
| 77 | + } finally { |
| 78 | + fetchSpy.mockRestore() |
| 79 | + } |
| 80 | + }, |
| 81 | + ) |
| 82 | +}) |
0 commit comments