Files
ruflo/tests/test.utils.ts
T
rUvandClaude fd295cda16 🚀 Release: Claude Flow v2.0.0-alpha.62
## 🔒 Security Fixes
- CRITICAL: Removed vulnerable pkg dependency (GHSA-22r3-9w55-cj54)
- Replaced with secure @vercel/ncc alternative
- Security score improved from 55/100 to 75/100
- All npm audit vulnerabilities resolved (0 vulnerabilities)

## 🚀 Infrastructure Improvements
- Re-enabled ALL CI/CD security gates with strict enforcement
- Fixed Jest configuration and test infrastructure
- Fixed 18 TypeScript test files with import issues
- Created comprehensive test utilities

## 🛠️ Code Quality
- Fixed 145 ESLint errors (16% reduction)
- Fixed 15 critical TypeScript errors
- Added development tooling configs

## 📚 Documentation
- Created security audit report
- Created fix summary documentation
- Created functionality review
- Updated GitHub issue #362

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-07-18 13:35:41 +00:00

284 lines
6.2 KiB
TypeScript

import { jest } from '@jest/globals';
// Mock logger utilities
export const mockLogger = {
info: jest.fn(),
error: jest.fn(),
warn: jest.fn(),
debug: jest.fn(),
trace: jest.fn()
};
// Mock coordination system utilities
export const mockCoordinationSystem = {
initialize: jest.fn(),
shutdown: jest.fn(),
getStatus: jest.fn(),
addAgent: jest.fn(),
removeAgent: jest.fn(),
orchestrateTask: jest.fn()
};
// Mock memory backend utilities
export const mockMemoryBackend = {
store: jest.fn(),
retrieve: jest.fn(),
delete: jest.fn(),
list: jest.fn(),
clear: jest.fn()
};
// Mock orchestrator utilities
export const mockOrchestrator = {
start: jest.fn(),
stop: jest.fn(),
executeTask: jest.fn(),
getAgents: jest.fn(),
getTaskStatus: jest.fn()
};
// Test helper functions
export const createMockAgent = (id: string, type: string = 'test') => ({
id,
type,
capabilities: ['test'],
status: 'idle',
execute: jest.fn(),
initialize: jest.fn(),
shutdown: jest.fn()
});
export const createMockTask = (id: string, description: string) => ({
id,
description,
status: 'pending',
priority: 'medium',
createdAt: new Date(),
updatedAt: new Date()
});
// Async test utilities
export const waitFor = (ms: number) => new Promise(resolve => setTimeout(resolve, ms));
export const waitForCondition = async (
condition: () => boolean,
timeout: number = 5000,
interval: number = 100
): Promise<void> => {
const startTime = Date.now();
while (!condition()) {
if (Date.now() - startTime > timeout) {
throw new Error('Condition not met within timeout');
}
await waitFor(interval);
}
};
// Environment setup utilities
export const setupTestEnvironment = () => {
// Reset all mocks
jest.clearAllMocks();
// Set test environment variables
process.env.NODE_ENV = 'test';
process.env.LOG_LEVEL = 'error';
return {
logger: mockLogger,
coordinationSystem: mockCoordinationSystem,
memoryBackend: mockMemoryBackend,
orchestrator: mockOrchestrator
};
};
export const teardownTestEnvironment = () => {
jest.clearAllMocks();
// Clean up environment variables
delete process.env.LOG_LEVEL;
};
// Re-export commonly used test utilities
export { jest } from '@jest/globals';
export { describe, it, test, beforeEach, afterEach, beforeAll, afterAll, expect } from '@jest/globals';
// Export assertion utilities
export const assert = (condition: boolean, message?: string) => {
if (!condition) {
throw new Error(message || 'Assertion failed');
}
};
export const assertEquals = (actual: any, expected: any, message?: string) => {
expect(actual).toEqual(expected);
};
export const assertExists = (value: any, message?: string) => {
expect(value).toBeDefined();
expect(value).not.toBeNull();
};
export const assertRejects = async (fn: () => Promise<any>, errorType?: any) => {
if (errorType) {
await expect(fn()).rejects.toThrow(errorType);
} else {
await expect(fn()).rejects.toThrow();
}
};
export const assertThrows = (fn: () => any, errorType?: any) => {
if (errorType) {
expect(fn).toThrow(errorType);
} else {
expect(fn).toThrow();
}
};
// Export assertion utilities for spies
export const assertSpyCalls = (spyFn: any, expectedCalls: number) => {
expect(spyFn).toHaveBeenCalledTimes(expectedCalls);
};
// Export FakeTime for timer mocking
export class FakeTime {
constructor() {
jest.useFakeTimers();
}
install() {
jest.useFakeTimers();
}
restore() {
jest.useRealTimers();
}
uninstall() {
jest.useRealTimers();
}
tick(ms: number) {
jest.advanceTimersByTime(ms);
}
async tickAsync(ms: number) {
await jest.advanceTimersByTimeAsync(ms);
}
runAll() {
jest.runAllTimers();
}
runPending() {
jest.runOnlyPendingTimers();
}
}
// Additional spy utilities with sinon-like API
export const spy = (obj?: any, method?: string) => {
if (obj && method) {
return jest.spyOn(obj, method);
}
// Return a standalone spy function
const spyFn = jest.fn();
(spyFn as any).calls = {
get length() { return spyFn.mock.calls.length; },
get count() { return spyFn.mock.calls.length; }
};
return spyFn;
};
export const stub = () => {
const stubFn = jest.fn();
(stubFn as any).calls = {
get length() { return stubFn.mock.calls.length; },
get count() { return stubFn.mock.calls.length; }
};
return stubFn;
};
// Additional testing utilities
export function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Test data builder utilities
export class TestDataBuilder {
static createTestAgent(overrides?: any) {
return {
id: 'test-agent-1',
name: 'Test Agent',
type: 'test',
status: 'active',
...overrides
};
}
static createTestTask(overrides?: any) {
return {
id: 'test-task-1',
description: 'Test task description',
status: 'pending',
priority: 'medium',
...overrides
};
}
static createTestMemory(overrides?: any) {
return {
id: 'test-memory-1',
key: 'test-key',
value: { data: 'test data' },
metadata: {
created: new Date().toISOString(),
updated: new Date().toISOString()
},
...overrides
};
}
static config() {
return {
orchestrator: {
maxConcurrentAgents: 10,
taskQueueSize: 100,
healthCheckInterval: 10000,
sessionRetentionMs: 3600000
},
coordination: {
deadlockDetection: false,
maxTaskRetries: 3
},
memory: {
defaultBackend: 'memory',
maxCacheSize: 1000
}
};
}
static agentProfile(overrides?: any) {
return {
id: 'test-agent-' + Math.random().toString(36).substr(2, 9),
name: 'Test Agent',
type: 'test',
capabilities: ['test'],
maxConcurrentTasks: 5,
priority: 5,
...overrides
};
}
static task(overrides?: any) {
return {
id: 'test-task-' + Math.random().toString(36).substr(2, 9),
type: 'test',
description: 'Test task',
priority: 50,
status: 'pending',
dependencies: [],
metadata: {},
...overrides
};
}
}