Files
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

190 lines
5.7 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { matchesModeration } from '../../src/matchers/moderation';
import { OpenAiModerationProvider } from '../../src/providers/openai/moderation';
import { ReplicateModerationProvider } from '../../src/providers/replicate';
import { LLAMA_GUARD_REPLICATE_PROVIDER } from '../../src/redteam/constants';
import { mockProcessEnv } from '../util/utils';
describe('matchesModeration', () => {
const mockModerationResponse = {
flags: [],
tokenUsage: { total: 5, prompt: 2, completion: 3 },
};
const normalizedTokenUsage = {
total: 5,
prompt: 2,
completion: 3,
cached: 0,
numRequests: 0,
completionDetails: {
reasoning: 0,
acceptedPrediction: 0,
rejectedPrediction: 0,
},
};
let restoreProcessEnv = () => {};
function setTestEnv(overrides: Record<string, string | undefined> = {}) {
restoreProcessEnv();
restoreProcessEnv = mockProcessEnv({
OPENAI_API_KEY: undefined,
REPLICATE_API_KEY: undefined,
REPLICATE_API_TOKEN: undefined,
...overrides,
});
}
beforeEach(() => {
setTestEnv();
});
afterEach(() => {
vi.restoreAllMocks();
restoreProcessEnv();
restoreProcessEnv = () => {};
});
it('should skip moderation when assistant response is empty', async () => {
const openAiSpy = vi
.spyOn(OpenAiModerationProvider.prototype, 'callModerationApi')
.mockResolvedValue(mockModerationResponse);
const result = await matchesModeration({
userPrompt: 'test prompt',
assistantResponse: '',
});
expect(result).toEqual({
pass: true,
score: 1,
reason: expect.any(String),
});
expect(openAiSpy).not.toHaveBeenCalled();
});
it('should use OpenAI when OPENAI_API_KEY is present', async () => {
setTestEnv({ OPENAI_API_KEY: 'test-key' });
const openAiSpy = vi
.spyOn(OpenAiModerationProvider.prototype, 'callModerationApi')
.mockResolvedValue(mockModerationResponse);
await matchesModeration({
userPrompt: 'test prompt',
assistantResponse: 'test response',
});
expect(openAiSpy).toHaveBeenCalledWith('test prompt', 'test response');
});
it('should propagate token usage returned by moderation provider', async () => {
setTestEnv({ OPENAI_API_KEY: 'test-key' });
vi.spyOn(OpenAiModerationProvider.prototype, 'callModerationApi').mockResolvedValue(
mockModerationResponse,
);
const result = await matchesModeration({
userPrompt: 'test prompt',
assistantResponse: 'test response',
});
expect(result.tokensUsed).toEqual(normalizedTokenUsage);
});
it('should fall back to Replicate when only REPLICATE_API_KEY is present', async () => {
setTestEnv({ REPLICATE_API_KEY: 'test-key' });
const replicateSpy = vi
.spyOn(ReplicateModerationProvider.prototype, 'callModerationApi')
.mockResolvedValue(mockModerationResponse);
await matchesModeration({
userPrompt: 'test prompt',
assistantResponse: 'test response',
});
expect(replicateSpy).toHaveBeenCalledWith('test prompt', 'test response');
});
it('should respect provider override in grading config', async () => {
setTestEnv({ OPENAI_API_KEY: 'test-key' });
const replicateSpy = vi
.spyOn(ReplicateModerationProvider.prototype, 'callModerationApi')
.mockResolvedValue(mockModerationResponse);
await matchesModeration(
{
userPrompt: 'test prompt',
assistantResponse: 'test response',
},
{
provider: LLAMA_GUARD_REPLICATE_PROVIDER,
},
);
expect(replicateSpy).toHaveBeenCalledWith('test prompt', 'test response');
});
it('should fail when the moderation API returns an error', async () => {
setTestEnv({ OPENAI_API_KEY: 'test-key' });
vi.spyOn(OpenAiModerationProvider.prototype, 'callModerationApi').mockResolvedValue({
error: 'provider unavailable',
tokenUsage: mockModerationResponse.tokenUsage,
});
await expect(
matchesModeration({
userPrompt: 'test prompt',
assistantResponse: 'test response',
}),
).resolves.toEqual({
pass: false,
score: 0,
reason: 'Moderation API error: provider unavailable',
tokensUsed: normalizedTokenUsage,
// Tagged so inverse-aware callers (not-moderation) don't flip a transport
// error into a spurious pass.
metadata: { graderError: true },
});
});
it('should fail when moderation flags match the requested categories', async () => {
setTestEnv({ OPENAI_API_KEY: 'test-key' });
vi.spyOn(OpenAiModerationProvider.prototype, 'callModerationApi').mockResolvedValue({
flags: [
{ code: 'violence', description: 'Violence', confidence: 1 },
{ code: 'hate', description: 'Hate', confidence: 1 },
],
});
await expect(
matchesModeration({
userPrompt: 'test prompt',
assistantResponse: 'test response',
categories: ['hate'],
}),
).resolves.toEqual({
pass: false,
score: 0,
reason: 'Moderation flags detected: Hate',
});
});
it('should pass when flags do not match the requested categories', async () => {
setTestEnv({ OPENAI_API_KEY: 'test-key' });
vi.spyOn(OpenAiModerationProvider.prototype, 'callModerationApi').mockResolvedValue({
flags: [{ code: 'violence', description: 'Violence', confidence: 1 }],
});
await expect(
matchesModeration({
userPrompt: 'test prompt',
assistantResponse: 'test response',
categories: ['hate'],
}),
).resolves.toEqual({
pass: true,
score: 1,
reason: 'No relevant moderation flags detected',
});
});
});