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
548 lines
13 KiB
Markdown
548 lines
13 KiB
Markdown
# @claude-flow/testing
|
|
|
|
[](https://www.npmjs.com/package/@claude-flow/testing)
|
|
[](https://www.npmjs.com/package/@claude-flow/testing)
|
|
[](https://opensource.org/licenses/MIT)
|
|
[](https://www.typescriptlang.org/)
|
|
[](https://github.com/ruvnet/claude-flow)
|
|
[](https://vitest.dev/)
|
|
|
|
> Comprehensive testing framework for V3 Claude-Flow modules. Implements London School TDD patterns with behavior verification, shared fixtures, and mock services.
|
|
|
|
Based on ADR-008 (Vitest over Jest).
|
|
|
|
## Installation
|
|
|
|
```bash
|
|
npm install @claude-flow/testing vitest --save-dev
|
|
```
|
|
|
|
## Quick Start
|
|
|
|
```typescript
|
|
import {
|
|
setupV3Tests,
|
|
createMockApplication,
|
|
agentConfigs,
|
|
swarmConfigs,
|
|
waitFor,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Configure test environment
|
|
setupV3Tests();
|
|
|
|
describe('MyModule', () => {
|
|
const app = createMockApplication();
|
|
|
|
beforeEach(() => {
|
|
// Mocks are automatically reset
|
|
});
|
|
|
|
it('should spawn an agent', async () => {
|
|
const result = await app.agentLifecycle.spawn(agentConfigs.queenCoordinator);
|
|
|
|
expect(result.success).toBe(true);
|
|
expect(result.agent.type).toBe('queen-coordinator');
|
|
});
|
|
});
|
|
```
|
|
|
|
## Directory Structure
|
|
|
|
```
|
|
src/
|
|
├── fixtures/ # Pre-defined test data
|
|
│ ├── agent-fixtures.ts # Mock agents, configs
|
|
│ ├── memory-fixtures.ts # Memory entries, backends
|
|
│ ├── swarm-fixtures.ts # Swarm configs, topologies
|
|
│ └── mcp-fixtures.ts # MCP tools, contexts
|
|
├── helpers/ # Test utilities
|
|
│ ├── test-utils.ts # waitFor, retry, timeout
|
|
│ ├── mock-factory.ts # Factory functions for mocks
|
|
│ ├── assertion-helpers.ts # Custom Vitest matchers
|
|
│ └── setup-teardown.ts # Global setup/teardown
|
|
├── mocks/ # Mock service implementations
|
|
│ ├── mock-services.ts # AgentDB, SwarmCoordinator, etc.
|
|
│ └── mock-mcp-client.ts # MCP client for CLI testing
|
|
├── setup.ts # Global test configuration
|
|
└── index.ts # Main exports
|
|
```
|
|
|
|
## Fixtures
|
|
|
|
### Agent Fixtures
|
|
|
|
```typescript
|
|
import {
|
|
agentConfigs,
|
|
agentInstances,
|
|
createAgentConfig,
|
|
createAgentInstance,
|
|
createV3SwarmAgentConfigs,
|
|
createMockAgent,
|
|
createMockV3Swarm,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Pre-defined configs
|
|
const queen = agentConfigs.queenCoordinator;
|
|
const coder = agentConfigs.coder;
|
|
|
|
// Create with overrides
|
|
const customAgent = createAgentConfig('coder', {
|
|
name: 'Custom Coder',
|
|
priority: 90,
|
|
});
|
|
|
|
// Full V3 15-agent swarm
|
|
const swarmConfigs = createV3SwarmAgentConfigs();
|
|
|
|
// Mock agents with vitest mocks
|
|
const mockAgent = createMockAgent('security-architect');
|
|
mockAgent.execute.mockResolvedValue({ success: true });
|
|
```
|
|
|
|
### Memory Fixtures
|
|
|
|
```typescript
|
|
import {
|
|
memoryEntries,
|
|
searchResults,
|
|
learnedPatterns,
|
|
hnswConfigs,
|
|
memoryBackendConfigs,
|
|
createMemoryEntry,
|
|
createVectorQuery,
|
|
generateMockEmbedding,
|
|
createMemoryBatch,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Pre-defined entries
|
|
const pattern = memoryEntries.agentPattern;
|
|
const securityRule = memoryEntries.securityRule;
|
|
|
|
// Create with overrides
|
|
const entry = createMemoryEntry('agentPattern', {
|
|
key: 'custom:pattern:001',
|
|
});
|
|
|
|
// Generate embeddings
|
|
const embedding = generateMockEmbedding(384, 'my-seed');
|
|
|
|
// Create batch for performance testing
|
|
const batch = createMemoryBatch(10000, 'semantic');
|
|
```
|
|
|
|
### Swarm Fixtures
|
|
|
|
```typescript
|
|
import {
|
|
swarmConfigs,
|
|
swarmStates,
|
|
swarmTasks,
|
|
swarmMessages,
|
|
coordinationResults,
|
|
createSwarmConfig,
|
|
createSwarmTask,
|
|
createSwarmMessage,
|
|
createConsensusRequest,
|
|
createMockSwarmCoordinator,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Pre-defined configs
|
|
const v3Config = swarmConfigs.v3Default;
|
|
const minimalConfig = swarmConfigs.minimal;
|
|
|
|
// Create with overrides
|
|
const customConfig = createSwarmConfig('v3Default', {
|
|
maxAgents: 20,
|
|
coordination: {
|
|
consensusProtocol: 'pbft',
|
|
heartbeatInterval: 500,
|
|
electionTimeout: 3000,
|
|
},
|
|
});
|
|
|
|
// Mock coordinator
|
|
const coordinator = createMockSwarmCoordinator();
|
|
await coordinator.initialize(v3Config);
|
|
```
|
|
|
|
### MCP Fixtures
|
|
|
|
```typescript
|
|
import {
|
|
mcpTools,
|
|
mcpResources,
|
|
mcpPrompts,
|
|
mcpServerConfigs,
|
|
mcpToolResults,
|
|
mcpErrors,
|
|
createMCPTool,
|
|
createMCPRequest,
|
|
createMCPResponse,
|
|
createMockMCPClient,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Pre-defined tools
|
|
const swarmInit = mcpTools.swarmInit;
|
|
const agentSpawn = mcpTools.agentSpawn;
|
|
|
|
// Mock client
|
|
const client = createMockMCPClient();
|
|
await client.connect();
|
|
const result = await client.callTool('swarm_init', { topology: 'mesh' });
|
|
```
|
|
|
|
## Test Utilities
|
|
|
|
### Async Utilities
|
|
|
|
```typescript
|
|
import {
|
|
waitFor,
|
|
waitUntilChanged,
|
|
retry,
|
|
withTimeout,
|
|
sleep,
|
|
parallelLimit,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Wait for condition
|
|
await waitFor(() => element.isVisible(), { timeout: 5000 });
|
|
|
|
// Wait for value to change
|
|
await waitUntilChanged(() => counter.value, { from: 0 });
|
|
|
|
// Retry with exponential backoff
|
|
const result = await retry(
|
|
async () => await fetchData(),
|
|
{ maxAttempts: 3, backoff: 100 }
|
|
);
|
|
|
|
// Timeout wrapper
|
|
await withTimeout(async () => await longOp(), 5000);
|
|
|
|
// Parallel with concurrency limit
|
|
const results = await parallelLimit(
|
|
items.map(item => () => processItem(item)),
|
|
5 // max 5 concurrent
|
|
);
|
|
```
|
|
|
|
### Time Control
|
|
|
|
```typescript
|
|
import { createMockClock, measureTime } from '@claude-flow/testing';
|
|
|
|
// Mock clock for time-dependent tests
|
|
const clock = createMockClock();
|
|
clock.install();
|
|
clock.tick(1000); // Advance by 1 second
|
|
clock.uninstall();
|
|
|
|
// Measure execution time
|
|
const { result, duration } = await measureTime(async () => {
|
|
return await expensiveOperation();
|
|
});
|
|
```
|
|
|
|
### Event Emitter
|
|
|
|
```typescript
|
|
import { createTestEmitter } from '@claude-flow/testing';
|
|
|
|
const emitter = createTestEmitter<{ message: string; count: number }>();
|
|
|
|
const handler = vi.fn();
|
|
emitter.on('message', handler);
|
|
emitter.emit('message', 'hello');
|
|
|
|
expect(handler).toHaveBeenCalledWith('hello');
|
|
```
|
|
|
|
## Mock Factory
|
|
|
|
### Application Mocks
|
|
|
|
```typescript
|
|
import {
|
|
createMockApplication,
|
|
createMockEventBus,
|
|
createMockTaskManager,
|
|
createMockAgentLifecycle,
|
|
createMockMemoryService,
|
|
createMockSecurityService,
|
|
createMockSwarmCoordinator,
|
|
createMockLogger,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Full application with all mocks
|
|
const app = createMockApplication();
|
|
|
|
// Individual service mocks
|
|
const eventBus = createMockEventBus();
|
|
const taskManager = createMockTaskManager();
|
|
const security = createMockSecurityService();
|
|
|
|
// Use in tests
|
|
await app.taskManager.create({ name: 'Test', type: 'coding', payload: {} });
|
|
expect(app.taskManager.create).toHaveBeenCalled();
|
|
|
|
// Access tracked state
|
|
expect(app.eventBus.publishedEvents).toHaveLength(1);
|
|
expect(app.taskManager.tasks.size).toBe(1);
|
|
```
|
|
|
|
## Mock Services
|
|
|
|
### MockAgentDB
|
|
|
|
```typescript
|
|
import { MockAgentDB } from '@claude-flow/testing';
|
|
|
|
const db = new MockAgentDB();
|
|
|
|
// Insert vectors
|
|
await db.insert('vec-1', embedding, { type: 'pattern' });
|
|
|
|
// Search
|
|
const results = await db.search(queryEmbedding, 10, 0.7);
|
|
|
|
// Verify calls
|
|
expect(db.insert).toHaveBeenCalledWith('vec-1', expect.any(Array), expect.any(Object));
|
|
```
|
|
|
|
### MockSwarmCoordinator
|
|
|
|
```typescript
|
|
import { MockSwarmCoordinator } from '@claude-flow/testing';
|
|
|
|
const coordinator = new MockSwarmCoordinator();
|
|
|
|
await coordinator.initialize({ topology: 'hierarchical-mesh' });
|
|
await coordinator.addAgent({ type: 'coder', name: 'Coder-1' });
|
|
const result = await coordinator.coordinate({ id: 'task-1', type: 'coding', payload: {} });
|
|
|
|
expect(coordinator.getState().agentCount).toBe(1);
|
|
expect(result.success).toBe(true);
|
|
```
|
|
|
|
### MockMCPClient
|
|
|
|
```typescript
|
|
import { MockMCPClient, createStandardMockMCPClient } from '@claude-flow/testing';
|
|
|
|
// Standard client with common tools
|
|
const client = createStandardMockMCPClient();
|
|
await client.connect();
|
|
|
|
// Custom tool handlers
|
|
client.setToolHandler('swarm_init', async (params) => ({
|
|
content: [{ type: 'text', text: JSON.stringify({ swarmId: 'test' }) }],
|
|
}));
|
|
|
|
const result = await client.callTool('swarm_init', { topology: 'mesh' });
|
|
|
|
// Verify request history
|
|
expect(client.getRequestHistory()).toHaveLength(1);
|
|
expect(client.getLastRequest()?.method).toBe('tools/call');
|
|
```
|
|
|
|
## Assertions
|
|
|
|
### Standard Assertions
|
|
|
|
```typescript
|
|
import {
|
|
assertEventPublished,
|
|
assertEventOrder,
|
|
assertMocksCalledInOrder,
|
|
assertV3PerformanceTargets,
|
|
assertValidStateTransition,
|
|
assertNoSensitiveData,
|
|
} from '@claude-flow/testing';
|
|
|
|
// Event assertions
|
|
assertEventPublished(mockEventBus, 'UserCreated', { userId: '123' });
|
|
assertEventOrder(mockEventBus.publish, ['UserCreated', 'EmailSent']);
|
|
|
|
// Mock order
|
|
assertMocksCalledInOrder([mockValidate, mockSave, mockNotify]);
|
|
|
|
// Performance targets
|
|
assertV3PerformanceTargets({
|
|
searchSpeedup: 160,
|
|
flashAttentionSpeedup: 3.5,
|
|
memoryReduction: 0.55,
|
|
});
|
|
|
|
// State transitions
|
|
assertValidStateTransition('pending', 'running', {
|
|
pending: ['running', 'cancelled'],
|
|
running: ['completed', 'failed'],
|
|
});
|
|
|
|
// Security
|
|
assertNoSensitiveData(mockLogger.logs, ['password', 'token', 'secret']);
|
|
```
|
|
|
|
### Custom Vitest Matchers
|
|
|
|
```typescript
|
|
import { registerCustomMatchers } from '@claude-flow/testing';
|
|
|
|
// Register in setup
|
|
registerCustomMatchers();
|
|
|
|
// Use in tests
|
|
expect(mockFn).toHaveBeenCalledWithPattern({ userId: expect.any(String) });
|
|
expect(event).toHaveEventType('UserCreated');
|
|
expect(metrics).toMeetV3PerformanceTargets();
|
|
```
|
|
|
|
## Setup & Teardown
|
|
|
|
### Global Test Setup
|
|
|
|
```typescript
|
|
import { setupV3Tests, configureTestEnvironment } from '@claude-flow/testing';
|
|
|
|
// Simple setup
|
|
setupV3Tests();
|
|
|
|
// Custom configuration
|
|
configureTestEnvironment({
|
|
resetMocks: true,
|
|
fakeTimers: true,
|
|
suppressConsole: ['log', 'warn'],
|
|
env: {
|
|
NODE_ENV: 'test',
|
|
DEBUG: 'false',
|
|
},
|
|
});
|
|
```
|
|
|
|
### Test Context
|
|
|
|
```typescript
|
|
import { createSetupContext, createTestScope } from '@claude-flow/testing';
|
|
|
|
// Setup context with cleanup
|
|
const ctx = createSetupContext();
|
|
ctx.addCleanup(() => server.close());
|
|
ctx.registerResource(database);
|
|
// ... run tests
|
|
await ctx.runCleanup();
|
|
|
|
// Isolated test scope
|
|
const scope = createTestScope();
|
|
scope.addMock(mockService);
|
|
await scope.run(async () => {
|
|
// test code - mocks auto-cleared after
|
|
});
|
|
```
|
|
|
|
### Performance Testing
|
|
|
|
```typescript
|
|
import { createPerformanceTestHelper } from '@claude-flow/testing';
|
|
|
|
const perf = createPerformanceTestHelper();
|
|
|
|
perf.startMeasurement('search');
|
|
await search(query);
|
|
const duration = perf.endMeasurement('search');
|
|
|
|
// Get statistics
|
|
const stats = perf.getStats('search');
|
|
console.log(`Avg: ${stats.avg}ms, P95: ${stats.p95}ms`);
|
|
```
|
|
|
|
## Performance Targets
|
|
|
|
The testing framework includes assertions for V3 performance targets:
|
|
|
|
| Metric | Target |
|
|
|--------|--------|
|
|
| Search Speedup | 150x - 12,500x |
|
|
| Flash Attention Speedup | 2.49x - 7.47x |
|
|
| Memory Reduction | >= 50% |
|
|
| Startup Time | < 500ms |
|
|
| Response Time | < 100ms |
|
|
|
|
```typescript
|
|
import { assertV3PerformanceTargets, TEST_CONFIG } from '@claude-flow/testing';
|
|
|
|
// Assert targets
|
|
assertV3PerformanceTargets({
|
|
searchSpeedup: 160,
|
|
flashAttentionSpeedup: 3.5,
|
|
memoryReduction: 0.55,
|
|
startupTimeMs: 450,
|
|
responseTimeMs: 80,
|
|
});
|
|
|
|
// Access constants
|
|
console.log(TEST_CONFIG.FLASH_ATTENTION_SPEEDUP_MIN); // 2.49
|
|
console.log(TEST_CONFIG.AGENTDB_SEARCH_IMPROVEMENT_MAX); // 12500
|
|
```
|
|
|
|
## Best Practices
|
|
|
|
### 1. Use London School TDD
|
|
|
|
```typescript
|
|
// Arrange mocks before acting
|
|
const mockRepo = createMock<UserRepository>();
|
|
mockRepo.findById.mockResolvedValue(user);
|
|
|
|
// Act
|
|
await service.processUser('123');
|
|
|
|
// Assert behavior (not implementation)
|
|
expect(mockRepo.findById).toHaveBeenCalledWith('123');
|
|
expect(mockNotifier.notify).toHaveBeenCalledBefore(mockRepo.save);
|
|
```
|
|
|
|
### 2. Use Fixtures Over Inline Data
|
|
|
|
```typescript
|
|
// Good - use fixtures
|
|
const agent = agentConfigs.queenCoordinator;
|
|
const task = createSwarmTask('securityScan');
|
|
|
|
// Avoid - inline data
|
|
const agent = { type: 'queen-coordinator', name: 'Test', capabilities: [] };
|
|
```
|
|
|
|
### 3. Isolate Tests
|
|
|
|
```typescript
|
|
// Use fresh mocks per test
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
// Or use test scope
|
|
const scope = createTestScope();
|
|
await scope.run(async () => {
|
|
// isolated test
|
|
});
|
|
```
|
|
|
|
### 4. Test Behavior, Not Implementation
|
|
|
|
```typescript
|
|
// Good - behavior verification
|
|
expect(mockEventBus.publish).toHaveBeenCalledWith(
|
|
expect.objectContaining({ type: 'UserCreated' })
|
|
);
|
|
|
|
// Avoid - implementation details
|
|
expect(service._internalQueue.length).toBe(1);
|
|
```
|
|
|
|
## License
|
|
|
|
MIT
|