Files
wehub-resource-sync 23f7624596
ADR-166 MCP Bridge Security Lock / Static-source security lock (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / Compose default binds loopback + Mongo has auth (push) Failing after 2s
CodeQL Advanced / Analyze (rust) (push) Failing after 0s
ADR-166 MCP Bridge Security Lock / plugin-agent-federation bindHost default (push) Failing after 1s
ADR-166 MCP Bridge Security Lock / Runtime behavior — 401 + terminal gate + fail-closed (push) Failing after 4s
business-pods-smoke / smoke (push) Failing after 1s
all-plugins-smoke / smoke-all (push) Failing after 2s
CI/CD Pipeline / Security & Code Quality (push) Failing after 1s
CI/CD Pipeline / Test Suite (ubuntu-latest) (push) Failing after 1s
CI/CD Pipeline / Build & Package (macos-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (ubuntu-latest) (push) Has been skipped
CI/CD Pipeline / Build & Package (windows-latest) (push) Has been skipped
CI/CD Pipeline / Documentation & Examples (push) Failing after 1s
Clone Tracker (14-day rolling) / Snapshot clones for ruflo ecosystem (push) Failing after 1s
CodeQL Advanced / Analyze (actions) (push) Failing after 1s
CodeQL Advanced / Analyze (javascript-typescript) (push) Failing after 1s
federation-peer-rust / stable-noop (push) Failing after 1s
metaharness-ci / score (push) Failing after 1s
metaharness-ci / router-compat (push) Failing after 0s
metaharness-ci / similarity-tests (push) Failing after 0s
no-agentbbs-smoke / smoke-without-agentbbs (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (windows-latest) (push) Has been skipped
codex-integration-audit / Codex integration audit (push) Failing after 1s
helpers-manifest-guard / guard (push) Failing after 1s
🔗 Cross-Agent Integration Tests / 🤝 Agent Coordination Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🧠 Memory Sharing Integration (push) Has been skipped
🔗 Cross-Agent Integration Tests / 🛡️ Fault Tolerance Tests (push) Has been skipped
🔗 Cross-Agent Integration Tests / ⚡ Performance Integration Tests (push) Has been skipped
metaharness-ci / mcp-scan (push) Failing after 1s
metaharness-ci / eject-dryrun (push) Failing after 1s
metaharness-ci / metaharness-real-data (push) Failing after 0s
no-cli-optdep-bloat-2561 / guard (push) Failing after 1s
no-metaharness-smoke / smoke-without-metaharness (push) Failing after 1s
no-phantom-agentic-flow-subpath / guard (push) Failing after 1s
🔄 Automated Rollback Manager / 🚨 Failure Detection (push) Failing after 1s
V3 CI/CD Pipeline / Plugin hooks smoke / ubuntu-latest / Node 22 (push) Failing after 1s
V3 CI/CD Pipeline / ruflo-graph-intelligence build + test smoke (#2044, ADR-123) (push) Failing after 1s
CVE Audit Gate / Audit root (critical-blocking) (push) Failing after 2s
cost-tracker-smoke / smoke (push) Failing after 3s
oia-audit-weekly / audit (push) Failing after 2s
ruflo-agent-smoke / ruflo-agent structural smoke (push) Failing after 1s
📊 Status Badges Update / 📊 Update Status Badges (push) Failing after 1s
V3 CI/CD Pipeline / Static regression guards (#2267 YAML + (push) Failing after 1s
V3 CI/CD Pipeline / Test V3 Packages (push) Failing after 0s
V3 CI/CD Pipeline / agent_execute provider routing smoke (#2042) (push) Failing after 0s
CVE Audit Gate / Audit v3 (critical-blocking) (push) Failing after 1s
federation-peer-rust / stable-native (push) Failing after 2s
🔗 Cross-Agent Integration Tests / 🚀 Integration Test Setup (push) Failing after 2s
neural-trader-smoke / runtime-smoke (push) Failing after 1s
V3 CI/CD Pipeline / Build V3 (macos-latest) (push) Has been skipped
V3 CI/CD Pipeline / Build V3 (ubuntu-latest) (push) Has been skipped
V3 CI/CD Pipeline / Type Check V3 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 24 (push) Failing after 1s
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / ubuntu-latest / Node 22 (push) Failing after 2s
V3 CI/CD Pipeline / browser rvf create flag smoke (#2015) (push) Failing after 0s
V3 CI/CD Pipeline / Dependency review (#2046) (push) Has been skipped
V3 CI/CD Pipeline / Supply-chain audit (#2046) (push) Failing after 0s
V3 CI/CD Pipeline / witness marker drift smoke (#2021) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader portfolio CG smoke (#2068, ADR-126 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / neural-trader backtest signing smoke (#2068, ADR-126 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / kg-extract type-import classification smoke (#2049) (push) Failing after 0s
V3 CI/CD Pipeline / witness verify precondition smoke (#1880) (push) Failing after 2s
V3 CI/CD Pipeline / neural-trader pipeline risk-gate smoke (#2068, ADR-126 Phase 5) (push) Failing after 0s
V3 CI/CD Pipeline / neural-trader feature attribution smoke (#2068, ADR-126 Phase 6) (push) Failing after 0s
V3 CI/CD Pipeline / plugin-registry signature verification smoke (#1922, CWE-347) (push) Failing after 4s
V3 CI/CD Pipeline / memory stats legacy-DB smoke (#2120) (push) Failing after 4s
V3 CI/CD Pipeline / github deprecated actions smoke (#2089, ADR-127 Phase 3) (push) Failing after 1s
V3 CI/CD Pipeline / graph query + pathfinder smoke (ADR-130 P2+P5) (push) Has been skipped
V3 CI/CD Pipeline / graph trajectory hooks smoke (ADR-130 P3) (push) Has been skipped
V3 CI/CD Pipeline / graph plugin adapter smoke (ADR-130 P4) (push) Has been skipped
V3 CI/CD Pipeline / graph benchmark (ADR-130 P6) (push) Has been skipped
V3 CI/CD Pipeline / statusline generator delegation smoke (#2195) (push) Failing after 1s
V3 CI/CD Pipeline / wizard init regression guard (#2206 (push) Failing after 1s
V3 CI/CD Pipeline / memory no-stray-db smoke (ADR-125 P7) (push) Failing after 1s
V3 CI/CD Pipeline / github-safe injection smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github actions pin smoke (#2089, ADR-127 Phase 1) (push) Failing after 1s
V3 CI/CD Pipeline / github attribution opt-in smoke (#2089, ADR-127 Phase 4) (push) Failing after 1s
V3 CI/CD Pipeline / pre-bash hook safety smoke (#2017) (push) Failing after 1s
V3 CI/CD Pipeline / Memory import smoke / ubuntu-latest (push) Failing after 0s
V3 CI/CD Pipeline / MCP protocol smoke / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / ruvllm WASM auto-init smoke (#2086) (push) Failing after 4s
V3 CI/CD Pipeline / MCP paired-tool round-trip smoke (#1889) (push) Failing after 1s
V3 CI/CD Pipeline / Plugin package install-safety (#1902/#1903/#1904) (push) Failing after 1s
V3 CI/CD Pipeline / Tool description discoverability (ADR-112) (push) Failing after 3s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (22) (push) Failing after 1s
V3 CI/CD Pipeline / CLI npx-install smoke (#1147 / (24) (push) Failing after 1s
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / ubuntu-latest (push) Failing after 2s
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / ubuntu-latest (push) Failing after 1s
V3 CI/CD Pipeline / Vector-index dimension audit (#1947) (push) Failing after 0s
V3 CI/CD Pipeline / Hook-command install safety (#1921) (push) Failing after 1s
V3 CI/CD Pipeline / ToolOutputGuardrail smoke (ADR-131, (push) Failing after 1s
V3 CI/CD Pipeline / init-bundle invariants smoke (#2095, ADR-128 Phase 5) (push) Failing after 1s
V3 CI/CD Pipeline / wasm provider bridge smoke (ADR-129 P1) (push) Failing after 2s
V3 CI/CD Pipeline / wasm gallery CRUD smoke (ADR-129 P3) (push) Failing after 1s
V3 CI/CD Pipeline / wasm plugin bridge smoke (ADR-129 P4) (push) Failing after 0s
V3 CI/CD Pipeline / wasm compose smoke (ADR-129 P2) (push) Failing after 4s
V3 CI/CD Pipeline / graph schema smoke (ADR-130 P1) (push) Failing after 0s
Validate Marketplace / validate (push) Failing after 1s
🔍 Verification Pipeline / 🚀 Setup Verification (push) Failing after 1s
🔍 Verification Pipeline / 🛡️ Security Verification (push) Has been skipped
🔍 Verification Pipeline / 📝 Code Quality (push) Has been skipped
🔍 Verification Pipeline / 🧪 Test Verification (${{ matrix.os }}, Node ${{ matrix.node }}) (push) Has been skipped
🔍 Verification Pipeline / 🏗️ Build Verification (push) Has been skipped
🔍 Verification Pipeline / 📚 Documentation Verification (push) Has been skipped
CVE Audit Gate / High-severity report (warn only) (push) Has been cancelled
🔄 Automated Rollback Manager / 🔄 Execute Rollback (push) Has been cancelled
🔄 Automated Rollback Manager / ✅ Post-Rollback Verification (push) Has been cancelled
🔄 Automated Rollback Manager / 📊 Rollback Monitoring (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook execution smoke (#2132) / windows-latest (push) Has been cancelled
🔄 Automated Rollback Manager / ⏳ Manual Rollback Approval (push) Has been cancelled
V3 CI/CD Pipeline / MCP protocol smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Memory import smoke / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows hook shim smoke (#2132) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Windows init hooks smoke (#2132) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / macos-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / ubuntu-latest (push) Has been cancelled
V3 CI/CD Pipeline / Witness verify (signed manifest) / windows-latest (push) Has been cancelled
V3 CI/CD Pipeline / Publish to npm (alpha) (push) Has been cancelled
V3 CI/CD Pipeline / Smoke (no better-sqlite3) / macos-latest / Node 22 (push) Has been cancelled
V3 CI/CD Pipeline / Plugin hooks smoke / macos-latest / Node 22 (push) Has been cancelled
CI/CD Pipeline / Deploy & Release (push) Has been cancelled
CI/CD Pipeline / CI Status (push) Has been cancelled
🔗 Cross-Agent Integration Tests / 📊 Integration Test Report (push) Has been cancelled
🔄 Automated Rollback Manager / 🔍 Pre-Rollback Validation (push) Has been cancelled
🔍 Verification Pipeline / ⚡ Performance Verification (push) Has been cancelled
🔍 Verification Pipeline / 📊 Verification Report (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:02:19 +08:00

470 lines
15 KiB
TypeScript

/**
* Mock Factory Utilities for Security Module Testing
*
* Provides type-safe mock creation utilities for testing security components.
* Uses vitest's mocking capabilities with full TypeScript support.
*
* @module v3/security/__tests__/helpers/create-mock
*/
import { vi, type MockInstance } from 'vitest';
/**
* Type representing a mocked interface where all methods are vi.fn() mocks
*/
export type MockedInterface<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer R
? MockInstance<(...args: A) => R>
: T[K];
};
/**
* Type for a deeply mocked interface (including nested objects)
*/
export type DeepMockedInterface<T> = {
[K in keyof T]: T[K] extends (...args: infer A) => infer R
? MockInstance<(...args: A) => R>
: T[K] extends object
? DeepMockedInterface<T[K]>
: T[K];
};
/**
* Creates a type-safe mock object for an interface.
* All methods are replaced with vi.fn() mocks.
*
* @example
* ```typescript
* interface IService {
* getData(): Promise<string>;
* process(input: number): boolean;
* }
*
* const mock = createMock<IService>();
* mock.getData.mockResolvedValue('test');
* mock.process.mockReturnValue(true);
* ```
*
* @returns A proxy-based mock object
*/
export function createMock<T extends object>(): MockedInterface<T> {
const cache = new Map<string | symbol, MockInstance>();
return new Proxy({} as MockedInterface<T>, {
get(target, prop) {
if (!cache.has(prop)) {
cache.set(prop, vi.fn());
}
return cache.get(prop);
},
});
}
/**
* Creates a partial mock with some real implementations.
*
* @param overrides - Partial implementation to use
* @returns A mock object with the provided overrides
*
* @example
* ```typescript
* const mock = createPartialMock<IService>({
* getData: vi.fn().mockResolvedValue('real'),
* });
* ```
*/
export function createPartialMock<T extends object>(
overrides: Partial<MockedInterface<T>> = {}
): MockedInterface<T> {
const baseMock = createMock<T>();
return { ...baseMock, ...overrides };
}
/**
* Creates a spy on an existing object's methods.
*
* @param obj - The object to spy on
* @param methods - Array of method names to spy on
* @returns The object with spied methods
*
* @example
* ```typescript
* const service = new RealService();
* const spied = createSpy(service, ['getData', 'process']);
* ```
*/
export function createSpy<T extends object, K extends keyof T>(
obj: T,
methods: K[]
): T & { [P in K]: MockInstance } {
const spiedObj = { ...obj } as T & { [P in K]: MockInstance };
for (const method of methods) {
if (typeof obj[method] === 'function') {
(spiedObj as Record<K, MockInstance>)[method] = vi.fn(
(obj[method] as Function).bind(obj)
);
}
}
return spiedObj;
}
/**
* Mock factory for PasswordHasher
*/
export interface MockPasswordHasher {
hash: MockInstance<(password: string) => Promise<string>>;
verify: MockInstance<(password: string, hash: string) => Promise<boolean>>;
validate: MockInstance<(password: string) => { isValid: boolean; errors: string[] }>;
needsRehash: MockInstance<(hash: string) => boolean>;
getConfig: MockInstance<() => Record<string, unknown>>;
}
export function createMockPasswordHasher(
overrides: Partial<MockPasswordHasher> = {}
): MockPasswordHasher {
return {
hash: vi.fn().mockResolvedValue('$2b$12$mockedHashValue'),
verify: vi.fn().mockResolvedValue(true),
validate: vi.fn().mockReturnValue({ isValid: true, errors: [] }),
needsRehash: vi.fn().mockReturnValue(false),
getConfig: vi.fn().mockReturnValue({ rounds: 12 }),
...overrides,
};
}
/**
* Mock factory for CredentialGenerator
*/
export interface MockCredentialGenerator {
generatePassword: MockInstance<(length?: number) => string>;
generateApiKey: MockInstance<(prefix?: string) => { key: string; prefix: string; keyId: string; createdAt: Date }>;
generateSecret: MockInstance<(length?: number) => string>;
generateEncryptionKey: MockInstance<() => string>;
generateInstallationCredentials: MockInstance<(expirationDays?: number) => {
adminPassword: string;
servicePassword: string;
jwtSecret: string;
sessionSecret: string;
encryptionKey: string;
generatedAt: Date;
expiresAt?: Date;
}>;
generateSessionToken: MockInstance<() => string>;
generateCsrfToken: MockInstance<() => string>;
generateNonce: MockInstance<() => string>;
}
export function createMockCredentialGenerator(
overrides: Partial<MockCredentialGenerator> = {}
): MockCredentialGenerator {
const now = new Date();
return {
generatePassword: vi.fn().mockReturnValue('MockedSecureP@ssword123!'),
generateApiKey: vi.fn().mockReturnValue({
key: 'cf_mockedApiKey12345',
prefix: 'cf_',
keyId: '550e8400-e29b-41d4-a716-446655440000',
createdAt: now,
}),
generateSecret: vi.fn().mockReturnValue('0'.repeat(64)),
generateEncryptionKey: vi.fn().mockReturnValue('a'.repeat(64)),
generateInstallationCredentials: vi.fn().mockReturnValue({
adminPassword: 'MockedAdminP@ss123!',
servicePassword: 'MockedServiceP@ss123!',
jwtSecret: '0'.repeat(64),
sessionSecret: '1'.repeat(64),
encryptionKey: 'a'.repeat(64),
generatedAt: now,
}),
generateSessionToken: vi.fn().mockReturnValue('mockedSessionToken'),
generateCsrfToken: vi.fn().mockReturnValue('mockedCsrfToken'),
generateNonce: vi.fn().mockReturnValue('0'.repeat(32)),
...overrides,
};
}
/**
* Mock factory for PathValidator
*/
export interface MockPathValidator {
validate: MockInstance<(path: string) => Promise<{
isValid: boolean;
resolvedPath: string;
relativePath: string;
matchedPrefix: string;
errors: string[];
}>>;
validateSync: MockInstance<(path: string) => {
isValid: boolean;
resolvedPath: string;
relativePath: string;
matchedPrefix: string;
errors: string[];
}>;
validateOrThrow: MockInstance<(path: string) => Promise<string>>;
securePath: MockInstance<(prefix: string, ...segments: string[]) => Promise<string>>;
isWithinAllowed: MockInstance<(path: string) => boolean>;
getAllowedPrefixes: MockInstance<() => readonly string[]>;
}
export function createMockPathValidator(
overrides: Partial<MockPathValidator> = {}
): MockPathValidator {
return {
validate: vi.fn().mockResolvedValue({
isValid: true,
resolvedPath: '/workspaces/project/src/file.ts',
relativePath: 'src/file.ts',
matchedPrefix: '/workspaces/project',
errors: [],
}),
validateSync: vi.fn().mockReturnValue({
isValid: true,
resolvedPath: '/workspaces/project/src/file.ts',
relativePath: 'src/file.ts',
matchedPrefix: '/workspaces/project',
errors: [],
}),
validateOrThrow: vi.fn().mockResolvedValue('/workspaces/project/src/file.ts'),
securePath: vi.fn().mockResolvedValue('/workspaces/project/src/file.ts'),
isWithinAllowed: vi.fn().mockReturnValue(true),
getAllowedPrefixes: vi.fn().mockReturnValue(['/workspaces/project']),
...overrides,
};
}
/**
* Mock factory for SafeExecutor
*/
export interface MockSafeExecutor {
execute: MockInstance<(command: string, args?: string[]) => Promise<{
stdout: string;
stderr: string;
exitCode: number;
command: string;
args: string[];
duration: number;
}>>;
executeStreaming: MockInstance<(command: string, args?: string[]) => {
process: unknown;
stdout: unknown;
stderr: unknown;
promise: Promise<unknown>;
}>;
sanitizeArgument: MockInstance<(arg: string) => string>;
isCommandAllowed: MockInstance<(command: string) => boolean>;
allowCommand: MockInstance<(command: string) => void>;
getAllowedCommands: MockInstance<() => readonly string[]>;
}
export function createMockSafeExecutor(
overrides: Partial<MockSafeExecutor> = {}
): MockSafeExecutor {
return {
execute: vi.fn().mockResolvedValue({
stdout: 'success',
stderr: '',
exitCode: 0,
command: 'echo',
args: ['hello'],
duration: 10,
}),
executeStreaming: vi.fn().mockReturnValue({
process: {},
stdout: null,
stderr: null,
promise: Promise.resolve({
stdout: 'success',
stderr: '',
exitCode: 0,
command: 'echo',
args: ['hello'],
duration: 10,
}),
}),
sanitizeArgument: vi.fn().mockImplementation((arg: string) => arg.replace(/[;&|]/g, '')),
isCommandAllowed: vi.fn().mockReturnValue(true),
allowCommand: vi.fn(),
getAllowedCommands: vi.fn().mockReturnValue(['echo', 'git', 'npm', 'node']),
...overrides,
};
}
/**
* Mock factory for TokenGenerator
*/
export interface MockTokenGenerator {
generate: MockInstance<(length?: number) => string>;
generateWithExpiration: MockInstance<(expirationSeconds?: number, metadata?: Record<string, unknown>) => {
value: string;
createdAt: Date;
expiresAt: Date;
metadata?: Record<string, unknown>;
}>;
generateSessionToken: MockInstance<() => { value: string; createdAt: Date; expiresAt: Date }>;
generateCsrfToken: MockInstance<() => { value: string; createdAt: Date; expiresAt: Date }>;
generateApiToken: MockInstance<(prefix?: string) => { value: string; createdAt: Date; expiresAt: Date }>;
generateVerificationCode: MockInstance<(length?: number, expirationMinutes?: number, maxAttempts?: number) => {
code: string;
createdAt: Date;
expiresAt: Date;
attempts: number;
maxAttempts: number;
}>;
generateSignedToken: MockInstance<(payload: Record<string, unknown>, expirationSeconds?: number) => {
token: string;
signature: string;
combined: string;
createdAt: Date;
expiresAt: Date;
}>;
verifySignedToken: MockInstance<(combined: string) => Record<string, unknown> | null>;
generateTokenPair: MockInstance<() => {
accessToken: { value: string; createdAt: Date; expiresAt: Date };
refreshToken: { value: string; createdAt: Date; expiresAt: Date };
}>;
isExpired: MockInstance<(token: { expiresAt: Date }) => boolean>;
compare: MockInstance<(a: string, b: string) => boolean>;
}
export function createMockTokenGenerator(
overrides: Partial<MockTokenGenerator> = {}
): MockTokenGenerator {
const now = new Date();
const expires = new Date(now.getTime() + 3600000);
return {
generate: vi.fn().mockReturnValue('mockedToken12345'),
generateWithExpiration: vi.fn().mockReturnValue({
value: 'mockedTokenWithExpiration',
createdAt: now,
expiresAt: expires,
}),
generateSessionToken: vi.fn().mockReturnValue({
value: 'mockedSessionToken',
createdAt: now,
expiresAt: expires,
}),
generateCsrfToken: vi.fn().mockReturnValue({
value: 'mockedCsrfToken',
createdAt: now,
expiresAt: expires,
}),
generateApiToken: vi.fn().mockReturnValue({
value: 'cf_mockedApiToken',
createdAt: now,
expiresAt: expires,
}),
generateVerificationCode: vi.fn().mockReturnValue({
code: '123456',
createdAt: now,
expiresAt: expires,
attempts: 0,
maxAttempts: 3,
}),
generateSignedToken: vi.fn().mockReturnValue({
token: 'mockedToken',
signature: 'mockedSignature',
combined: 'mockedToken.mockedSignature',
createdAt: now,
expiresAt: expires,
}),
verifySignedToken: vi.fn().mockReturnValue({ userId: '123' }),
generateTokenPair: vi.fn().mockReturnValue({
accessToken: { value: 'accessToken', createdAt: now, expiresAt: expires },
refreshToken: { value: 'refreshToken', createdAt: now, expiresAt: new Date(now.getTime() + 604800000) },
}),
isExpired: vi.fn().mockReturnValue(false),
compare: vi.fn().mockImplementation((a: string, b: string) => a === b),
...overrides,
};
}
/**
* Mock factory for InputValidator
*/
export interface MockInputValidator {
validateEmail: MockInstance<(email: string) => string>;
validatePassword: MockInstance<(password: string) => string>;
validateIdentifier: MockInstance<(id: string) => string>;
validatePath: MockInstance<(path: string) => string>;
validateCommandArg: MockInstance<(arg: string) => string>;
validateLoginRequest: MockInstance<(data: unknown) => { email: string; password: string; mfaCode?: string }>;
validateCreateUser: MockInstance<(data: unknown) => { email: string; password: string; role: string }>;
validateTaskInput: MockInstance<(data: unknown) => { taskId: string; content: string; agentType: string }>;
}
export function createMockInputValidator(
overrides: Partial<MockInputValidator> = {}
): MockInputValidator {
return {
validateEmail: vi.fn().mockImplementation((email: string) => email.toLowerCase()),
validatePassword: vi.fn().mockImplementation((password: string) => password),
validateIdentifier: vi.fn().mockImplementation((id: string) => id),
validatePath: vi.fn().mockImplementation((path: string) => path),
validateCommandArg: vi.fn().mockImplementation((arg: string) => arg),
validateLoginRequest: vi.fn().mockImplementation((data: unknown) => data as { email: string; password: string }),
validateCreateUser: vi.fn().mockImplementation((data: unknown) => data as { email: string; password: string; role: string }),
validateTaskInput: vi.fn().mockImplementation((data: unknown) => data as { taskId: string; content: string; agentType: string }),
...overrides,
};
}
/**
* Resets all mocks in a mock object
*/
export function resetMock<T extends object>(mock: MockedInterface<T>): void {
for (const key of Object.keys(mock)) {
const value = (mock as Record<string, unknown>)[key];
if (typeof value === 'function' && 'mockReset' in value) {
(value as MockInstance).mockReset();
}
}
}
/**
* Clears all mocks in a mock object (keeps implementation)
*/
export function clearMock<T extends object>(mock: MockedInterface<T>): void {
for (const key of Object.keys(mock)) {
const value = (mock as Record<string, unknown>)[key];
if (typeof value === 'function' && 'mockClear' in value) {
(value as MockInstance).mockClear();
}
}
}
/**
* Restores all mocks in a mock object
*/
export function restoreMock<T extends object>(mock: MockedInterface<T>): void {
for (const key of Object.keys(mock)) {
const value = (mock as Record<string, unknown>)[key];
if (typeof value === 'function' && 'mockRestore' in value) {
(value as MockInstance).mockRestore();
}
}
}
/**
* Helper to verify mock was called with specific arguments
*/
export function expectCalledWith<T extends MockInstance>(
mock: T,
...args: Parameters<T extends MockInstance<infer F> ? F : never>
): void {
expect(mock).toHaveBeenCalledWith(...args);
}
/**
* Helper to verify mock was called exactly N times
*/
export function expectCalledTimes<T extends MockInstance>(
mock: T,
times: number
): void {
expect(mock).toHaveBeenCalledTimes(times);
}