Files
promptfoo--promptfoo/test/providers/openai/completion.test.ts
T
wehub-resource-sync 0d3cb498a3
CI / Shell Format Check (push) Has been cancelled
CI / Check Ruby (3.4) (push) Has been cancelled
CI / CI Config (push) Has been cancelled
CI / Test on Node ${{ matrix.node }} and ${{ matrix.os }}${{ matrix.shard && format(' (shard {0}/3)', matrix.shard) || '' }} (push) Has been cancelled
CI / Build on Node ${{ matrix.node }} (push) Has been cancelled
CI / Style Check (push) Has been cancelled
CI / Generate Assets (push) Has been cancelled
CI / Check Python (3.14) (push) Has been cancelled
CI / Check Python (3.9) (push) Has been cancelled
CI / Build Docs (push) Has been cancelled
CI / Code Scan Action (push) Has been cancelled
CI / Site tests (push) Has been cancelled
CI / webui tests (push) Has been cancelled
CI / Run Integration Tests (push) Has been cancelled
CI / Run Smoke Tests (push) Has been cancelled
CI / Go Tests (push) Has been cancelled
CI / Share Test (push) Has been cancelled
CI / Redteam (Production API) (push) Has been cancelled
CI / Redteam (Staging API) (push) Has been cancelled
CI / GitHub Actions Lint (push) Has been cancelled
CI / Check Ruby (3.0) (push) Has been cancelled
release-please / release-please (push) Has been cancelled
release-please / build (push) Has been cancelled
release-please / publish-npm (push) Has been cancelled
release-please / publish-npm-backfill (push) Has been cancelled
release-please / docker (push) Has been cancelled
release-please / publish-code-scan-action (push) Has been cancelled
release-please / attest-code-scan-action (push) Has been cancelled
Deploy local.promptfoo.app / Deploy to Cloudflare Pages (push) Has been cancelled
Test and Publish Multi-arch Docker Image / test (push) Has been cancelled
Test and Publish Multi-arch Docker Image / build-docker-and-push-digests (map[digest-suffix:linux-amd64 platform:linux/amd64 runner:ubuntu-latest]) (push) Has been cancelled
Test and Publish Multi-arch Docker Image / build-docker-and-push-digests (map[digest-suffix:linux-arm64 platform:linux/arm64 runner:ubuntu-24.04-arm]) (push) Has been cancelled
Test and Publish Multi-arch Docker Image / merge-docker-digests (push) Has been cancelled
Test and Publish Multi-arch Docker Image / Attest Multi-arch Image (push) Has been cancelled
Validate Renovate Config / Validate Renovate Configuration (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 13:24:08 +08:00

256 lines
7.8 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { disableCache, enableCache, fetchWithCache } from '../../../src/cache';
import logger from '../../../src/logger';
import { OpenAiCompletionProvider } from '../../../src/providers/openai/completion';
import { mockProcessEnv } from '../../util/utils';
import { getOpenAiMissingApiKeyMessage, restoreEnvVar } from './shared';
vi.mock('../../../src/cache');
vi.mock('../../../src/logger');
const mockFetchWithCache = vi.mocked(fetchWithCache);
describe('OpenAI Provider', () => {
beforeEach(() => {
vi.resetAllMocks();
disableCache();
// Set a default API key for tests unless explicitly testing missing key
mockProcessEnv({ OPENAI_API_KEY: 'test-api-key' });
});
afterEach(() => {
enableCache();
});
describe('OpenAiCompletionProvider', () => {
const mockResponse = {
data: {
choices: [{ text: 'Test output' }],
usage: { total_tokens: 10, prompt_tokens: 5, completion_tokens: 5 },
},
cached: false,
status: 200,
statusText: 'OK',
severity: 'info',
};
it('should call API successfully with text completion', async () => {
mockFetchWithCache.mockResolvedValue(mockResponse);
const provider = new OpenAiCompletionProvider('text-davinci-003');
const result = await provider.callApi('Test prompt');
expect(mockFetchWithCache).toHaveBeenCalledTimes(1);
expect(result.output).toBe('Test output');
expect(result.tokenUsage).toEqual({ total: 10, prompt: 5, completion: 5, numRequests: 1 });
});
it('should handle API errors', async () => {
mockFetchWithCache.mockResolvedValue({
data: {
error: {
message: 'Test error',
type: 'test_error',
},
},
cached: false,
status: 400,
statusText: 'Bad Request',
});
const provider = new OpenAiCompletionProvider('text-davinci-003');
const result = await provider.callApi('Test prompt');
expect(result.error).toBeDefined();
expect(result.error).toContain('Test error');
});
it('should handle fetch errors', async () => {
mockFetchWithCache.mockRejectedValue(new Error('Network error'));
const provider = new OpenAiCompletionProvider('text-davinci-003');
const result = await provider.callApi('Test prompt');
expect(result.error).toBeDefined();
expect(result.error).toContain('Network error');
});
it('should handle missing API key', async () => {
// Save the original env var and clear it for this test
const originalApiKey = process.env.OPENAI_API_KEY;
mockProcessEnv({ OPENAI_API_KEY: undefined });
try {
const provider = new OpenAiCompletionProvider('text-davinci-003', {
config: {
apiKeyRequired: true,
},
env: {
OPENAI_API_KEY: undefined,
},
});
await expect(provider.callApi('Test prompt')).rejects.toThrow(
getOpenAiMissingApiKeyMessage(),
);
} finally {
restoreEnvVar('OPENAI_API_KEY', originalApiKey);
}
});
it('should use custom apiKeyEnvar in missing API key errors', async () => {
const originalApiKey = process.env.OPENAI_API_KEY;
const originalCustomApiKey = process.env.CUSTOM_OPENAI_KEY;
mockProcessEnv({ OPENAI_API_KEY: undefined });
mockProcessEnv({ CUSTOM_OPENAI_KEY: undefined });
try {
const provider = new OpenAiCompletionProvider('text-davinci-003', {
config: {
apiKeyEnvar: 'CUSTOM_OPENAI_KEY',
},
env: {
OPENAI_API_KEY: undefined,
CUSTOM_OPENAI_KEY: undefined,
},
});
await expect(provider.callApi('Test prompt')).rejects.toThrow(
getOpenAiMissingApiKeyMessage('CUSTOM_OPENAI_KEY'),
);
} finally {
restoreEnvVar('OPENAI_API_KEY', originalApiKey);
restoreEnvVar('CUSTOM_OPENAI_KEY', originalCustomApiKey);
}
});
it('should warn about unknown model', () => {
const warnSpy = vi.spyOn(logger, 'warn');
new OpenAiCompletionProvider('unknown-model');
expect(warnSpy).toHaveBeenCalledWith(
'FYI: Using unknown OpenAI completion model: unknown-model',
);
warnSpy.mockRestore();
});
it('should handle cached responses', async () => {
mockFetchWithCache.mockResolvedValue({
...mockResponse,
cached: true,
});
const provider = new OpenAiCompletionProvider('text-davinci-003');
const result = await provider.callApi('Test prompt');
expect(result.cached).toBe(true);
expect(result.output).toBe('Test output');
});
it('should handle responses without usage information', async () => {
mockFetchWithCache.mockResolvedValue({
data: {
choices: [{ text: 'Test output' }],
},
cached: false,
status: 200,
statusText: 'OK',
});
const provider = new OpenAiCompletionProvider('text-davinci-003');
const result = await provider.callApi('Test prompt');
expect(result.output).toBe('Test output');
expect(result.tokenUsage).toEqual({});
});
it('should handle fetchWithCache returning undefined response', async () => {
mockFetchWithCache.mockResolvedValue(undefined as any);
const provider = new OpenAiCompletionProvider('text-davinci-003');
const result = await provider.callApi('Test prompt');
expect(mockFetchWithCache).toHaveBeenCalledTimes(1);
expect(result.error).toContain('Cannot destructure property');
});
it('should pass custom headers from config', async () => {
mockFetchWithCache.mockResolvedValue(mockResponse);
const customHeaders = {
'X-Test-Header': 'test-value',
};
const provider = new OpenAiCompletionProvider('text-davinci-003', {
config: {
headers: customHeaders,
},
});
await provider.callApi('Test prompt');
expect(mockFetchWithCache).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
headers: expect.objectContaining({
'Content-Type': 'application/json',
'X-OpenAI-Originator': 'promptfoo',
'X-Test-Header': 'test-value',
}),
}),
expect.any(Number),
'json',
undefined,
undefined,
);
});
it('should pass passthrough config fields in body', async () => {
mockFetchWithCache.mockResolvedValue(mockResponse);
const provider = new OpenAiCompletionProvider('text-davinci-003', {
config: {
passthrough: { logprobs: 3 },
},
});
await provider.callApi('Test prompt');
const actualCall = mockFetchWithCache.mock.calls[0];
const body = JSON.parse(actualCall[1]?.body as string);
expect(body.logprobs).toBe(3);
});
it('should handle response parsing errors', async () => {
mockFetchWithCache.mockResolvedValue({
data: {}, // Missing choices array
cached: false,
status: 200,
statusText: 'OK',
});
const provider = new OpenAiCompletionProvider('text-davinci-003');
const result = await provider.callApi('Test prompt');
expect(result.error).toMatch(/API error:/);
});
it('should handle invalid OPENAI_STOP env var', async () => {
mockProcessEnv({ OPENAI_STOP: '{invalid json}' });
const provider = new OpenAiCompletionProvider('text-davinci-003', {
config: {
apiKey: 'test-api-key',
},
});
await expect(provider.callApi('test')).rejects.toThrow(
/OPENAI_STOP is not a valid JSON string/,
);
mockProcessEnv({ OPENAI_STOP: undefined });
});
});
});