Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

chore: test suite migration: deno β†’ node.js/jest (#228)

lanemcdb82963d74d4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 00dcc38533..8c32b057a6 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -28,7 +28,7 @@ jobs:
deno-version: ${{ env.DENO_VERSION }}
- name: Run security audit
- run: < /dev/null |
+ run: |
# Check for security vulnerabilities in dependencies
deno cache --reload src/cli/index.ts
diff --git a/.hive-mind/config.json b/.hive-mind/config.json
index 8d69d2c1c8..badaca461a 100644
--- a/.hive-mind/config.json
+++ b/.hive-mind/config.json
@@ -1,6 +1,6 @@
{
"version": "2.0.0",
- "initialized": "2025-07-09T20:16:20.811Z",
+ "initialized": "2025-07-12T23:37:36.210Z",
"defaults": {
"queenType": "strategic",
"maxWorkers": 8,
diff --git a/TEST_FIX_PLAN.md b/TEST_FIX_PLAN.md
new file mode 100644
index 0000000000..2f302ec83e
--- /dev/null
+++ b/TEST_FIX_PLAN.md
@@ -0,0 +1,379 @@
+# πŸ§ͺ Claude-Flow Test Suite Fix Plan
+
+## πŸ“Š Executive Summary
+
+This document outlines a comprehensive plan to fix the failing test suite in the claude-flow repository. Currently, **100% of tests are failing** due to a critical runtime environment mismatch between Deno and Node.js.
+
+**Key Metrics:**
+- πŸ“ **52+ test files** affected
+- 🚨 **0% test success rate**
+- ⏱️ **7-12 days** estimated fix time
+- 🎯 **100% test execution** target outcome
+
+## πŸ” Root Cause Analysis
+
+### 1. **Runtime Environment Mismatch (Critical)**
+- **Issue**: Tests written for Deno runtime but project configured for Node.js/Jest
+- **Evidence**: All test files import from `https://deno.land/[email protected]/` URLs
+- **Impact**: Complete test suite failure
+- **Example Error**: `Cannot find module 'https://deno.land/[email protected]/testing/bdd.ts'`
+
+### 2. **Module Resolution Conflicts**
+- **Issue**: Jest cannot resolve Deno-style URL imports
+- **Files Affected**: All `.test.ts` and `.test.js` files
+- **Root Cause**: Incompatible import syntax between runtimes
+
+### 3. **Test Environment Teardown Issues**
+- **Issue**: Jest environment teardown causing cascading failures
+- **Error Pattern**: `You are trying to import a file after the Jest environment has been torn down`
+- **Impact**: Tests cannot complete execution
+
+### 4. **Mixed Runtime Dependencies**
+- **Issue**: Test utilities use Deno APIs in Node.js environment
+- **Problematic APIs**: `Deno.makeTempDir`, `Deno.Command`, `Deno.writeTextFile`
+- **Files**: `tests/test.utils.ts`, `tests/test.config.ts`
+
+### 5. **Import Path Inconsistencies**
+- **Issue**: Incorrect relative paths and file extensions
+- **Example**: Importing `.ts` files instead of `.js` in Node.js environment
+- **Impact**: Module resolution failures
+
+## πŸ› οΈ Comprehensive Fix Strategy
+
+### Phase 1: Critical Infrastructure Fixes (Priority: HIGH)
+
+#### 1.1 Runtime Strategy Decision
+**Recommendation: Migrate to Node.js/Jest**
+- βœ… Consistent with package.json configuration
+- βœ… Better CI/CD integration
+- βœ… Existing Jest setup can be leveraged
+- βœ… More mature tooling ecosystem
+
+#### 1.2 Test Utilities Conversion
+**File**: `tests/test.utils.ts`
+
+**Deno β†’ Node.js API Mapping:**
+```typescript
+// File Operations
+Deno.makeTempDir() β†’ fs.mkdtempSync(path.join(os.tmpdir(), 'claude-flow-'))
+Deno.writeTextFile() β†’ fs.writeFileSync()
+Deno.readTextFile() β†’ fs.readFileSync()
+
+// Process Management
+Deno.Command() β†’ child_process.spawn()
+Deno.env.get() β†’ process.env
+
+// Path Operations
+Deno.cwd() β†’ process.cwd()
+```
+
+#### 1.3 Import Statement Standardization
+**Pattern**: Convert all Deno imports to Node.js equivalents
+
+```typescript
+// BEFORE (Deno style)
+import { describe, it, beforeEach } from "https://deno.land/[email protected]/testing/bdd.ts";
+import { assertEquals, assertExists } from "https://deno.land/[email protected]/assert/mod.ts";
+
+// AFTER (Node.js/Jest style)
+import { describe, it, beforeEach, expect } from '@jest/globals';
+```
+
+### Phase 2: Test Configuration Updates (Priority: HIGH)
+
+#### 2.1 Jest Configuration Enhancement
+**File**: `jest.config.js`
+
+**Required Updates:**
+```javascript
+export default {
+ // Enhanced module name mapping
+ moduleNameMapper: {
+ '^(\\.{1,2}/.*)\\.js$': '$1',
+ '^~/(.*)$': '<rootDir>/src/$1',
+ '^@/(.*)$': '<rootDir>/src/$1',
+ '^@tests/(.*)$': '<rootDir>/tests/$1'
+ },
+
+ // Better transform handling
+ transformIgnorePatterns: [
+ 'node_modules/(?!(chalk|ora|inquirer|nanoid|fs-extra|ansi-styles|ruv-swarm)/)'
+ ],
+
+ // Improved test environment
+ testEnvironment: 'node',
+
+ // Enhanced setup
+ setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
+
+ // Better timeout handling
+ testTimeout: 30000
+};
+```
+
+#### 2.2 Jest Setup File Fix
+**File**: `jest.setup.js`
+
+**Current Issues:**
+- Import from `src/core/logger.js` causing module resolution conflicts
+- Missing proper test environment initialization
+
+**Solution:**
+```javascript
+// Set test environment flags
+process.env.CLAUDE_FLOW_ENV = 'test';
+process.env.NODE_ENV = 'test';
+
+// Mock external dependencies that cause issues
+jest.mock('better-sqlite3', () => ({
+ default: jest.fn().mockImplementation(() => ({
+ prepare: jest.fn().mockReturnValue({
+ run: jest.fn(),
+ get: jest.fn(),
+ all: jest.fn()
+ }),
+ close: jest.fn()
+ }))
+}));
+
+// Handle unhandled rejections
+process.on('unhandledRejection', (reason, promise) => {
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
+});
+```
+
+### Phase 3: Assertion Library Migration (Priority: MEDIUM)
+
+#### 3.1 Assertion Mapping Strategy
+**Complete mapping from Deno to Jest:**
+
+| Deno Assertion | Jest Equivalent | Usage Example |
+|----------------|-----------------|---------------|
+| `assertEquals(a, b)` | `expect(a).toBe(b)` | Exact equality |
+| `assertExists(value)` | `expect(value).toBeDefined()` | Existence check |
+| `assertGreater(a, b)` | `expect(a).toBeGreaterThan(b)` | Numerical comparison |
+| `assertThrows(() => fn())` | `expect(() => fn()).toThrow()` | Exception testing |
+| `assertRejects(promise)` | `expect(promise).rejects.toThrow()` | Async exception testing |
+| `assert(condition)` | `expect(condition).toBeTruthy()` | Boolean assertion |
+
+#### 3.2 Mock and Spy Migration
+```typescript
+// BEFORE (Deno style)
+import { spy, stub, assertSpyCall } from 'https://deno.land/[email protected]/testing/mock.ts';
+
+// AFTER (Jest style)
+import { jest } from '@jest/globals';
+
+// Usage changes:
+const mockFn = jest.fn();
+expect(mockFn).toHaveBeenCalledWith(expectedArgs);
+```
+
+### Phase 4: File-by-File Conversion (Priority: MEDIUM)
+
+#### 4.1 Conversion Priority Order
+1. **Test utilities** (`tests/test.utils.ts`) - Foundation
+2. **Unit tests** (`tests/unit/**/*.test.ts`) - Core functionality
+3. **Integration tests** (`tests/integration/**/*.test.ts`) - System tests
+4. **E2E tests** (`tests/e2e/**/*.test.ts`) - End-to-end validation
+5. **Performance tests** (`tests/performance/**/*.test.ts`) - Benchmarking
+
+#### 4.2 Automated Conversion Scripts
+**Create conversion utilities:**
+
+```bash
+# Script 1: Import converter
+scripts/convert-imports.js
+
+# Script 2: Assertion converter
+scripts/convert-assertions.js
+
+# Script 3: Path fixer
+scripts/fix-paths.js
+
+# Script 4: Validation runner
+scripts/validate-conversion.js
+```
+
+### Phase 5: Source Code Import Fixes (Priority: LOW)
+
+#### 5.1 Import Path Standardization
+**Pattern**: Fix relative import paths and extensions
+
+```typescript
+// Common issues to fix:
+import { ConfigManager } from '../../../src/core/config.ts';
+// Should be:
+import { ConfigManager } from '../../../src/core/config.js';
+
+// Or with alias:
+import { ConfigManager } from '@/core/config.js';
+```
+
+#### 5.2 Template Test Updates
+**Files**: Tests in `src/templates/` directory
+- Update to use Node.js file operations
+- Fix import statements
+- Ensure Jest compatibility
+
+## πŸ“‹ Implementation Checklist
+
+### Phase 1: Infrastructure (Days 1-3)
+- [ ] Update `tests/test.utils.ts` for Node.js compatibility
+- [ ] Convert Deno APIs to Node.js equivalents
+- [ ] Fix `jest.setup.js` configuration issues
+- [ ] Test core utilities functionality
+
+### Phase 2: Configuration (Day 4)
+- [ ] Enhance `jest.config.js` with proper mappings
+- [ ] Update package.json test scripts
+- [ ] Configure CI/CD for new test setup
+- [ ] Validate Jest environment
+
+### Phase 3: Bulk Conversion (Days 5-8)
+- [ ] Convert all import statements (52+ files)
+- [ ] Migrate assertion libraries
+- [ ] Update mock and spy usage
+- [ ] Fix relative import paths
+
+### Phase 4: Validation (Days 9-10)
+- [ ] Run unit tests and fix issues
+- [ ] Run integration tests and fix issues
+- [ ] Run e2e tests and fix issues
+- [ ] Performance test validation
+
+### Phase 5: Polish (Days 11-12)
+- [ ] Fix remaining edge cases
+- [ ] Update documentation
+- [ ] Add test coverage reporting
+- [ ] Final validation and cleanup
+
+## πŸ”§ Conversion Scripts
+
+### 1. Import Converter Script
+```javascript
+// scripts/convert-imports.js
+const fs = require('fs');
+const path = require('path');
+
+const DENO_TO_JEST_IMPORTS = {
+ "https://deno.land/[email protected]/testing/bdd.ts": "@jest/globals",
+ "https://deno.land/[email protected]/assert/mod.ts": "@jest/globals",
+ "https://deno.land/[email protected]/testing/mock.ts": "@jest/globals"
+};
+
+function convertImports(filePath) {
+ let content = fs.readFileSync(filePath, 'utf8');
+
+ Object.entries(DENO_TO_JEST_IMPORTS).forEach(([denoImport, jestImport]) => {
+ const regex = new RegExp(`from\\s+['"]${denoImport.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}['"]`, 'g');
+ content = content.replace(regex, `from '${jestImport}'`);
+ });
+
+ fs.writeFileSync(filePath, content);
+}
+```
+
+### 2. Assertion Converter Script
+```javascript
+// scripts/convert-assertions.js
+const ASSERTION_MAPPINGS = {
+ 'assertEquals(': 'expect(',
+ 'assertExists(': 'expect(',
+ 'assertGreater(': 'expect(',
+ 'assertThrows(': 'expect(',
+ 'assertRejects(': 'expect('
+};
+
+function convertAssertions(content) {
+ Object.entries(ASSERTION_MAPPINGS).forEach(([denoAssertion, jestStart]) => {
+ // Complex regex replacements for each assertion type
+ content = content.replace(new RegExp(denoAssertion, 'g'), jestStart);
+ });
+ return content;
+}
+```
+
+## πŸ“Š Success Metrics
+
+### Pre-Implementation (Current State)
+- ❌ Test execution rate: 0%
+- ❌ Passing tests: 0
+- ❌ CI/CD pipeline: Broken
+- ❌ Code coverage: Unmeasurable
+
+### Post-Implementation (Target State)
+- βœ… Test execution rate: 100%
+- βœ… Passing tests: Target 90%+
+- βœ… CI/CD pipeline: Functional
+- βœ… Code coverage: Measurable and reportable
+
+### Validation Criteria
+1. **All test files can be imported without errors**
+2. **Jest can discover and run all test suites**
+3. **No runtime environment conflicts**
+4. **Assertion failures are meaningful and clear**
+5. **CI/CD pipeline executes tests successfully**
+
+## πŸš€ Rollout Strategy
+
+### Development Phase
+1. Create feature branch: `fix/test-suite-migration`
+2. Implement changes incrementally
+3. Test each phase before proceeding
+4. Maintain detailed change log
+
+### Testing Phase
+1. Validate each converted test file individually
+2. Run test suites in isolation
+3. Perform integration testing
+4. Load test the complete suite
+
+### Deployment Phase
+1. Create pull request with comprehensive documentation
+2. Conduct code review
+3. Merge to main branch
+4. Update CI/CD configuration
+5. Monitor test execution in production
+
+## πŸ“ Risk Assessment
+
+### High Risk
+- **Runtime incompatibilities** - Mitigation: Thorough testing of Node.js alternatives
+- **Breaking changes to source code** - Mitigation: Focus on test-only changes
+- **Performance degradation** - Mitigation: Benchmark before/after
+
+### Medium Risk
+- **Time overrun** - Mitigation: Phased approach with clear milestones
+- **Incomplete conversion** - Mitigation: Automated validation scripts
+- **CI/CD disruption** - Mitigation: Feature branch testing
+
+### Low Risk
+- **Documentation gaps** - Mitigation: Comprehensive documentation updates
+- **Developer workflow changes** - Mitigation: Clear migration guide
+
+## πŸ“š Additional Resources
+
+### Documentation Updates Required
+- [ ] Update README.md testing section
+- [ ] Create test development guide
+- [ ] Document new test utilities
+- [ ] Update CI/CD documentation
+
+### Training Materials
+- [ ] Node.js vs Deno testing differences
+- [ ] Jest best practices guide
+- [ ] Test migration checklist
+- [ ] Troubleshooting guide
+
+## 🎯 Conclusion
+
+This comprehensive plan addresses all identified issues in the claude-flow test suite through a systematic, phased approach. The migration from Deno to Node.js/Jest will restore full test functionality and enable reliable CI/CD operations.
+
+**Expected Timeline**: 7-12 days for complete implementation
+**Success Rate**: 100% test execution capability
+**Impact**: Restored development velocity and code quality assurance
+
+---
+
+*This plan will be executed on the `fix/test-suite-migration` branch with regular progress updates and validation checkpoints.*
\ No newline at end of file
diff --git a/jest.config.js b/jest.config.js
index 1db0d6a4be..9bffb21ab3 100644
--- a/jest.config.js
+++ b/jest.config.js
@@ -31,7 +31,8 @@ export default {
moduleNameMapper: {
'^(\\.{1,2}/.*)\\.js$': '$1',
'^~/(.*)$': '<rootDir>/src/$1',
- '^@/(.*)$': '<rootDir>/src/$1'
+ '^@/(.*)$': '<rootDir>/src/$1',
+ '^@tests/(.*)$': '<rootDir>/tests/$1'
},
modulePathIgnorePatterns: [
'<rootDir>/dist/',
@@ -55,5 +56,18 @@ export default {
coverageReporters: ['text', 'lcov', 'html'],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testTimeout: 30000,
- verbose: true
+ verbose: true,
+ // Enhanced error handling
+ errorOnDeprecated: false,
+ // Better module resolution
+ moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
+ // Clear mocks between tests
+ clearMocks: true,
+ restoreMocks: true,
+ // Enhanced globals
+ globals: {
+ 'ts-jest': {
+ useESM: true
+ }
+ }
};
\ No newline at end of file
diff --git a/jest.setup.js b/jest.setup.js
index 7583b17715..ad5dd86ab9 100644
--- a/jest.setup.js
+++ b/jest.setup.js
@@ -7,16 +7,6 @@
process.env.CLAUDE_FLOW_ENV = 'test';
process.env.NODE_ENV = 'test';
-// Initialize logger for test environment
-import { Logger } from './src/core/logger.js';
-Logger.getInstance({
- level: 'error',
- format: 'json',
- destination: 'console'
-});
-
-// Test timeout will be set in Jest config
-
// Suppress console output during tests unless explicitly needed
const originalConsole = { ...console };
@@ -25,5 +15,8 @@ global.originalConsole = originalConsole;
// Handle unhandled rejections in tests
process.on('unhandledRejection', (reason, promise) => {
- console.error('Unhandled Rejection at:', promise, 'reason:', reason);
+ // Only log in test environment if needed
+ if (process.env.DEBUG_TESTS) {
+ console.error('Unhandled Rejection at:', promise, 'reason:', reason);
+ }
});
\ No newline at end of file
diff --git a/tests/batch-init.test.js b/tests/batch-init.test.js
index 12aa3347e3..773a266ef3 100644
--- a/tests/batch-init.test.js
+++ b/tests/batch-init.test.js
@@ -3,7 +3,7 @@
* Test Suite for Batch Initialization Features
*/
-import { assertEquals, assert } from 'https://deno.land/[email protected]/assert/mod.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import {
batchInitCommand,
validateBatchOptions,
@@ -40,25 +40,25 @@ Deno.test('Batch Options Validation', () => {
template: 'web-api',
environments: ['dev', 'staging']
});
- assertEquals(errors.length, 0, 'Valid options should pass validation');
+ expect(errors.length).toBe(0, 'Valid options should pass validation');
// Invalid max concurrency
errors = validateBatchOptions({
maxConcurrency: 25
});
- assert(errors.some(e => e.includes('maxConcurrency')), 'High concurrency should fail');
+ expect(errors.some(e => e.includes('maxConcurrency').toBeTruthy()), 'High concurrency should fail');
// Invalid template
errors = validateBatchOptions({
template: 'invalid-template'
});
- assert(errors.some(e => e.includes('template')), 'Invalid template should fail');
+ expect(errors.some(e => e.includes('template').toBeTruthy()), 'Invalid template should fail');
// Invalid environment
errors = validateBatchOptions({
environments: ['invalid-env']
});
- assert(errors.some(e => e.includes('environment')), 'Invalid environment should fail');
+ expect(errors.some(e => e.includes('environment').toBeTruthy()), 'Invalid environment should fail');
console.log('βœ… Batch options validation tests passed');
});
@@ -69,17 +69,17 @@ Deno.test('Project Templates', () => {
// Check that all templates have required properties
for (const [key, template] of Object.entries(PROJECT_TEMPLATES)) {
- assert(template.name, `Template ${key} should have a name`);
- assert(template.description, `Template ${key} should have a description`);
- assert(Array.isArray(template.extraDirs), `Template ${key} should have extraDirs array`);
- assert(typeof template.extraFiles === 'object', `Template ${key} should have extraFiles object`);
+ expect(template.name, `Template ${key} should have a name`).toBeTruthy();
+ expect(template.description, `Template ${key} should have a description`).toBeTruthy();
+ expect(Array.isArray(template.extraDirs).toBeTruthy(), `Template ${key} should have extraDirs array`);
+ expect(typeof template.extraFiles === 'object', `Template ${key} should have extraFiles object`).toBeTruthy();
}
// Check specific templates
- assert(PROJECT_TEMPLATES['web-api'], 'web-api template should exist');
- assert(PROJECT_TEMPLATES['react-app'], 'react-app template should exist');
- assert(PROJECT_TEMPLATES['microservice'], 'microservice template should exist');
- assert(PROJECT_TEMPLATES['cli-tool'], 'cli-tool template should exist');
+ expect(PROJECT_TEMPLATES['web-api'], 'web-api template should exist').toBeTruthy();
+ expect(PROJECT_TEMPLATES['react-app'], 'react-app template should exist').toBeTruthy();
+ expect(PROJECT_TEMPLATES['microservice'], 'microservice template should exist').toBeTruthy();
+ expect(PROJECT_TEMPLATES['cli-tool'], 'cli-tool template should exist').toBeTruthy();
console.log('βœ… Project templates tests passed');
});
@@ -90,15 +90,15 @@ Deno.test('Environment Configurations', () => {
// Check that all environments have required properties
for (const [key, env] of Object.entries(ENVIRONMENT_CONFIGS)) {
- assert(env.name, `Environment ${key} should have a name`);
- assert(Array.isArray(env.features), `Environment ${key} should have features array`);
- assert(typeof env.config === 'object', `Environment ${key} should have config object`);
+ expect(env.name, `Environment ${key} should have a name`).toBeTruthy();
+ expect(Array.isArray(env.features).toBeTruthy(), `Environment ${key} should have features array`);
+ expect(typeof env.config === 'object', `Environment ${key} should have config object`).toBeTruthy();
}
// Check specific environments
- assert(ENVIRONMENT_CONFIGS['dev'], 'dev environment should exist');
- assert(ENVIRONMENT_CONFIGS['staging'], 'staging environment should exist');
- assert(ENVIRONMENT_CONFIGS['prod'], 'prod environment should exist');
+ expect(ENVIRONMENT_CONFIGS['dev'], 'dev environment should exist').toBeTruthy();
+ expect(ENVIRONMENT_CONFIGS['staging'], 'staging environment should exist').toBeTruthy();
+ expect(ENVIRONMENT_CONFIGS['prod'], 'prod environment should exist').toBeTruthy();
console.log('βœ… Environment configurations tests passed');
});
@@ -118,13 +118,13 @@ Deno.test('Batch Initialization - Minimal', async () => {
const results = await batchInitCommand(projects, options);
- assertEquals(results.length, 2, 'Should create 2 projects');
- assert(results.every(r => r.success), 'All projects should be created successfully');
+ expect(results.length).toBe(2, 'Should create 2 projects');
+ expect(results.every(r => r.success).toBeTruthy(), 'All projects should be created successfully');
// Check that projects were created
for (const project of projects) {
const stats = await Deno.stat(project);
- assert(stats.isDirectory, `${project} should be a directory`);
+ expect(stats.isDirectory, `${project} should be a directory`).toBeTruthy();
// Check for essential files
await Deno.stat(`${project}/CLAUDE.md`);
@@ -152,8 +152,8 @@ Deno.test('Template-Based Initialization', async () => {
const results = await batchInitCommand(projects, options);
- assertEquals(results.length, 1, 'Should create 1 project');
- assert(results[0].success, 'Project should be created successfully');
+ expect(results.length).toBe(1, 'Should create 1 project');
+ expect(results[0].success, 'Project should be created successfully').toBeTruthy();
// Check template-specific files
const projectDir = projects[0];
@@ -163,8 +163,8 @@ Deno.test('Template-Based Initialization', async () => {
// Check package.json content
const packageJson = JSON.parse(await Deno.readTextFile(`${projectDir}/package.json`));
- assertEquals(packageJson.name, 'api-project');
- assert(packageJson.dependencies.express, 'Should have Express dependency');
+ expect(packageJson.name).toBe('api-project');
+ expect(packageJson.dependencies.express, 'Should have Express dependency').toBeTruthy();
console.log('βœ… Template-based initialization tests passed');
await cleanup();
@@ -185,8 +185,8 @@ Deno.test('Multi-Environment Initialization', async () => {
const results = await batchInitCommand(projects, options);
- assertEquals(results.length, 2, 'Should create 2 environment variants');
- assert(results.every(r => r.success), 'All environments should be created successfully');
+ expect(results.length).toBe(2, 'Should create 2 environment variants');
+ expect(results.every(r => r.success).toBeTruthy(), 'All environments should be created successfully');
// Check that both environments were created
await Deno.stat('multi-env-app-dev');
@@ -196,8 +196,8 @@ Deno.test('Multi-Environment Initialization', async () => {
const devData = JSON.parse(await Deno.readTextFile('multi-env-app-dev/memory/claude-flow-data.json'));
const stagingData = JSON.parse(await Deno.readTextFile('multi-env-app-staging/memory/claude-flow-data.json'));
- assertEquals(devData.environment, 'dev');
- assertEquals(stagingData.environment, 'staging');
+ expect(devData.environment).toBe('dev');
+ expect(stagingData.environment).toBe('staging');
console.log('βœ… Multi-environment initialization tests passed');
await cleanup();
@@ -218,9 +218,9 @@ Deno.test('Error Handling', async () => {
const results = await batchInitCommand(projects, options);
- assertEquals(results.length, 2, 'Should attempt to create 2 projects');
- assert(results[0].success, 'Valid project should succeed');
- assert(!results[1].success, 'Invalid project should fail');
+ expect(results.length).toBe(2, 'Should attempt to create 2 projects');
+ expect(results[0].success, 'Valid project should succeed').toBeTruthy();
+ expect(!results[1].success, 'Invalid project should fail').toBeTruthy();
console.log('βœ… Error handling tests passed');
await cleanup();
diff --git a/tests/data/sessions/test-dir/2025-07-05T01-28-45.294Z-metrics.json b/tests/data/sessions/test-dir/2025-07-05T01-28-45.294Z-metrics.json
deleted file mode 100644
index 1fb190685f..0000000000
--- a/tests/data/sessions/test-dir/2025-07-05T01-28-45.294Z-metrics.json
+++ /dev/null
@@ -1,17 +0,0 @@
-{
- "performance": {
- "duration_ms": 5,
- "operations_per_minute": "0.0",
- "tokens_saved": 0,
- "efficiency_score": "NaN"
- },
- "learning": {
- "patterns_improved": 0,
- "average_improvement": "NaN",
- "confidence_average": "NaN"
- },
- "agents": {
- "total_spawned": 0,
- "by_type": {}
- }
-}
\ No newline at end of file
diff --git a/tests/data/sessions/test-dir/2025-07-05T01-28-45.294Z-summary.md b/tests/data/sessions/test-dir/2025-07-05T01-28-45.294Z-summary.md
deleted file mode 100644
index 95d6deabb8..0000000000
--- a/tests/data/sessions/test-dir/2025-07-05T01-28-45.294Z-summary.md
+++ /dev/null
@@ -1,21 +0,0 @@
-# ruv-swarm Session Summary
-Date: 2025-07-05T01:28:45.294Z
-Duration: 0s
-Token Reduction: 0 tokens
-
-## Swarm Activity
-- Active Agents: 0 ()
-- Operations Performed: 0
-- Files Modified: 0
-- Neural Improvements: 0
-
-## Operations Breakdown
-
-
-## Learning Highlights
-
-
-## Performance Metrics
-- Average Operation Time: Infinitys
-- Token Efficiency: NaN tokens/operation
-- Learning Rate: NaN improvements/operation
diff --git a/tests/e2e/cli-commands.test.ts b/tests/e2e/cli-commands.test.ts
index 899e2e1445..109b8728f7 100644
--- a/tests/e2e/cli-commands.test.ts
+++ b/tests/e2e/cli-commands.test.ts
@@ -44,7 +44,7 @@ describe('CLI Commands E2E', () => {
const output = new TextDecoder().decode(stdout);
const errorOutput = new TextDecoder().decode(stderr);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Claude-Flow');
assertStringIncludes(output, 'COMMANDS');
assertStringIncludes(output, 'start');
@@ -67,27 +67,27 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Configuration file created');
// Verify file was created with valid content
const stat = await Deno.stat(configPath);
- assertEquals(stat.isFile, true);
+ expect(stat.isFile).toBe(true);
const content = await Deno.readTextFile(configPath);
const config = JSON.parse(content);
- assertExists(config.orchestrator);
- assertExists(config.terminal);
- assertExists(config.memory);
- assertExists(config.coordination);
- assertExists(config.mcp);
- assertExists(config.logging);
+ expect(config.orchestrator).toBeDefined();
+ expect(config.terminal).toBeDefined();
+ expect(config.memory).toBeDefined();
+ expect(config.coordination).toBeDefined();
+ expect(config.mcp).toBeDefined();
+ expect(config.logging).toBeDefined();
// Check specific default values
- assertEquals(config.orchestrator.maxConcurrentAgents, 10);
- assertEquals(config.terminal.type, 'auto');
- assertEquals(config.memory.backend, 'hybrid');
+ expect(config.orchestrator.maxConcurrentAgents).toBe(10);
+ expect(config.terminal.type).toBe('auto');
+ expect(config.memory.backend).toBe('hybrid');
});
it('should validate configuration file', async () => {
@@ -145,7 +145,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Configuration is valid');
});
@@ -180,7 +180,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 1); // Should exit with error code
+ expect(code).toBe(1); // Should exit with error code
assertStringIncludes(output, 'Configuration validation failed');
});
@@ -195,13 +195,13 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
// Should contain JSON configuration
const config = JSON.parse(output);
- assertExists(config.orchestrator);
- assertExists(config.terminal);
- assertExists(config.memory);
+ expect(config.orchestrator).toBeDefined();
+ expect(config.terminal).toBeDefined();
+ expect(config.memory).toBeDefined();
});
});
@@ -224,17 +224,17 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Agent profile created');
// Parse JSON output to verify profile
const profile = JSON.parse(output.split('\n').find(line => line.includes('"id"')) || '{}');
- assertEquals(profile.name, 'Test Researcher');
- assertEquals(profile.type, 'researcher');
- assertEquals(profile.priority, 5);
- assertEquals(profile.maxConcurrentTasks, 3);
- assertEquals(profile.capabilities.includes('analysis'), true);
- assertEquals(profile.capabilities.includes('research'), true);
+ expect(profile.name).toBe('Test Researcher');
+ expect(profile.type).toBe('researcher');
+ expect(profile.priority).toBe(5);
+ expect(profile.maxConcurrentTasks).toBe(3);
+ expect(profile.capabilities.includes('analysis')).toBe(true);
+ expect(profile.capabilities.includes('research')).toBe(true);
});
it('should list agent profiles', async () => {
@@ -263,7 +263,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await listCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Active Agents');
});
@@ -301,7 +301,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await statusCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, agentId);
assertStringIncludes(output, 'Status Test Agent');
});
@@ -343,7 +343,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await terminateCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Agent terminated');
assertStringIncludes(output, agentId);
});
@@ -368,17 +368,17 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Task created');
// Parse JSON output to verify task
const task = JSON.parse(output.split('\n').find(line => line.includes('"id"')) || '{}');
- assertEquals(task.type, 'analysis');
- assertEquals(task.description, 'Analyze the test data for patterns');
- assertEquals(task.priority, 8);
- assertEquals(task.dependencies.includes('data-collection'), true);
- assertEquals(task.dependencies.includes('preprocessing'), true);
- assertEquals(task.input.dataset, 'test-data');
+ expect(task.type).toBe('analysis');
+ expect(task.description).toBe('Analyze the test data for patterns');
+ expect(task.priority).toBe(8);
+ expect(task.dependencies.includes('data-collection')).toBe(true);
+ expect(task.dependencies.includes('preprocessing')).toBe(true);
+ expect(task.input.dataset).toBe('test-data');
});
it('should list tasks', async () => {
@@ -407,7 +407,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await listCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Tasks');
});
@@ -444,7 +444,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await statusCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, taskId);
assertStringIncludes(output, 'status-test');
});
@@ -483,7 +483,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await executeCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Task execution');
});
@@ -524,7 +524,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await cancelCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Task cancelled');
assertStringIncludes(output, taskId);
});
@@ -548,7 +548,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Memory query results');
});
@@ -573,7 +573,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Memory entry stored');
assertStringIncludes(output, entryContent);
});
@@ -614,7 +614,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await deleteCommand.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Memory entry deleted');
assertStringIncludes(output, entryId);
});
@@ -630,7 +630,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Memory synchronization');
});
@@ -645,7 +645,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Memory Statistics');
});
});
@@ -667,7 +667,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Claude-Flow system');
});
@@ -682,7 +682,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'System Status');
});
@@ -697,7 +697,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
assertStringIncludes(output, 'Claude-Flow');
assertStringIncludes(output, 'version');
});
@@ -715,7 +715,7 @@ describe('CLI Commands E2E', () => {
const { code, stderr } = await command.output();
const errorOutput = new TextDecoder().decode(stderr);
- assertEquals(code, 1);
+ expect(code).toBe(1);
assertStringIncludes(errorOutput, 'Unknown command');
});
@@ -733,7 +733,7 @@ describe('CLI Commands E2E', () => {
const { code, stderr } = await command.output();
const errorOutput = new TextDecoder().decode(stderr);
- assertEquals(code, 1);
+ expect(code).toBe(1);
assertStringIncludes(errorOutput, 'required');
});
@@ -751,7 +751,7 @@ describe('CLI Commands E2E', () => {
const { code, stderr } = await command.output();
const errorOutput = new TextDecoder().decode(stderr);
- assertEquals(code, 1);
+ expect(code).toBe(1);
assertStringIncludes(errorOutput, 'not found');
});
@@ -772,7 +772,7 @@ describe('CLI Commands E2E', () => {
const { code, stderr } = await command.output();
const errorOutput = new TextDecoder().decode(stderr);
- assertEquals(code, 1);
+ expect(code).toBe(1);
assertStringIncludes(errorOutput, 'JSON');
});
});
@@ -793,11 +793,11 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
// Should be valid JSON
const config = JSON.parse(output);
- assertExists(config.orchestrator);
+ expect(config.orchestrator).toBeDefined();
});
it('should support table output format', async () => {
@@ -815,7 +815,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
// Table format should contain headers and borders
assertStringIncludes(output, '|');
});
@@ -835,7 +835,7 @@ describe('CLI Commands E2E', () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
+ expect(code).toBe(0);
// YAML format should contain key-value pairs with colons
assertStringIncludes(output, 'orchestrator:');
assertStringIncludes(output, 'terminal:');
@@ -868,7 +868,7 @@ describe('CLI Commands E2E', () => {
await writer.close();
const { code } = await process.output();
- assertEquals(code, 0);
+ expect(code).toBe(0);
});
});
});
\ No newline at end of file
diff --git a/tests/e2e/full-system-integration.test.ts b/tests/e2e/full-system-integration.test.ts
index 4f3fba9e5e..4a5012d549 100644
--- a/tests/e2e/full-system-integration.test.ts
+++ b/tests/e2e/full-system-integration.test.ts
@@ -3,9 +3,9 @@
* Tests complete workflows and system integration
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertStringIncludes } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { assertEquals, assertExists, assertStringIncludes } from "../test.utils.ts";
+// FakeTime equivalent available in test.utils.ts
import {
AsyncTestUtils,
@@ -143,7 +143,7 @@ describe('Full System Integration Tests', () => {
};
const result = await shutdownTest();
- assertEquals(result, 'shutdown complete');
+ expect(result).toBe('shutdown complete');
});
it('should recover from component failures during startup', async () => {
@@ -174,11 +174,11 @@ describe('Full System Integration Tests', () => {
};
const results = await componentFailureTest();
- assertEquals(results.length, 4);
+ expect(results.length).toBe(4);
// All components should eventually be running
results.forEach(result => {
- assertEquals(['success', 'recovered'].includes(result.status), true);
+ expect(['success').toBe('recovered'].includes(result.status), true);
});
});
});
@@ -233,11 +233,11 @@ describe('Full System Integration Tests', () => {
const executionLog = await workflowTest();
// Verify workflow executed correctly
- assertEquals(executionLog.length >= 3, true); // At least some tasks completed
+ expect(executionLog.length >= 3).toBe(true); // At least some tasks completed
// Verify agent participation
const agentsUsed = new Set(executionLog.map(entry => entry.agent));
- assertEquals(agentsUsed.size >= 2, true); // Multiple agents participated
+ expect(agentsUsed.size >= 2).toBe(true); // Multiple agents participated
console.log(`Multi-agent workflow completed with ${executionLog.length} tasks`);
});
@@ -338,7 +338,7 @@ describe('Full System Integration Tests', () => {
const results = await concurrentWorkflowTest();
// All workflows should complete
- assertEquals(results.length, 8); // Total tasks across all workflows
+ expect(results.length).toBe(8); // Total tasks across all workflows
// Verify each workflow completed
const workflowResults = new Map();
@@ -349,10 +349,10 @@ describe('Full System Integration Tests', () => {
workflowResults.get(result.workflowId).push(result);
});
- assertEquals(workflowResults.size, 3); // All 3 workflows
- assertEquals(workflowResults.get('workflow-1').length, 3);
- assertEquals(workflowResults.get('workflow-2').length, 3);
- assertEquals(workflowResults.get('workflow-3').length, 2);
+ expect(workflowResults.size).toBe(3); // All 3 workflows
+ expect(workflowResults.get('workflow-1').length).toBe(3);
+ expect(workflowResults.get('workflow-2').length).toBe(3);
+ expect(workflowResults.get('workflow-3').length).toBe(2);
console.log('Concurrent workflows completed successfully');
});
@@ -384,8 +384,8 @@ describe('Full System Integration Tests', () => {
const results = await persistenceTest();
- assertEquals(results.stored, results.recovered);
- assertEquals(results.dataIntegrity, true);
+ expect(results.stored).toBe(results.recovered);
+ expect(results.dataIntegrity).toBe(true);
console.log(`Persistence test: ${results.stored} entries stored and recovered`);
});
@@ -425,9 +425,9 @@ describe('Full System Integration Tests', () => {
return memoryOperations.length;
});
- assertEquals(leaked, false);
- assertEquals(typeof result, 'number');
- assertEquals(result > 1000, true); // Many operations performed
+ expect(leaked).toBe(false);
+ expect(typeof result).toBe('number');
+ expect(result > 1000).toBe(true); // Many operations performed
console.log(`Memory operations completed: ${result} operations, memory increase: ${(memoryIncrease / 1024 / 1024).toFixed(2)}MB`);
});
@@ -480,8 +480,8 @@ describe('Full System Integration Tests', () => {
const results = await synchronizationTest();
- assertEquals(results.totalOperations, 50);
- assertEquals(results.agentsParticipated, 3);
+ expect(results.totalOperations).toBe(50);
+ expect(results.agentsParticipated).toBe(3);
TestAssertions.assertInRange(results.uniqueKeys, 10, 20); // Overlap expected
console.log(`Memory synchronization: ${results.uniqueKeys} unique keys from ${results.totalOperations} operations`);
@@ -545,8 +545,8 @@ describe('Full System Integration Tests', () => {
const results = await terminalTest();
- assertEquals(results.totalCommands, 12); // 4 commands * 3 sessions
- assertEquals(results.sessionsUsed, 3);
+ expect(results.totalCommands).toBe(12); // 4 commands * 3 sessions
+ expect(results.sessionsUsed).toBe(3);
TestAssertions.assertInRange(results.successfulCommands / results.totalCommands, 0.8, 1.0);
console.log(`Terminal test: ${results.successfulCommands}/${results.totalCommands} commands successful across ${results.sessionsUsed} sessions`);
@@ -599,18 +599,18 @@ describe('Full System Integration Tests', () => {
const results = await timeoutTest();
- assertEquals(results.length, 3);
+ expect(results.length).toBe(3);
// First command should succeed quickly
- assertEquals(results[0].success, true);
+ expect(results[0].success).toBe(true);
TestAssertions.assertInRange(results[0].actualDuration, 0, 500);
// Second command should succeed within timeout
- assertEquals(results[1].success, true);
+ expect(results[1].success).toBe(true);
TestAssertions.assertInRange(results[1].actualDuration, 1500, 3000);
// Third command should timeout
- assertEquals(results[2].success, false);
+ expect(results[2].success).toBe(false);
TestAssertions.assertInRange(results[2].actualDuration, 900, 1100);
console.log('Terminal timeout handling verified');
@@ -673,11 +673,11 @@ describe('Full System Integration Tests', () => {
const responses = await mcpTest();
- assertEquals(responses.length, 4);
+ expect(responses.length).toBe(4);
// Verify specific responses
const listToolsResponse = responses.find(r => r.request === 'list_tools');
- assertEquals(listToolsResponse?.response.result?.tools.length, 3);
+ expect(listToolsResponse?.response.result?.tools.length).toBe(3);
const calculatorResponse = responses.find(r => r.request === 'call_tool');
assertStringIncludes(calculatorResponse?.response.result?.content[0].text, '5 + 3 = 8');
@@ -732,8 +732,8 @@ describe('Full System Integration Tests', () => {
const results = await poolingTest();
- assertEquals(results.totalRequests, results.routedRequests);
- assertEquals(results.serverDistribution.length, 3);
+ expect(results.totalRequests).toBe(results.routedRequests);
+ expect(results.serverDistribution.length).toBe(3);
// Load should be distributed across servers
const totalLoad = results.serverDistribution.reduce((sum, s) => sum + s.finalLoad, 0);
@@ -769,7 +769,7 @@ describe('Full System Integration Tests', () => {
// System should maintain good performance
TestAssertions.assertInRange(throughputTest.successfulRequests / throughputTest.totalRequests, 0.9, 1.0);
TestAssertions.assertInRange(throughputTest.averageResponseTime, 0, 100);
- assertEquals(throughputTest.errors.length < throughputTest.totalRequests * 0.05, true); // Less than 5% errors
+ expect(throughputTest.errors.length < throughputTest.totalRequests * 0.05).toBe(true); // Less than 5% errors
console.log(`High throughput test: ${throughputTest.successfulRequests}/${throughputTest.totalRequests} successful (${throughputTest.requestsPerSecond.toFixed(1)} req/sec)`);
});
@@ -806,7 +806,7 @@ describe('Full System Integration Tests', () => {
return workload.length;
}, { threshold: 100 * 1024 * 1024 }); // 100MB threshold
- assertEquals(leaked, false);
+ expect(leaked).toBe(false);
console.log('Memory pressure test completed without leaks');
});
@@ -869,10 +869,10 @@ describe('Full System Integration Tests', () => {
const results = await overloadTest();
- assertEquals(results.totalRequests, results.successfulRequests + results.rejectedRequests);
+ expect(results.totalRequests).toBe(results.successfulRequests + results.rejectedRequests);
// System should have protected itself by rejecting excess requests
- assertEquals(results.rejectedRequests > 0, true);
+ expect(results.rejectedRequests > 0).toBe(true);
// But should have served a reasonable number of requests
TestAssertions.assertInRange(results.successfulRequests / results.totalRequests, 0.3, 0.8);
@@ -951,8 +951,8 @@ describe('Full System Integration Tests', () => {
const results = await cascadingFailureTest();
// All components should eventually recover
- assertEquals(results.recoveredComponents, 5);
- assertEquals(results.recoveryEvents >= 6, true); // At least 3 failures + 3 recoveries
+ expect(results.recoveredComponents).toBe(5);
+ expect(results.recoveryEvents >= 6).toBe(true); // At least 3 failures + 3 recoveries
console.log(`Cascading failure recovery: ${results.recoveredComponents}/5 components recovered`);
});
diff --git a/tests/e2e/full-workflow.test.ts b/tests/e2e/full-workflow.test.ts
index e253328100..912048c16c 100644
--- a/tests/e2e/full-workflow.test.ts
+++ b/tests/e2e/full-workflow.test.ts
@@ -94,7 +94,7 @@ describe('E2E Full Workflow', () => {
});
const { code: configCode } = await configCommand.output();
- assertEquals(configCode, 0);
+ expect(configCode).toBe(0);
// Step 2: Start system in background
const startCommand = new Deno.Command(Deno.execPath(), {
@@ -133,11 +133,11 @@ describe('E2E Full Workflow', () => {
});
const { code: researcherCode, stdout: researcherOutput } = await researcherCommand.output();
- assertEquals(researcherCode, 0);
+ expect(researcherCode).toBe(0);
const researcherResult = new TextDecoder().decode(researcherOutput);
const researcherMatch = researcherResult.match(/"id":\s*"([^"]+)"/);
- assertExists(researcherMatch);
+ expect(researcherMatch).toBeDefined();
const researcherId = researcherMatch[1];
// Step 4: Create implementer agent
@@ -157,11 +157,11 @@ describe('E2E Full Workflow', () => {
});
const { code: implementerCode, stdout: implementerOutput } = await implementerCommand.output();
- assertEquals(implementerCode, 0);
+ expect(implementerCode).toBe(0);
const implementerResult = new TextDecoder().decode(implementerOutput);
const implementerMatch = implementerResult.match(/"id":\s*"([^"]+)"/);
- assertExists(implementerMatch);
+ expect(implementerMatch).toBeDefined();
const implementerId = implementerMatch[1];
// Step 5: Create research task
@@ -185,11 +185,11 @@ describe('E2E Full Workflow', () => {
});
const { code: researchTaskCode, stdout: researchTaskOutput } = await researchTaskCommand.output();
- assertEquals(researchTaskCode, 0);
+ expect(researchTaskCode).toBe(0);
const researchTaskResult = new TextDecoder().decode(researchTaskOutput);
const researchTaskMatch = researchTaskResult.match(/"id":\s*"([^"]+)"/);
- assertExists(researchTaskMatch);
+ expect(researchTaskMatch).toBeDefined();
const researchTaskId = researchTaskMatch[1];
// Step 6: Create implementation task (depends on research)
@@ -215,11 +215,11 @@ describe('E2E Full Workflow', () => {
});
const { code: implementTaskCode, stdout: implementTaskOutput } = await implementTaskCommand.output();
- assertEquals(implementTaskCode, 0);
+ expect(implementTaskCode).toBe(0);
const implementTaskResult = new TextDecoder().decode(implementTaskOutput);
const implementTaskMatch = implementTaskResult.match(/"id":\s*"([^"]+)"/);
- assertExists(implementTaskMatch);
+ expect(implementTaskMatch).toBeDefined();
const implementTaskId = implementTaskMatch[1];
// Step 7: Execute research task
@@ -235,7 +235,7 @@ describe('E2E Full Workflow', () => {
});
const { code: executeResearchCode } = await executeResearchCommand.output();
- assertEquals(executeResearchCode, 0);
+ expect(executeResearchCode).toBe(0);
// Step 8: Wait for research task to complete, then execute implementation
await delay(3000);
@@ -252,7 +252,7 @@ describe('E2E Full Workflow', () => {
});
const { code: executeImplementCode } = await executeImplementCommand.output();
- assertEquals(executeImplementCode, 0);
+ expect(executeImplementCode).toBe(0);
// Step 9: Check task statuses
const researchStatusCommand = new Deno.Command(Deno.execPath(), {
@@ -267,7 +267,7 @@ describe('E2E Full Workflow', () => {
});
const { code: researchStatusCode, stdout: researchStatusOutput } = await researchStatusCommand.output();
- assertEquals(researchStatusCode, 0);
+ expect(researchStatusCode).toBe(0);
const researchStatus = new TextDecoder().decode(researchStatusOutput);
assertStringIncludes(researchStatus, researchTaskId);
@@ -288,7 +288,7 @@ describe('E2E Full Workflow', () => {
});
const { code: memoryQueryCode } = await memoryQueryCommand.output();
- assertEquals(memoryQueryCode, 0);
+ expect(memoryQueryCode).toBe(0);
// Step 11: Check system status
const statusCommand = new Deno.Command(Deno.execPath(), {
@@ -303,7 +303,7 @@ describe('E2E Full Workflow', () => {
});
const { code: statusCode, stdout: statusOutput } = await statusCommand.output();
- assertEquals(statusCode, 0);
+ expect(statusCode).toBe(0);
const statusResult = new TextDecoder().decode(statusOutput);
assertStringIncludes(statusResult, 'System Status');
@@ -321,7 +321,7 @@ describe('E2E Full Workflow', () => {
});
const { code: listAgentsCode } = await listAgentsCommand.output();
- assertEquals(listAgentsCode, 0);
+ expect(listAgentsCode).toBe(0);
const listTasksCommand = new Deno.Command(Deno.execPath(), {
args: [
@@ -335,7 +335,7 @@ describe('E2E Full Workflow', () => {
});
const { code: listTasksCode } = await listTasksCommand.output();
- assertEquals(listTasksCode, 0);
+ expect(listTasksCode).toBe(0);
} finally {
// Step 13: Shutdown system
@@ -399,7 +399,7 @@ describe('E2E Full Workflow', () => {
const { stdout: coordinatorOutput } = await coordinatorCommand.output();
const coordinatorResult = new TextDecoder().decode(coordinatorOutput);
const coordinatorId = coordinatorResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(coordinatorId);
+ expect(coordinatorId).toBeDefined();
// Create multiple worker agents
const workerIds: string[] = [];
@@ -422,7 +422,7 @@ describe('E2E Full Workflow', () => {
const { stdout: workerOutput } = await workerCommand.output();
const workerResult = new TextDecoder().decode(workerOutput);
const workerId = workerResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(workerId);
+ expect(workerId).toBeDefined();
workerIds.push(workerId);
}
@@ -449,7 +449,7 @@ describe('E2E Full Workflow', () => {
const { stdout: coordinationTaskOutput } = await coordinationTaskCommand.output();
const coordinationTaskResult = new TextDecoder().decode(coordinationTaskOutput);
const coordinationTaskId = coordinationTaskResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(coordinationTaskId);
+ expect(coordinationTaskId).toBeDefined();
// Create worker tasks
const workerTaskIds: string[] = [];
@@ -477,7 +477,7 @@ describe('E2E Full Workflow', () => {
const { stdout: workerTaskOutput } = await workerTaskCommand.output();
const workerTaskResult = new TextDecoder().decode(workerTaskOutput);
const workerTaskId = workerTaskResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(workerTaskId);
+ expect(workerTaskId).toBeDefined();
workerTaskIds.push(workerTaskId);
}
@@ -527,7 +527,7 @@ describe('E2E Full Workflow', () => {
});
const { code } = await statusCommand.output();
- assertEquals(code, 0);
+ expect(code).toBe(0);
}
// Check memory for coordination events
@@ -546,7 +546,7 @@ describe('E2E Full Workflow', () => {
});
const { code: memoryCode } = await coordinationMemoryCommand.output();
- assertEquals(memoryCode, 0);
+ expect(memoryCode).toBe(0);
} finally {
// Shutdown system
@@ -609,7 +609,7 @@ describe('E2E Full Workflow', () => {
const { stdout: agentOutput } = await resilientAgentCommand.output();
const agentResult = new TextDecoder().decode(agentOutput);
const agentId = agentResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(agentId);
+ expect(agentId).toBeDefined();
// Create task that may fail initially
const unreliableTaskCommand = new Deno.Command(Deno.execPath(), {
@@ -635,7 +635,7 @@ describe('E2E Full Workflow', () => {
const { stdout: taskOutput } = await unreliableTaskCommand.output();
const taskResult = new TextDecoder().decode(taskOutput);
const taskId = taskResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(taskId);
+ expect(taskId).toBeDefined();
// Execute unreliable task
const executeTaskCommand = new Deno.Command(Deno.execPath(), {
@@ -651,7 +651,7 @@ describe('E2E Full Workflow', () => {
const { code: executeCode } = await executeTaskCommand.output();
// Task may fail but system should handle it gracefully
- assertEquals([0, 1].includes(executeCode), true);
+ expect([0).toBe(1].includes(executeCode), true);
// Check task status to see retry attempts
const statusCommand = new Deno.Command(Deno.execPath(), {
@@ -666,7 +666,7 @@ describe('E2E Full Workflow', () => {
});
const { code: statusCode } = await statusCommand.output();
- assertEquals(statusCode, 0);
+ expect(statusCode).toBe(0);
// Create recovery task
const recoveryTaskCommand = new Deno.Command(Deno.execPath(), {
@@ -690,7 +690,7 @@ describe('E2E Full Workflow', () => {
const { stdout: recoveryOutput } = await recoveryTaskCommand.output();
const recoveryResult = new TextDecoder().decode(recoveryOutput);
const recoveryTaskId = recoveryResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(recoveryTaskId);
+ expect(recoveryTaskId).toBeDefined();
// Execute recovery task
const executeRecoveryCommand = new Deno.Command(Deno.execPath(), {
@@ -705,7 +705,7 @@ describe('E2E Full Workflow', () => {
});
const { code: recoveryCode } = await executeRecoveryCommand.output();
- assertEquals(recoveryCode, 0);
+ expect(recoveryCode).toBe(0);
// Check system health after error scenarios
const healthCommand = new Deno.Command(Deno.execPath(), {
@@ -720,7 +720,7 @@ describe('E2E Full Workflow', () => {
});
const { code: healthCode } = await healthCommand.output();
- assertEquals(healthCode, 0);
+ expect(healthCode).toBe(0);
} finally {
// Shutdown system
@@ -808,7 +808,7 @@ describe('E2E Full Workflow', () => {
const { stdout: agentOutput } = await agentCommand.output();
const agentResult = new TextDecoder().decode(agentOutput);
const agentId = agentResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(agentId);
+ expect(agentId).toBeDefined();
agentIds.push(agentId);
}
@@ -837,7 +837,7 @@ describe('E2E Full Workflow', () => {
const { stdout: taskOutput } = await taskCommand.output();
const taskResult = new TextDecoder().decode(taskOutput);
const taskId = taskResult.match(/"id":\s*"([^"]+)"/)?.[1];
- assertExists(taskId);
+ expect(taskId).toBeDefined();
taskIds.push(taskId);
}
@@ -881,7 +881,7 @@ describe('E2E Full Workflow', () => {
});
const { code: metricsCode, stdout: metricsOutput } = await metricsCommand.output();
- assertEquals(metricsCode, 0);
+ expect(metricsCode).toBe(0);
const metricsResult = new TextDecoder().decode(metricsOutput);
assertStringIncludes(metricsResult, 'System Status');
@@ -899,7 +899,7 @@ describe('E2E Full Workflow', () => {
});
const { code: memoryStatsCode } = await memoryStatsCommand.output();
- assertEquals(memoryStatsCode, 0);
+ expect(memoryStatsCode).toBe(0);
} finally {
// Shutdown system
diff --git a/tests/e2e/start-command-e2e.test.ts b/tests/e2e/start-command-e2e.test.ts
index 3401786cdb..d1761ae8d3 100644
--- a/tests/e2e/start-command-e2e.test.ts
+++ b/tests/e2e/start-command-e2e.test.ts
@@ -2,8 +2,8 @@
* End-to-end tests for the start command
*/
-import { assertEquals, assertExists } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { describe, it } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
describe('Start Command E2E', () => {
describe('JavaScript CLI', () => {
@@ -18,10 +18,10 @@ describe('Start Command E2E', () => {
const output = new TextDecoder().decode(stdout);
const error = new TextDecoder().decode(stderr);
- assertEquals(success, true);
- assertEquals(output.includes('--ui'), true);
- assertEquals(output.includes('Launch interactive process management UI'), true);
- assertEquals(output.includes('Process Management UI:'), true);
+ expect(success).toBe(true);
+ expect(output.includes('--ui')).toBe(true);
+ expect(output.includes('Launch interactive process management UI')).toBe(true);
+ expect(output.includes('Process Management UI:')).toBe(true);
});
it('should handle UI flag', async () => {
@@ -34,8 +34,8 @@ describe('Start Command E2E', () => {
const { stdout, stderr, success } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(success, true);
- assertEquals(output.includes('Launching interactive process management UI'), true);
+ expect(success).toBe(true);
+ expect(output.includes('Launching interactive process management UI')).toBe(true);
});
});
@@ -80,11 +80,11 @@ describe('Start Command E2E', () => {
await Deno.remove(tempFile);
- assertEquals(success, true);
- assertEquals(output.includes('PROCESSES:6'), true);
- assertEquals(output.includes('STATUS:running'), true);
- assertEquals(output.includes('STOPPED:stopped'), true);
- assertEquals(output.includes('STATS:6'), true);
+ expect(success).toBe(true);
+ expect(output.includes('PROCESSES:6')).toBe(true);
+ expect(output.includes('STATUS:running')).toBe(true);
+ expect(output.includes('STOPPED:stopped')).toBe(true);
+ expect(output.includes('STATS:6')).toBe(true);
});
});
@@ -124,10 +124,10 @@ describe('Start Command E2E', () => {
await Deno.remove(tempFile);
- assertEquals(success, true);
- assertEquals(output.includes('EVENTS:2'), true);
- assertEquals(output.includes('HAS_AGENT:true'), true);
- assertEquals(output.includes('HAS_TASK:true'), true);
+ expect(success).toBe(true);
+ expect(output.includes('EVENTS:2')).toBe(true);
+ expect(output.includes('HAS_AGENT:true')).toBe(true);
+ expect(output.includes('HAS_TASK:true')).toBe(true);
});
});
@@ -140,13 +140,13 @@ describe('Start Command E2E', () => {
});
const { stdout: daemonOut } = await daemonTest.output();
const daemonHelp = new TextDecoder().decode(daemonOut);
- assertEquals(daemonHelp.includes('--daemon'), true);
+ expect(daemonHelp.includes('--daemon')).toBe(true);
// Test port flag
- assertEquals(daemonHelp.includes('--port'), true);
+ expect(daemonHelp.includes('--port')).toBe(true);
// Test verbose flag
- assertEquals(daemonHelp.includes('--verbose'), true);
+ expect(daemonHelp.includes('--verbose')).toBe(true);
});
it('should maintain existing functionality', async () => {
@@ -168,13 +168,13 @@ describe('Start Command E2E', () => {
const { stdout, success } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(success, true);
- assertEquals(output.includes('Starting in daemon mode'), true);
- assertEquals(output.includes('Process ID:'), true);
+ expect(success).toBe(true);
+ expect(output.includes('Starting in daemon mode')).toBe(true);
+ expect(output.includes('Process ID:')).toBe(true);
// Check PID file was created
const pidExists = await Deno.stat('.claude-flow.pid').then(() => true).catch(() => false);
- assertEquals(pidExists, true);
+ expect(pidExists).toBe(true);
} finally {
Deno.chdir(originalCwd);
diff --git a/tests/e2e/workflow.test.ts b/tests/e2e/workflow.test.ts
index ed78907bdf..55869c6bb0 100644
--- a/tests/e2e/workflow.test.ts
+++ b/tests/e2e/workflow.test.ts
@@ -2,7 +2,7 @@
* End-to-end workflow tests
*/
-import { assertEquals } from 'https://deno.land/[email protected]/testing/asserts.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { delay } from '../../src/utils/helpers.ts';
Deno.test('E2E - CLI should show help', async () => {
@@ -15,9 +15,9 @@ Deno.test('E2E - CLI should show help', async () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
- assertEquals(output.includes('Claude-Flow: Advanced AI agent orchestration system'), true);
- assertEquals(output.includes('COMMANDS'), true);
+ expect(code).toBe(0);
+ expect(output.includes('Claude-Flow: Advanced AI agent orchestration system')).toBe(true);
+ expect(output.includes('COMMANDS')).toBe(true);
});
Deno.test('E2E - Config init should create file', async () => {
@@ -40,19 +40,19 @@ Deno.test('E2E - Config init should create file', async () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
- assertEquals(output.includes('Configuration file created'), true);
+ expect(code).toBe(0);
+ expect(output.includes('Configuration file created')).toBe(true);
// Verify file was created
const stat = await Deno.stat(testFile);
- assertEquals(stat.isFile, true);
+ expect(stat.isFile).toBe(true);
// Verify content is valid JSON
const content = await Deno.readTextFile(testFile);
const config = JSON.parse(content);
- assertEquals(typeof config.orchestrator, 'object');
- assertEquals(typeof config.terminal, 'object');
- assertEquals(typeof config.memory, 'object');
+ expect(typeof config.orchestrator).toBe('object');
+ expect(typeof config.terminal).toBe('object');
+ expect(typeof config.memory).toBe('object');
} finally {
// Cleanup
try {
@@ -82,11 +82,11 @@ Deno.test('E2E - Agent spawn command should create profile', async () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
- assertEquals(output.includes('Agent profile created'), true);
- assertEquals(output.includes('"name": "test-researcher"'), true);
- assertEquals(output.includes('"type": "researcher"'), true);
- assertEquals(output.includes('"priority": 5'), true);
+ expect(code).toBe(0);
+ expect(output.includes('Agent profile created')).toBe(true);
+ expect(output.includes('"name": "test-researcher"')).toBe(true);
+ expect(output.includes('"type": "researcher"')).toBe(true);
+ expect(output.includes('"priority": 5')).toBe(true);
});
Deno.test('E2E - Task create command should create task', async () => {
@@ -108,9 +108,9 @@ Deno.test('E2E - Task create command should create task', async () => {
const { code, stdout } = await command.output();
const output = new TextDecoder().decode(stdout);
- assertEquals(code, 0);
- assertEquals(output.includes('Task created'), true);
- assertEquals(output.includes('"type": "analysis"'), true);
- assertEquals(output.includes('"description": "Analyze the test results"'), true);
- assertEquals(output.includes('"priority": 10'), true);
+ expect(code).toBe(0);
+ expect(output.includes('Task created')).toBe(true);
+ expect(output.includes('"type": "analysis"')).toBe(true);
+ expect(output.includes('"description": "Analyze the test results"')).toBe(true);
+ expect(output.includes('"priority": 10')).toBe(true);
});
\ No newline at end of file
diff --git a/tests/integration/cli/init/e2e-workflow.test.ts b/tests/integration/cli/init/e2e-workflow.test.ts
index 7a122aa5cf..8e236d1f77 100644
--- a/tests/integration/cli/init/e2e-workflow.test.ts
+++ b/tests/integration/cli/init/e2e-workflow.test.ts
@@ -39,7 +39,7 @@ describe("End-to-End Init Workflow Tests", () => {
});
const initResult = await initCommand.output();
- assertEquals(initResult.success, true);
+ expect(initResult.success).toBe(true);
const initOutput = new TextDecoder().decode(initResult.stdout);
assertStringIncludes(initOutput, "initialized successfully");
@@ -57,7 +57,7 @@ describe("End-to-End Init Workflow Tests", () => {
];
for (const file of expectedFiles) {
- assertExists(await exists(join(testDir, file)));
+ expect(await exists(join(testDir, file).toBeDefined()));
}
const expectedDirs = [
@@ -74,7 +74,7 @@ describe("End-to-End Init Workflow Tests", () => {
];
for (const dir of expectedDirs) {
- assertExists(await exists(join(testDir, dir)));
+ expect(await exists(join(testDir, dir).toBeDefined()));
}
// Step 2: Test that local executable works
@@ -86,7 +86,7 @@ describe("End-to-End Init Workflow Tests", () => {
});
const helpResult = await helpCommand.output();
- assertEquals(helpResult.success, true);
+ expect(helpResult.success).toBe(true);
const helpOutput = new TextDecoder().decode(helpResult.stdout);
assertStringIncludes(helpOutput, "claude-flow");
@@ -120,15 +120,15 @@ describe("End-to-End Init Workflow Tests", () => {
});
const initResult = await initCommand.output();
- assertEquals(initResult.success, true);
+ expect(initResult.success).toBe(true);
const initOutput = new TextDecoder().decode(initResult.stdout);
assertStringIncludes(initOutput, "SPARC development environment");
// Verify SPARC structure
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// Step 2: Test SPARC commands
const sparcModesCommand = new Deno.Command(join(testDir, "claude-flow"), {
@@ -149,7 +149,7 @@ describe("End-to-End Init Workflow Tests", () => {
assertStringIncludes(claudeContent, "Test-Driven Development");
// Step 4: Verify slash commands directory
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
});
it("should handle project upgrade workflow", async () => {
@@ -187,10 +187,10 @@ describe("End-to-End Init Workflow Tests", () => {
});
const fullResult = await fullCommand.output();
- assertEquals(fullResult.success, true);
+ expect(fullResult.success).toBe(true);
const fullClaude = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(fullClaude.length > minimalClaude.length, true);
+ expect(fullClaude.length > minimalClaude.length).toBe(true);
assertStringIncludes(fullClaude, "## Project Overview");
// Step 3: Upgrade to SPARC project
@@ -209,11 +209,11 @@ describe("End-to-End Init Workflow Tests", () => {
});
const sparcResult = await sparcCommand.output();
- assertEquals(sparcResult.success, true);
+ expect(sparcResult.success).toBe(true);
const sparcClaude = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
assertStringIncludes(sparcClaude, "SPARC Development Environment");
- assertExists(await exists(join(testDir, ".roo")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
});
});
@@ -248,24 +248,24 @@ describe("End-to-End Init Workflow Tests", () => {
});
const result = await initCommand.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should not interfere with existing project files
- assertExists(await exists(join(testDir, "package.json")));
- assertExists(await exists(join(testDir, "index.js")));
- assertExists(await exists(join(testDir, "src/app.js")));
- assertExists(await exists(join(testDir, "tests/app.test.js")));
+ expect(await exists(join(testDir, "package.json").toBeDefined()));
+ expect(await exists(join(testDir, "index.js").toBeDefined()));
+ expect(await exists(join(testDir, "src/app.js").toBeDefined()));
+ expect(await exists(join(testDir, "tests/app.test.js").toBeDefined()));
// Should add Claude Flow files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
- assertExists(await exists(join(testDir, "claude-flow")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
+ expect(await exists(join(testDir, "claude-flow").toBeDefined()));
// Verify package.json is unchanged
const packageJson = JSON.parse(await Deno.readTextFile(join(testDir, "package.json")));
- assertEquals(packageJson.name, "test-project");
- assertEquals(packageJson.version, "1.0.0");
+ expect(packageJson.name).toBe("test-project");
+ expect(packageJson.version).toBe("1.0.0");
});
it("should initialize in Git repository", async () => {
@@ -315,16 +315,16 @@ describe("End-to-End Init Workflow Tests", () => {
});
const result = await initCommand.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should preserve git repository
- assertExists(await exists(join(testDir, ".git")));
- assertExists(await exists(join(testDir, "README.md")));
- assertExists(await exists(join(testDir, ".gitignore")));
+ expect(await exists(join(testDir, ".git").toBeDefined()));
+ expect(await exists(join(testDir, "README.md").toBeDefined()));
+ expect(await exists(join(testDir, ".gitignore").toBeDefined()));
// Should add Claude Flow files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
// Check git status
const gitStatusCommand = new Deno.Command("git", {
@@ -387,21 +387,21 @@ describe("End-to-End Init Workflow Tests", () => {
const result = await initCommand.output();
const endTime = performance.now();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should not take too long even with many files
- assertEquals(endTime - startTime < 30000, true);
+ expect(endTime - startTime < 30000).toBe(true);
// Should preserve all existing structure
for (const dir of projectStructure) {
- assertExists(await exists(join(testDir, dir)));
- assertExists(await exists(join(testDir, dir, "index.js")));
+ expect(await exists(join(testDir, dir).toBeDefined()));
+ expect(await exists(join(testDir, dir, "index.js").toBeDefined()));
}
// Should add Claude Flow files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
console.log(`Large project init completed in ${(endTime - startTime).toFixed(2)}ms`);
});
@@ -491,8 +491,8 @@ describe("End-to-End Init Workflow Tests", () => {
assertStringIncludes(output, "--sparc");
// Should not create any files
- assertEquals(await exists(join(testDir, "CLAUDE.md")), false);
- assertEquals(await exists(join(testDir, "memory-bank.md")), false);
+ expect(await exists(join(testDir).toBe("CLAUDE.md")), false);
+ expect(await exists(join(testDir).toBe("memory-bank.md")), false);
});
it("should handle error scenarios gracefully", async () => {
@@ -520,7 +520,7 @@ describe("End-to-End Init Workflow Tests", () => {
console.log("Standard output:", output);
// Should not leave the system in a bad state
- assertEquals(await exists(join(testDir, "memory")), true); // Original file should remain
+ expect(await exists(join(testDir).toBe("memory")), true); // Original file should remain
});
});
});
\ No newline at end of file
diff --git a/tests/integration/cli/init/full-init-flow.test.ts b/tests/integration/cli/init/full-init-flow.test.ts
index 7034894dce..2c46fdf851 100644
--- a/tests/integration/cli/init/full-init-flow.test.ts
+++ b/tests/integration/cli/init/full-init-flow.test.ts
@@ -47,18 +47,18 @@ describe("Full Init Flow Integration Tests", () => {
}
// Check that key files were created
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
- assertExists(await exists(join(testDir, "memory/claude-flow-data.json")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory/claude-flow-data.json").toBeDefined()));
// Check directory structure
- assertExists(await exists(join(testDir, "memory")));
- assertExists(await exists(join(testDir, "memory/agents")));
- assertExists(await exists(join(testDir, "memory/sessions")));
- assertExists(await exists(join(testDir, "coordination")));
- assertExists(await exists(join(testDir, ".claude")));
- assertExists(await exists(join(testDir, ".claude/commands")));
+ expect(await exists(join(testDir, "memory").toBeDefined()));
+ expect(await exists(join(testDir, "memory/agents").toBeDefined()));
+ expect(await exists(join(testDir, "memory/sessions").toBeDefined()));
+ expect(await exists(join(testDir, "coordination").toBeDefined()));
+ expect(await exists(join(testDir, ".claude").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands").toBeDefined()));
});
it("should handle project with existing files", async () => {
@@ -87,7 +87,7 @@ describe("Full Init Flow Integration Tests", () => {
// Should not overwrite without force
const existingContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(existingContent, "existing content");
+ expect(existingContent).toBe("existing content");
});
it("should handle force overwrite correctly", async () => {
@@ -109,15 +109,15 @@ describe("Full Init Flow Integration Tests", () => {
});
const result = await command.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should overwrite files
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(claudeContent.includes("old content"), false);
+ expect(claudeContent.includes("old content")).toBe(false);
assertStringIncludes(claudeContent, "Claude Code Configuration");
const memoryContent = await Deno.readTextFile(join(testDir, "memory-bank.md"));
- assertEquals(memoryContent.includes("old memory"), false);
+ expect(memoryContent.includes("old memory")).toBe(false);
assertStringIncludes(memoryContent, "Memory Bank");
});
});
@@ -141,9 +141,9 @@ describe("Full Init Flow Integration Tests", () => {
const output = new TextDecoder().decode(result.stdout);
// Should create SPARC structure
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// Should have SPARC-enhanced CLAUDE.md
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
@@ -171,7 +171,7 @@ describe("Full Init Flow Integration Tests", () => {
});
const result = await command.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should preserve existing .roomodes (as per manual creation logic)
const roomodesContent = await Deno.readTextFile(join(testDir, ".roomodes"));
@@ -195,12 +195,12 @@ describe("Full Init Flow Integration Tests", () => {
});
const result = await command.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should create basic files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
// Content should be minimal
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
@@ -233,15 +233,15 @@ describe("Full Init Flow Integration Tests", () => {
});
const result = await command.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should create SPARC structure
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
// Should overwrite CLAUDE.md with SPARC content
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(claudeContent.includes("conflicting"), false);
+ expect(claudeContent.includes("conflicting")).toBe(false);
assertStringIncludes(claudeContent, "SPARC Development Environment");
// Memory should be minimal
@@ -271,9 +271,9 @@ describe("Full Init Flow Integration Tests", () => {
const dataContent = await Deno.readTextFile(dataPath);
const data = JSON.parse(dataContent);
- assertEquals(Array.isArray(data.agents), true);
- assertEquals(Array.isArray(data.tasks), true);
- assertEquals(typeof data.lastUpdated, "number");
+ expect(Array.isArray(data.agents)).toBe(true);
+ expect(Array.isArray(data.tasks)).toBe(true);
+ expect(typeof data.lastUpdated).toBe("number");
});
it("should create valid SPARC JSON files", async () => {
@@ -330,8 +330,8 @@ describe("Full Init Flow Integration Tests", () => {
for (const file of mdFiles) {
const content = await Deno.readTextFile(join(testDir, file));
- assertEquals(content.startsWith("#"), true);
- assertEquals(content.includes("\r"), false); // No Windows line endings
+ expect(content.startsWith("#")).toBe(true);
+ expect(content.includes("\r")).toBe(false); // No Windows line endings
}
});
});
@@ -353,12 +353,12 @@ describe("Full Init Flow Integration Tests", () => {
await command.output();
// Check executable was created
- assertExists(await exists(join(testDir, "claude-flow")));
+ expect(await exists(join(testDir, "claude-flow").toBeDefined()));
// Check it's executable (on Unix-like systems)
try {
const fileInfo = await Deno.stat(join(testDir, "claude-flow"));
- assertEquals(fileInfo.isFile, true);
+ expect(fileInfo.isFile).toBe(true);
} catch {
// May not work on all systems
}
@@ -416,9 +416,9 @@ describe("Full Init Flow Integration Tests", () => {
await command.output();
// Files should be created in subDir
- assertExists(await exists(join(subDir, "CLAUDE.md")));
- assertExists(await exists(join(subDir, "memory-bank.md")));
- assertExists(await exists(join(subDir, "coordination.md")));
+ expect(await exists(join(subDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(subDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(subDir, "coordination.md").toBeDefined()));
});
it("should handle directory changes correctly", async () => {
@@ -441,9 +441,9 @@ describe("Full Init Flow Integration Tests", () => {
await command.output();
// Files should be in nested directory
- assertExists(await exists(join(nestedDir, "CLAUDE.md")));
- assertExists(await exists(join(nestedDir, "memory")));
- assertExists(await exists(join(nestedDir, "coordination")));
+ expect(await exists(join(nestedDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(nestedDir, "memory").toBeDefined()));
+ expect(await exists(join(nestedDir, "coordination").toBeDefined()));
});
});
});
\ No newline at end of file
diff --git a/tests/integration/cli/init/selective-modes.test.ts b/tests/integration/cli/init/selective-modes.test.ts
index 79957ea384..1582e8735f 100644
--- a/tests/integration/cli/init/selective-modes.test.ts
+++ b/tests/integration/cli/init/selective-modes.test.ts
@@ -66,13 +66,13 @@ describe("Selective Mode Initialization Tests", () => {
const standardClaude = await Deno.readTextFile(join(standardDir, "CLAUDE.md"));
const minimalClaude = await Deno.readTextFile(join(minimalDir, "CLAUDE.md"));
- assertEquals(standardClaude.length > minimalClaude.length, true);
+ expect(standardClaude.length > minimalClaude.length).toBe(true);
assertStringIncludes(minimalClaude, "Minimal project configuration");
const standardMemory = await Deno.readTextFile(join(standardDir, "memory-bank.md"));
const minimalMemory = await Deno.readTextFile(join(minimalDir, "memory-bank.md"));
- assertEquals(standardMemory.length > minimalMemory.length, true);
+ expect(standardMemory.length > minimalMemory.length).toBe(true);
assertStringIncludes(minimalMemory, "Simple memory tracking");
});
@@ -113,7 +113,7 @@ describe("Selective Mode Initialization Tests", () => {
for (const mode of dirs) {
for (const dir of expectedDirs) {
- assertExists(await exists(join(testDir, mode, dir)));
+ expect(await exists(join(testDir, mode, dir).toBeDefined()));
}
}
});
@@ -159,19 +159,19 @@ describe("Selective Mode Initialization Tests", () => {
await sparcCommand.output();
// Check SPARC-specific files
- assertEquals(await exists(join(regularDir, ".roo")), false);
- assertEquals(await exists(join(regularDir, ".roomodes")), false);
- assertEquals(await exists(join(regularDir, ".claude/commands/sparc")), false);
+ expect(await exists(join(regularDir).toBe(".roo")), false);
+ expect(await exists(join(regularDir).toBe(".roomodes")), false);
+ expect(await exists(join(regularDir).toBe(".claude/commands/sparc")), false);
- assertExists(await exists(join(sparcDir, ".roo")));
- assertExists(await exists(join(sparcDir, ".roomodes")));
- assertExists(await exists(join(sparcDir, ".claude/commands/sparc")));
+ expect(await exists(join(sparcDir, ".roo").toBeDefined()));
+ expect(await exists(join(sparcDir, ".roomodes").toBeDefined()));
+ expect(await exists(join(sparcDir, ".claude/commands/sparc").toBeDefined()));
// Check CLAUDE.md content differences
const regularClaude = await Deno.readTextFile(join(regularDir, "CLAUDE.md"));
const sparcClaude = await Deno.readTextFile(join(sparcDir, "CLAUDE.md"));
- assertEquals(regularClaude.includes("SPARC Development Environment"), false);
+ expect(regularClaude.includes("SPARC Development Environment")).toBe(false);
assertStringIncludes(sparcClaude, "SPARC Development Environment");
assertStringIncludes(sparcClaude, "## SPARC Development Commands");
});
@@ -202,15 +202,15 @@ describe("Selective Mode Initialization Tests", () => {
];
for (const dir of sparcDirs) {
- assertExists(await exists(join(testDir, dir)));
+ expect(await exists(join(testDir, dir).toBeDefined()));
}
// Check Claude commands
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// Check workflow files
- assertExists(await exists(join(testDir, ".roo/workflows/basic-tdd.json")));
- assertExists(await exists(join(testDir, ".roo/README.md")));
+ expect(await exists(join(testDir, ".roo/workflows/basic-tdd.json").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/README.md").toBeDefined()));
});
});
@@ -233,9 +233,9 @@ describe("Selective Mode Initialization Tests", () => {
await command.output();
// Should have SPARC structure
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// Should have SPARC-enhanced CLAUDE.md (SPARC overrides minimal for CLAUDE.md)
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
@@ -290,9 +290,9 @@ describe("Selective Mode Initialization Tests", () => {
const sparcMinimalClaude = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
// SPARC version should be different from minimal-only
- assertEquals(minimalClaude === sparcMinimalClaude, false);
+ expect(minimalClaude === sparcMinimalClaude).toBe(false);
assertStringIncludes(sparcMinimalClaude, "SPARC Development Environment");
- assertEquals(minimalClaude.includes("SPARC Development Environment"), false);
+ expect(minimalClaude.includes("SPARC Development Environment")).toBe(false);
});
});
@@ -337,10 +337,10 @@ describe("Selective Mode Initialization Tests", () => {
const fullMemory = await Deno.readTextFile(join(testDir, "memory-bank.md"));
// Should be different and longer
- assertEquals(minimalClaude === fullClaude, false);
- assertEquals(minimalMemory === fullMemory, false);
- assertEquals(fullClaude.length > minimalClaude.length, true);
- assertEquals(fullMemory.length > minimalMemory.length, true);
+ expect(minimalClaude === fullClaude).toBe(false);
+ expect(minimalMemory === fullMemory).toBe(false);
+ expect(fullClaude.length > minimalClaude.length).toBe(true);
+ expect(fullMemory.length > minimalMemory.length).toBe(true);
});
it("should support adding SPARC to existing project", async () => {
@@ -360,8 +360,8 @@ describe("Selective Mode Initialization Tests", () => {
await regularCommand.output();
// Verify no SPARC files
- assertEquals(await exists(join(testDir, ".roo")), false);
- assertEquals(await exists(join(testDir, ".roomodes")), false);
+ expect(await exists(join(testDir).toBe(".roo")), false);
+ expect(await exists(join(testDir).toBe(".roomodes")), false);
// Add SPARC with force
const sparcCommand = new Deno.Command("deno", {
@@ -381,9 +381,9 @@ describe("Selective Mode Initialization Tests", () => {
await sparcCommand.output();
// Should now have SPARC files
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// CLAUDE.md should be SPARC-enhanced
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
@@ -414,9 +414,9 @@ describe("Selective Mode Initialization Tests", () => {
const coordContent = await Deno.readTextFile(join(testDir, "coordination.md"));
// Minimal files should be under reasonable size limits
- assertEquals(claudeContent.length < 5000, true); // Should be much smaller than full
- assertEquals(memoryContent.length < 2000, true);
- assertEquals(coordContent.length < 2000, true);
+ expect(claudeContent.length < 5000).toBe(true); // Should be much smaller than full
+ expect(memoryContent.length < 2000).toBe(true);
+ expect(coordContent.length < 2000).toBe(true);
// But should still have basic structure
assertStringIncludes(claudeContent, "# Claude Code Configuration");
@@ -465,10 +465,10 @@ describe("Selective Mode Initialization Tests", () => {
const roomodesContent = await Deno.readTextFile(join(testDir, ".roomodes"));
const roomodesData = JSON.parse(roomodesContent);
- assertEquals(typeof roomodesData.modes, "object");
- assertExists(roomodesData.modes.architect);
- assertExists(roomodesData.modes.tdd);
- assertExists(roomodesData.modes.code);
+ expect(typeof roomodesData.modes).toBe("object");
+ expect(roomodesData.modes.architect).toBeDefined();
+ expect(roomodesData.modes.tdd).toBeDefined();
+ expect(roomodesData.modes.code).toBeDefined();
}
});
});
diff --git a/tests/integration/enhanced-repl.test.ts b/tests/integration/enhanced-repl.test.ts
index 7a1a574f7f..481a88d0d6 100644
--- a/tests/integration/enhanced-repl.test.ts
+++ b/tests/integration/enhanced-repl.test.ts
@@ -2,8 +2,8 @@
* Integration tests for the Enhanced REPL
*/
-import { assertEquals, assertExists, assertStringIncludes } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { describe, it, beforeEach, afterEach } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
// Mock implementations for testing
class MockInput {
@@ -80,25 +80,25 @@ describe('Enhanced REPL Integration Tests', () => {
varManager.set('tempVar', 'temporary', 'temporary');
// Check values
- assertEquals(varManager.get('testString'), 'Hello World');
- assertEquals(varManager.get('testNumber'), 42);
- assertEquals(varManager.get('testObject').key, 'value');
- assertEquals(varManager.has('testString'), true);
- assertEquals(varManager.has('nonexistent'), false);
+ expect(varManager.get('testString')).toBe('Hello World');
+ expect(varManager.get('testNumber')).toBe(42);
+ expect(varManager.get('testObject').key).toBe('value');
+ expect(varManager.has('testString')).toBe(true);
+ expect(varManager.has('nonexistent')).toBe(false);
// Check persistence (temporary variables should not be saved)
const variables = varManager.list();
- assertEquals(variables.length, 3); // Excludes temporary
- assertEquals(variables.some(v => v.name === 'tempVar'), false);
+ expect(variables.length).toBe(3); // Excludes temporary
+ expect(variables.some(v => v.name === 'tempVar')).toBe(false);
// Test scoped listing
const sessionVars = varManager.list('session');
- assertEquals(sessionVars.length, 2);
- assertEquals(sessionVars.every(v => v.scope === 'session'), true);
+ expect(sessionVars.length).toBe(2);
+ expect(sessionVars.every(v => v.scope === 'session')).toBe(true);
const globalVars = varManager.list('global');
- assertEquals(globalVars.length, 1);
- assertEquals(globalVars[0].name, 'testNumber');
+ expect(globalVars.length).toBe(1);
+ expect(globalVars[0].name).toBe('testNumber');
});
it('should handle variable deletion', async () => {
@@ -110,17 +110,17 @@ describe('Enhanced REPL Integration Tests', () => {
varManager.set('var2', 'value2');
varManager.set('var3', 'value3');
- assertEquals(varManager.list().length, 3);
+ expect(varManager.list().length).toBe(3);
// Delete individual variable
- assertEquals(varManager.delete('var1'), true);
- assertEquals(varManager.delete('nonexistent'), false);
- assertEquals(varManager.list().length, 2);
- assertEquals(varManager.has('var1'), false);
+ expect(varManager.delete('var1')).toBe(true);
+ expect(varManager.delete('nonexistent')).toBe(false);
+ expect(varManager.list().length).toBe(2);
+ expect(varManager.has('var1')).toBe(false);
// Clear all variables
varManager.clear();
- assertEquals(varManager.list().length, 0);
+ expect(varManager.list().length).toBe(0);
});
it('should handle scope-based clearing', async () => {
@@ -132,16 +132,16 @@ describe('Enhanced REPL Integration Tests', () => {
varManager.set('globalVar', 'value', 'global');
varManager.set('tempVar', 'value', 'temporary');
- assertEquals(varManager.list().length, 3);
+ expect(varManager.list().length).toBe(3);
// Clear only session variables
varManager.clear('session');
const remaining = varManager.list();
- assertEquals(remaining.length, 2);
- assertEquals(remaining.some(v => v.scope === 'session'), false);
- assertEquals(remaining.some(v => v.scope === 'global'), true);
- assertEquals(remaining.some(v => v.scope === 'temporary'), true);
+ expect(remaining.length).toBe(2);
+ expect(remaining.some(v => v.scope === 'session')).toBe(false);
+ expect(remaining.some(v => v.scope === 'global')).toBe(true);
+ expect(remaining.some(v => v.scope === 'temporary')).toBe(true);
});
});
@@ -155,26 +155,26 @@ describe('Enhanced REPL Integration Tests', () => {
const session1Id = sessionManager.createSession('Test Session 1');
const session2Id = sessionManager.createSession('Test Session 2');
- assertExists(session1Id);
- assertExists(session2Id);
- assertEquals(session1Id !== session2Id, true);
+ expect(session1Id).toBeDefined();
+ expect(session2Id).toBeDefined();
+ expect(session1Id !== session2Id).toBe(true);
// List sessions
const sessions = sessionManager.listSessions();
- assertEquals(sessions.length, 2);
- assertEquals(sessions.some(s => s.name === 'Test Session 1'), true);
- assertEquals(sessions.some(s => s.name === 'Test Session 2'), true);
+ expect(sessions.length).toBe(2);
+ expect(sessions.some(s => s.name === 'Test Session 1')).toBe(true);
+ expect(sessions.some(s => s.name === 'Test Session 2')).toBe(true);
// Load session
const loadedSession = sessionManager.loadSession(session1Id);
- assertExists(loadedSession);
- assertEquals(loadedSession!.name, 'Test Session 1');
- assertEquals(sessionManager.getCurrentSession()!.id, session1Id);
+ expect(loadedSession).toBeDefined();
+ expect(loadedSession!.name).toBe('Test Session 1');
+ expect(sessionManager.getCurrentSession()!.id).toBe(session1Id);
// Delete session
- assertEquals(sessionManager.deleteSession(session2Id), true);
- assertEquals(sessionManager.deleteSession('nonexistent'), false);
- assertEquals(sessionManager.listSessions().length, 1);
+ expect(sessionManager.deleteSession(session2Id)).toBe(true);
+ expect(sessionManager.deleteSession('nonexistent')).toBe(false);
+ expect(sessionManager.listSessions().length).toBe(1);
});
it('should handle session persistence', async () => {
@@ -193,10 +193,10 @@ describe('Enhanced REPL Integration Tests', () => {
// Should load persisted sessions
const sessions = sessionManager2.listSessions();
- assertEquals(sessions.length, 1);
- assertEquals(sessions[0].name, 'Persistent Session');
- assertEquals(sessions[0].history.length, 2);
- assertEquals(sessions[0].variables.has('testVar'), true);
+ expect(sessions.length).toBe(1);
+ expect(sessions[0].name).toBe('Persistent Session');
+ expect(sessions[0].history.length).toBe(2);
+ expect(sessions[0].variables.has('testVar')).toBe(true);
});
});
@@ -211,35 +211,35 @@ describe('Enhanced REPL Integration Tests', () => {
debugManager.addBreakpoint('condition-check');
let breakpoints = debugManager.listBreakpoints();
- assertEquals(breakpoints.length, 3);
- assertEquals(breakpoints.includes('task-001'), true);
+ expect(breakpoints.length).toBe(3);
+ expect(breakpoints.includes('task-001')).toBe(true);
- assertEquals(debugManager.removeBreakpoint('task-001'), true);
- assertEquals(debugManager.removeBreakpoint('nonexistent'), false);
+ expect(debugManager.removeBreakpoint('task-001')).toBe(true);
+ expect(debugManager.removeBreakpoint('nonexistent')).toBe(false);
breakpoints = debugManager.listBreakpoints();
- assertEquals(breakpoints.length, 2);
- assertEquals(breakpoints.includes('task-001'), false);
+ expect(breakpoints.length).toBe(2);
+ expect(breakpoints.includes('task-001')).toBe(false);
// Watch expressions
debugManager.addWatch('status', 'variables.currentStatus');
debugManager.addWatch('progress', 'task.progress.percentage');
const watches = debugManager.listWatches();
- assertEquals(watches.size, 2);
- assertEquals(watches.get('status'), 'variables.currentStatus');
- assertEquals(watches.get('progress'), 'task.progress.percentage');
+ expect(watches.size).toBe(2);
+ expect(watches.get('status')).toBe('variables.currentStatus');
+ expect(watches.get('progress')).toBe('task.progress.percentage');
- assertEquals(debugManager.removeWatch('status'), true);
- assertEquals(debugManager.removeWatch('nonexistent'), false);
- assertEquals(debugManager.listWatches().size, 1);
+ expect(debugManager.removeWatch('status')).toBe(true);
+ expect(debugManager.removeWatch('nonexistent')).toBe(false);
+ expect(debugManager.listWatches().size).toBe(1);
// Step mode
- assertEquals(debugManager.isStepMode(), false);
+ expect(debugManager.isStepMode()).toBe(false);
debugManager.enableStepMode();
- assertEquals(debugManager.isStepMode(), true);
+ expect(debugManager.isStepMode()).toBe(true);
debugManager.disableStepMode();
- assertEquals(debugManager.isStepMode(), false);
+ expect(debugManager.isStepMode()).toBe(false);
});
it('should manage call stack', async () => {
@@ -267,16 +267,16 @@ describe('Enhanced REPL Integration Tests', () => {
debugManager.pushFrame(frame2);
let stack = debugManager.getCallStack();
- assertEquals(stack.length, 2);
- assertEquals(stack[1].name, 'task-001'); // Most recent frame
+ expect(stack.length).toBe(2);
+ expect(stack[1].name).toBe('task-001'); // Most recent frame
// Pop frame
const poppedFrame = debugManager.popFrame();
- assertEquals(poppedFrame!.name, 'task-001');
+ expect(poppedFrame!.name).toBe('task-001');
stack = debugManager.getCallStack();
- assertEquals(stack.length, 1);
- assertEquals(stack[0].name, 'workflow-main');
+ expect(stack.length).toBe(1);
+ expect(stack[0].name).toBe('workflow-main');
});
});
@@ -285,24 +285,24 @@ describe('Enhanced REPL Integration Tests', () => {
const { MultiLineEditor } = await import('../../package/src/cli/enhanced-repl.ts');
const editor = new (MultiLineEditor as any)();
- assertEquals(editor.isActive(), false);
+ expect(editor.isActive()).toBe(false);
editor.startEdit('const data = {');
- assertEquals(editor.isActive(), true);
+ expect(editor.isActive()).toBe(true);
editor.addLine(' name: "test",');
editor.addLine(' value: 42');
editor.addLine('};');
const content = editor.getContent();
- assertEquals(content.includes('const data = {'), true);
- assertEquals(content.includes('name: "test"'), true);
- assertEquals(content.includes('value: 42'), true);
- assertEquals(content.includes('};'), true);
+ expect(content.includes('const data = {')).toBe(true);
+ expect(content.includes('name: "test"')).toBe(true);
+ expect(content.includes('value: 42')).toBe(true);
+ expect(content.includes('};')).toBe(true);
editor.clear();
- assertEquals(editor.isActive(), false);
- assertEquals(editor.getContent(), '');
+ expect(editor.isActive()).toBe(false);
+ expect(editor.getContent()).toBe('');
});
it('should handle initial content', async () => {
@@ -313,11 +313,11 @@ describe('Enhanced REPL Integration Tests', () => {
editor.startEdit(initialContent);
const content = editor.getContent();
- assertEquals(content, initialContent);
+ expect(content).toBe(initialContent);
editor.addLine('// Additional line');
const updatedContent = editor.getContent();
- assertEquals(updatedContent.includes('// Additional line'), true);
+ expect(updatedContent.includes('// Additional line')).toBe(true);
});
});
@@ -329,27 +329,27 @@ describe('Enhanced REPL Integration Tests', () => {
// Simple command
let parsed = parseEnhancedCommand('help');
- assertEquals(parsed, ['help']);
+ expect(parsed).toBe(['help']);
// Command with arguments
parsed = parseEnhancedCommand('let name = "John Doe"');
- assertEquals(parsed, ['let', 'name', '=', 'John Doe']);
+ expect(parsed).toBe(['let', 'name', '=', 'John Doe']);
// Command with single quotes
parsed = parseEnhancedCommand("set greeting = 'Hello World'");
- assertEquals(parsed, ['set', 'greeting', '=', 'Hello World']);
+ expect(parsed).toBe(['set', 'greeting', '=', 'Hello World']);
// Command with escaped quotes
parsed = parseEnhancedCommand('echo "He said \\"Hello\\""');
- assertEquals(parsed, ['echo', 'He said "Hello"']);
+ expect(parsed).toBe(['echo', 'He said "Hello"']);
// Command with multiple spaces
parsed = parseEnhancedCommand('workflow run test.yaml');
- assertEquals(parsed, ['workflow', 'run', 'test.yaml']);
+ expect(parsed).toBe(['workflow', 'run', 'test.yaml']);
// Complex JSON assignment
parsed = parseEnhancedCommand('let config = {"timeout": 5000, "retries": 3}');
- assertEquals(parsed, ['let', 'config', '=', '{"timeout": 5000, "retries": 3}']);
+ expect(parsed).toBe(['let', 'config', '=', '{"timeout": 5000, "retries": 3}']);
});
});
@@ -370,25 +370,25 @@ describe('Enhanced REPL Integration Tests', () => {
// Basic command completion
let completions = getCompletions('hel', mockContext, mockVarManager);
- assertEquals(completions.includes('help'), true);
+ expect(completions.includes('help')).toBe(true);
completions = getCompletions('deb', mockContext, mockVarManager);
- assertEquals(completions.includes('debug'), true);
+ expect(completions.includes('debug')).toBe(true);
// Variable name completion
completions = getCompletions('get api', mockContext, mockVarManager);
- assertEquals(completions.includes('apiKey'), true);
+ expect(completions.includes('apiKey')).toBe(true);
completions = getCompletions('var con', mockContext, mockVarManager);
- assertEquals(completions.includes('config'), true);
+ expect(completions.includes('config')).toBe(true);
// Session subcommand completion
completions = getCompletions('session s', mockContext, mockVarManager);
- assertEquals(completions.includes('save'), true);
+ expect(completions.includes('save')).toBe(true);
completions = getCompletions('session l', mockContext, mockVarManager);
- assertEquals(completions.includes('list'), true);
- assertEquals(completions.includes('load'), true);
+ expect(completions.includes('list')).toBe(true);
+ expect(completions.includes('load')).toBe(true);
});
});
@@ -403,7 +403,7 @@ describe('Enhanced REPL Integration Tests', () => {
varManager.set('test', 'value');
// Variable should still work in memory
- assertEquals(varManager.get('test'), 'value');
+ expect(varManager.get('test')).toBe('value');
});
it('should handle invalid JSON gracefully', async () => {
@@ -414,11 +414,11 @@ describe('Enhanced REPL Integration Tests', () => {
// Should not crash, just start with empty state
const varManager = new (VariableManager as any)(corruptFile);
- assertEquals(varManager.list().length, 0);
+ expect(varManager.list().length).toBe(0);
// Should still work normally
varManager.set('test', 'value');
- assertEquals(varManager.get('test'), 'value');
+ expect(varManager.get('test')).toBe('value');
});
});
@@ -442,11 +442,11 @@ describe('Enhanced REPL Integration Tests', () => {
// Mock workflow engine
const mockEngine = {
loadWorkflow: async (path: string) => {
- assertEquals(path, workflowFile);
+ expect(path).toBe(workflowFile);
return workflow;
},
executeWorkflow: async (wf: any) => {
- assertEquals(wf.name, 'REPL Test Workflow');
+ expect(wf.name).toBe('REPL Test Workflow');
return {
id: 'test-execution-001',
workflowName: wf.name,
@@ -470,7 +470,7 @@ describe('Enhanced REPL Integration Tests', () => {
await handleWorkflowCommand(['run', workflowFile], mockContext, mockEngine);
// Verify workflow was executed
- assertEquals(mockContext.activeWorkflows.size, 1);
+ expect(mockContext.activeWorkflows.size).toBe(1);
});
});
});
\ No newline at end of file
diff --git a/tests/integration/full-system.test.ts b/tests/integration/full-system.test.ts
index 6f4ec3e323..607b2902bb 100644
--- a/tests/integration/full-system.test.ts
+++ b/tests/integration/full-system.test.ts
@@ -248,8 +248,8 @@ function solution() {
};
const researchResult = await orchestrator.executeTask(researchTask);
- assertEquals(researchResult.status, 'completed');
- assertExists(researchResult.output);
+ expect(researchResult.status).toBe('completed');
+ expect(researchResult.output).toBeDefined();
// Step 2: Implementation task (depends on research)
const implementTask: Task = {
@@ -272,8 +272,8 @@ function solution() {
};
const implementResult = await orchestrator.executeTask(implementTask);
- assertEquals(implementResult.status, 'completed');
- assertExists(implementResult.output);
+ expect(implementResult.status).toBe('completed');
+ expect(implementResult.output).toBeDefined();
// Verify memory contains both research and implementation
const allMemories = await memoryManager.queryEntries({
@@ -287,10 +287,10 @@ function solution() {
m.type === 'artifact' && m.tags.includes('implementation')
);
- assertEquals(researchMemories.length, 1);
- assertEquals(implementMemories.length, 1);
- assertEquals(researchMemories[0].agentId, researcherProfile.id);
- assertEquals(implementMemories[0].agentId, implementerProfile.id);
+ expect(researchMemories.length).toBe(1);
+ expect(implementMemories.length).toBe(1);
+ expect(researchMemories[0].agentId).toBe(researcherProfile.id);
+ expect(implementMemories[0].agentId).toBe(implementerProfile.id);
});
it('should handle complex multi-agent coordination scenario', async () => {
@@ -433,7 +433,7 @@ function solution() {
// All coordination tasks should complete
coordinationResults.forEach(result => {
- assertEquals(result.status, 'completed');
+ expect(result.status).toBe('completed');
});
// Workers report their status
@@ -462,11 +462,11 @@ function solution() {
// All status reports should complete
statusResults.forEach(result => {
- assertEquals(result.status, 'completed');
+ expect(result.status).toBe('completed');
});
// Verify coordination messages were sent
- assertEquals(coordinationManager.sendMessage.calls.length, 3);
+ expect(coordinationManager.sendMessage.calls.length).toBe(3);
// Verify status was stored in memory
const statusMemories = await memoryManager.queryEntries({
@@ -474,10 +474,10 @@ function solution() {
limit: 10,
});
- assertEquals(statusMemories.length, 3);
+ expect(statusMemories.length).toBe(3);
statusMemories.forEach((memory, index) => {
- assertEquals(memory.agentId, `worker-${index + 1}`);
- assertEquals(memory.context.progress, (index + 1) * 25);
+ expect(memory.agentId).toBe(`worker-${index + 1}`);
+ expect(memory.context.progress).toBe((index + 1) * 25);
});
});
@@ -530,7 +530,7 @@ function solution() {
stressAgents.map(agent => orchestrator.spawnAgent(agent))
);
- assertEquals(stressSessions.length, 5);
+ expect(stressSessions.length).toBe(5);
// Create many concurrent heavy tasks
const heavyTasks = stressAgents.flatMap((agent, agentIndex) =>
@@ -561,24 +561,24 @@ function solution() {
const duration = Date.now() - startTime;
// Verify all tasks completed
- assertEquals(results.length, 15); // 5 agents Γ— 3 tasks
+ expect(results.length).toBe(15); // 5 agents Γ— 3 tasks
results.forEach(result => {
- assertEquals(result.status, 'completed');
+ expect(result.status).toBe('completed');
});
// System should handle the load reasonably well
- assertEquals(duration < 30000, true); // Should complete within 30 seconds
+ expect(duration < 30000).toBe(true); // Should complete within 30 seconds
// Check system health after stress test
const orchestratorHealth = await orchestrator.getHealthStatus();
- assertEquals(orchestratorHealth.healthy, true);
+ expect(orchestratorHealth.healthy).toBe(true);
const terminalHealth = await terminalManager.getHealthStatus();
- assertEquals(terminalHealth.healthy, true);
+ expect(terminalHealth.healthy).toBe(true);
// Verify all agents are still active
const activeSessions = orchestrator.getActiveSessions();
- assertEquals(activeSessions.length, 5);
+ expect(activeSessions.length).toBe(5);
});
});
@@ -651,12 +651,12 @@ function solution() {
const successfulTasks = results.filter(r => r.status === 'completed');
const failedTasks = results.filter(r => r.status === 'failed');
- assertEquals(successfulTasks.length > 0, true);
- assertEquals(results.length, 10);
+ expect(successfulTasks.length > 0).toBe(true);
+ expect(results.length).toBe(10);
// System should still be healthy
const health = await orchestrator.getHealthStatus();
- assertEquals(health.healthy, true);
+ expect(health.healthy).toBe(true);
});
it('should handle memory conflicts and coordination deadlocks', async () => {
@@ -767,17 +767,17 @@ function solution() {
// All tasks should complete (conflicts resolved)
results.forEach(result => {
- assertEquals(result.status, 'completed');
+ expect(result.status).toBe('completed');
});
// Final entry should exist with one of the values
const finalEntry = await memoryManager.getEntry(sharedEntryId);
- assertExists(finalEntry);
- assertEquals(finalEntry.version >= 1, true);
+ expect(finalEntry).toBeDefined();
+ expect(finalEntry.version >= 1).toBe(true);
// Verify coordination prevented deadlocks
- assertEquals(coordinationManager.acquireResource.calls.length, 3);
- assertEquals(coordinationManager.releaseResource.calls.length, 3);
+ expect(coordinationManager.acquireResource.calls.length).toBe(3);
+ expect(coordinationManager.releaseResource.calls.length).toBe(3);
});
});
@@ -843,22 +843,22 @@ function solution() {
const finalMetrics = await orchestrator.getMetrics();
// Verify metrics structure
- assertExists(finalMetrics.uptime);
- assertExists(finalMetrics.totalAgents);
- assertExists(finalMetrics.activeAgents);
- assertExists(finalMetrics.totalTasks);
- assertExists(finalMetrics.completedTasks);
- assertExists(finalMetrics.memoryUsage);
- assertExists(finalMetrics.cpuUsage);
+ expect(finalMetrics.uptime).toBeDefined();
+ expect(finalMetrics.totalAgents).toBeDefined();
+ expect(finalMetrics.activeAgents).toBeDefined();
+ expect(finalMetrics.totalTasks).toBeDefined();
+ expect(finalMetrics.completedTasks).toBeDefined();
+ expect(finalMetrics.memoryUsage).toBeDefined();
+ expect(finalMetrics.cpuUsage).toBeDefined();
// Verify metric values make sense
- assertEquals(finalMetrics.activeAgents, 1);
- assertEquals(finalMetrics.completedTasks >= 5, true);
- assertEquals(finalMetrics.totalTasks >= 5, true);
+ expect(finalMetrics.activeAgents).toBe(1);
+ expect(finalMetrics.completedTasks >= 5).toBe(true);
+ expect(finalMetrics.totalTasks >= 5).toBe(true);
// Check memory and CPU usage are reasonable
- assertEquals(finalMetrics.memoryUsage.rss > 0, true);
- assertEquals(finalMetrics.cpuUsage.user >= 0, true);
+ expect(finalMetrics.memoryUsage.rss > 0).toBe(true);
+ expect(finalMetrics.cpuUsage.user >= 0).toBe(true);
});
});
});
\ No newline at end of file
diff --git a/tests/integration/mcp-integration.test.ts b/tests/integration/mcp-integration.test.ts
index b201958abb..9df35f8dab 100644
--- a/tests/integration/mcp-integration.test.ts
+++ b/tests/integration/mcp-integration.test.ts
@@ -90,8 +90,8 @@ describe('MCP Integration', () => {
// Verify tool registration
const tools = await mcpServer.listTools();
- assertEquals(tools.length, 1);
- assertEquals(tools[0].name, 'echo_tool');
+ expect(tools.length).toBe(1);
+ expect(tools[0].name).toBe('echo_tool');
// Create tool call request
const toolCall: MCPToolCall = {
@@ -111,10 +111,10 @@ describe('MCP Integration', () => {
// Execute tool
const result = await mcpServer.executeTool(toolCall, context);
- assertExists(result);
- assertEquals(result.content.length, 1);
- assertEquals(result.content[0].type, 'text');
- assertEquals(result.content[0].text?.includes('HELLO, MCP!'), true);
+ expect(result).toBeDefined();
+ expect(result.content.length).toBe(1);
+ expect(result.content[0].type).toBe('text');
+ expect(result.content[0].text?.includes('HELLO).toBe(MCP!'), true);
});
it('should handle tool execution errors gracefully', async () => {
@@ -147,10 +147,10 @@ describe('MCP Integration', () => {
const result = await mcpServer.executeTool(toolCall, context);
- assertEquals(result.isError, true);
- assertEquals(result.content.length, 1);
- assertEquals(result.content[0].type, 'text');
- assertEquals(result.content[0].text?.includes('Tool execution failed'), true);
+ expect(result.isError).toBe(true);
+ expect(result.content.length).toBe(1);
+ expect(result.content[0].type).toBe('text');
+ expect(result.content[0].text?.includes('Tool execution failed')).toBe(true);
});
it('should validate tool input schemas', async () => {
@@ -196,8 +196,8 @@ describe('MCP Integration', () => {
const result = await mcpServer.executeTool(invalidCall, context);
- assertEquals(result.isError, true);
- assertEquals(result.content[0].text?.includes('validation'), true);
+ expect(result.isError).toBe(true);
+ expect(result.content[0].text?.includes('validation')).toBe(true);
});
});
@@ -265,14 +265,14 @@ describe('MCP Integration', () => {
const results = await Promise.all(operations);
// Verify all operations completed
- assertEquals(results.length, 3);
+ expect(results.length).toBe(3);
results.forEach(result => {
- assertEquals(result.isError, false);
- assertExists(result.content[0].text);
+ expect(result.isError).toBe(false);
+ expect(result.content[0].text).toBeDefined();
});
// Final resource count should be 3 (one increment per agent)
- assertEquals(resourceCount, 3);
+ expect(resourceCount).toBe(3);
});
it('should handle tool registration conflicts', async () => {
@@ -304,8 +304,8 @@ describe('MCP Integration', () => {
// Verify only first tool is registered
const tools = await mcpServer.listTools();
- assertEquals(tools.length, 1);
- assertEquals(tools[0].description, 'First version of tool');
+ expect(tools.length).toBe(1);
+ expect(tools[0].description).toBe('First version of tool');
});
});
@@ -378,14 +378,14 @@ describe('MCP Integration', () => {
const response = await mcpServer.handleRequest(request);
// Verify response structure
- assertEquals(response.jsonrpc, '2.0');
- assertEquals(response.id, request.id);
- assertExists(response.result);
- assertEquals(response.error, undefined);
+ expect(response.jsonrpc).toBe('2.0');
+ expect(response.id).toBe(request.id);
+ expect(response.result).toBeDefined();
+ expect(response.error).toBe(undefined);
// Verify calculation result
const toolResult = response.result as MCPToolResult;
- assertEquals(toolResult.content[0].text, '6 multiply 7 = 42');
+ expect(toolResult.content[0].text).toBe('6 multiply 7 = 42');
});
it('should handle malformed requests', async () => {
@@ -400,9 +400,9 @@ describe('MCP Integration', () => {
const response = await mcpServer.handleRequest(invalidRequest);
// Should return error response
- assertEquals(response.jsonrpc, '2.0');
- assertExists(response.error);
- assertEquals(response.error!.code, -32600); // Invalid Request
+ expect(response.jsonrpc).toBe('2.0');
+ expect(response.error).toBeDefined();
+ expect(response.error!.code).toBe(-32600); // Invalid Request
});
it('should handle unknown methods', async () => {
@@ -417,7 +417,7 @@ describe('MCP Integration', () => {
const response = await mcpServer.handleRequest(unknownRequest);
- assertEquals(response.error!.code, -32601); // Method not found
+ expect(response.error!.code).toBe(-32601); // Method not found
});
});
@@ -463,11 +463,11 @@ describe('MCP Integration', () => {
await delay(100);
// Verify transport received response
- assertEquals(mcpTransport.sent.length, 1);
+ expect(mcpTransport.sent.length).toBe(1);
const response = JSON.parse(mcpTransport.sent[0]);
- assertEquals(response.jsonrpc, '2.0');
- assertEquals(response.id, 1);
- assertEquals(response.result.content[0].text, 'Hello from transport!');
+ expect(response.jsonrpc).toBe('2.0');
+ expect(response.id).toBe(1);
+ expect(response.result.content[0].text).toBe('Hello from transport!');
});
it('should handle transport errors', async () => {
@@ -573,8 +573,8 @@ describe('MCP Integration', () => {
};
const searchResult = await mcpServer.executeTool(searchCall, researchContext);
- assertEquals(searchResult.isError, false);
- assertEquals(searchResult.content[0].text?.includes('Deno best practices'), true);
+ expect(searchResult.isError).toBe(false);
+ expect(searchResult.content[0].text?.includes('Deno best practices')).toBe(true);
// Test implementer using code tool
const implementerContext: MCPContext = {
@@ -592,8 +592,8 @@ describe('MCP Integration', () => {
};
const codeResult = await mcpServer.executeTool(codeCall, implementerContext);
- assertEquals(codeResult.isError, false);
- assertEquals(codeResult.content[0].text?.includes('javascript'), true);
+ expect(codeResult.isError).toBe(false);
+ expect(codeResult.content[0].text?.includes('javascript')).toBe(true);
});
});
@@ -651,12 +651,12 @@ describe('MCP Integration', () => {
const results = await Promise.all(concurrentCalls);
// Verify all executions completed
- assertEquals(results.length, 10);
- assertEquals(executionCount, 10);
+ expect(results.length).toBe(10);
+ expect(executionCount).toBe(10);
results.forEach((result, index) => {
- assertEquals(result.isError, false);
- assertEquals(result.content[0].text?.includes(`call-${index}`), true);
+ expect(result.isError).toBe(false);
+ expect(result.content[0].text?.includes(`call-${index}`)).toBe(true);
});
});
@@ -698,11 +698,11 @@ describe('MCP Integration', () => {
const elapsed = Date.now() - startTime;
// Should complete quickly (timeout mechanism)
- assertEquals(elapsed < 2000, true);
+ expect(elapsed < 2000).toBe(true);
// Should indicate timeout error if implemented
if (result.isError) {
- assertEquals(result.content[0].text?.includes('timeout'), true);
+ expect(result.content[0].text?.includes('timeout')).toBe(true);
}
});
});
diff --git a/tests/integration/mcp.test.ts b/tests/integration/mcp.test.ts
index 771d448405..e04706f2e4 100644
--- a/tests/integration/mcp.test.ts
+++ b/tests/integration/mcp.test.ts
@@ -2,8 +2,8 @@
* Integration tests for MCP (Model Context Protocol) implementation
*/
-import { describe, it, beforeEach, afterEach, expect } from 'https://deno.land/[email protected]/testing/bdd.ts';
-import { delay } from 'https://deno.land/[email protected]/async/delay.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { MCPServer } from '../../src/mcp/server.ts';
import { StdioTransport } from '../../src/mcp/transports/stdio.ts';
diff --git a/tests/integration/memory-coordination.test.ts b/tests/integration/memory-coordination.test.ts
index d124f74d37..ee144a1eaf 100644
--- a/tests/integration/memory-coordination.test.ts
+++ b/tests/integration/memory-coordination.test.ts
@@ -85,7 +85,7 @@ describe('Memory-Coordination Integration', () => {
}
// Verify all entries were stored
- assertEquals(memoryManager.storeEntry.calls.length, 3);
+ expect(memoryManager.storeEntry.calls.length).toBe(3);
// Query memories across agents
const query: MemoryQuery = {
@@ -95,11 +95,11 @@ describe('Memory-Coordination Integration', () => {
};
const results = await memoryManager.queryEntries(query);
- assertEquals(results.length, 3);
+ expect(results.length).toBe(3);
// Verify entries from all agents
const resultAgentIds = results.map(entry => entry.agentId).sort();
- assertEquals(resultAgentIds, agentIds.sort());
+ expect(resultAgentIds).toBe(agentIds.sort());
});
it('should handle memory conflicts using coordination', async () => {
@@ -148,8 +148,8 @@ describe('Memory-Coordination Integration', () => {
// Verify final state
const finalEntry = await memoryManager.getEntry(initialEntry.id);
- assertExists(finalEntry);
- assertEquals(finalEntry.version, 3); // Should be incremented due to conflict
+ expect(finalEntry).toBeDefined();
+ expect(finalEntry.version).toBe(3); // Should be incremented due to conflict
});
it('should coordinate cross-agent memory queries', async () => {
@@ -190,11 +190,11 @@ describe('Memory-Coordination Integration', () => {
};
const allMemories = await memoryManager.queryEntries(synthesisQuery);
- assertEquals(allMemories.length, 3);
+ expect(allMemories.length).toBe(3);
// Verify memories from all agents are accessible
const agentTypes = allMemories.map(m => m.context.createdBy).sort();
- assertEquals(agentTypes, ['coordinator', 'implementer', 'researcher']);
+ expect(agentTypes).toBe(['coordinator', 'implementer', 'researcher']);
});
});
@@ -246,11 +246,11 @@ describe('Memory-Coordination Integration', () => {
};
const resourceHistory = await memoryManager.queryEntries(resourceQuery);
- assertEquals(resourceHistory.length, 2);
+ expect(resourceHistory.length).toBe(2);
const actions = resourceHistory.map(entry => entry.context.action);
- assertEquals(actions.includes('acquire'), true);
- assertEquals(actions.includes('acquired'), true);
+ expect(actions.includes('acquire')).toBe(true);
+ expect(actions.includes('acquired')).toBe(true);
// Release resource
await coordinationManager.releaseResource(resourceId, agentId);
@@ -294,7 +294,7 @@ describe('Memory-Coordination Integration', () => {
{ agentId: agents[1], resourceId: resources[0] },
]);
- assertEquals(deadlockDetected, true);
+ expect(deadlockDetected).toBe(true);
// Log deadlock detection in memory
const deadlockEntry: MemoryEntry = {
@@ -322,8 +322,8 @@ describe('Memory-Coordination Integration', () => {
};
const deadlockHistory = await memoryManager.queryEntries(deadlockQuery);
- assertEquals(deadlockHistory.length, 1);
- assertEquals(deadlockHistory[0].context.agents, agents);
+ expect(deadlockHistory.length).toBe(1);
+ expect(deadlockHistory[0].context.agents).toBe(agents);
// Clean up resources
await coordinationManager.releaseResource(resources[0], agents[0]);
@@ -400,16 +400,16 @@ describe('Memory-Coordination Integration', () => {
};
const messageHistory = await memoryManager.queryEntries(messageQuery);
- assertEquals(messageHistory.length, 2);
+ expect(messageHistory.length).toBe(2);
const actions = messageHistory.map(entry => entry.context.action);
- assertEquals(actions.includes('send'), true);
- assertEquals(actions.includes('receive'), true);
+ expect(actions.includes('send')).toBe(true);
+ expect(actions.includes('receive')).toBe(true);
// Verify message coordination worked
- assertEquals(coordinationManager.sendMessage.calls.length, 1);
+ expect(coordinationManager.sendMessage.calls.length).toBe(1);
const sentMessage = coordinationManager.sendMessage.calls[0].args[2];
- assertEquals(sentMessage.id, message.id);
+ expect(sentMessage.id).toBe(message.id);
});
it('should handle message delivery failures with memory logging', async () => {
@@ -462,8 +462,8 @@ describe('Memory-Coordination Integration', () => {
};
const failures = await memoryManager.queryEntries(failureQuery);
- assertEquals(failures.length, 1);
- assertEquals(failures[0].context.retryRequired, true);
+ expect(failures.length).toBe(1);
+ expect(failures[0].context.retryRequired).toBe(true);
});
});
@@ -504,7 +504,7 @@ describe('Memory-Coordination Integration', () => {
try {
// Get current state
const currentEntry = await memoryManager.getEntry(entryId);
- assertExists(currentEntry);
+ expect(currentEntry).toBeDefined();
// Apply modification
const updatedEntry = {
@@ -543,9 +543,9 @@ describe('Memory-Coordination Integration', () => {
// Verify final state
const finalEntry = await memoryManager.getEntry(entryId);
- assertExists(finalEntry);
- assertEquals(finalEntry.version, finalVersion);
- assertEquals(finalEntry.context.priority, 1); // Last modification
+ expect(finalEntry).toBeDefined();
+ expect(finalEntry.version).toBe(finalVersion);
+ expect(finalEntry.context.priority).toBe(1); // Last modification
// Verify modification history
const modificationQuery: MemoryQuery = {
@@ -554,7 +554,7 @@ describe('Memory-Coordination Integration', () => {
};
const modificationHistory = await memoryManager.queryEntries(modificationQuery);
- assertEquals(modificationHistory.length, 3);
+ expect(modificationHistory.length).toBe(3);
});
it('should coordinate distributed memory cleanup', async () => {
@@ -634,14 +634,14 @@ describe('Memory-Coordination Integration', () => {
tags: ['temp'],
limit: 50,
});
- assertEquals(remainingTemp.length, 0);
+ expect(remainingTemp.length).toBe(0);
// Verify cleanup was logged
const cleanupLogs = await memoryManager.queryEntries({
tags: ['cleanup'],
limit: 10,
});
- assertEquals(cleanupLogs.length, 3); // One per agent
+ expect(cleanupLogs.length).toBe(3); // One per agent
});
});
@@ -696,11 +696,11 @@ describe('Memory-Coordination Integration', () => {
limit: 200,
});
- assertEquals(allEntries.length, agentCount * entriesPerAgent);
+ expect(allEntries.length).toBe(agentCount * entriesPerAgent);
// Verify entries from all agents
const uniqueAgents = new Set(allEntries.map(entry => entry.agentId));
- assertEquals(uniqueAgents.size, agentCount);
+ expect(uniqueAgents.size).toBe(agentCount);
});
});
});
\ No newline at end of file
diff --git a/tests/integration/orchestrator-terminal.test.ts b/tests/integration/orchestrator-terminal.test.ts
index 07c06f8656..582a70518b 100644
--- a/tests/integration/orchestrator-terminal.test.ts
+++ b/tests/integration/orchestrator-terminal.test.ts
@@ -124,17 +124,17 @@ describe('Orchestrator-Terminal Integration', () => {
const profile = createTestProfile('test-agent-1');
const sessionId = await orchestrator.spawnAgent(profile);
- assertExists(sessionId);
+ expect(sessionId).toBeDefined();
// Verify agent session was created
const sessions = orchestrator.getActiveSessions();
- assertEquals(sessions.length, 1);
- assertEquals(sessions[0].agentId, profile.id);
+ expect(sessions.length).toBe(1);
+ expect(sessions[0].agentId).toBe(profile.id);
// Verify terminal was spawned
const terminalSessions = terminalManager.getActiveSessions();
- assertEquals(terminalSessions.length, 1);
- assertEquals(terminalSessions[0].agentId, profile.id);
+ expect(terminalSessions.length).toBe(1);
+ expect(terminalSessions[0].agentId).toBe(profile.id);
});
it('should execute tasks through terminal', async () => {
@@ -157,9 +157,9 @@ describe('Orchestrator-Terminal Integration', () => {
const result = await orchestrator.executeTask(task);
- assertExists(result);
- assertEquals(result.output?.stdout, 'Task executed successfully\n');
- assertEquals(result.status, 'completed');
+ expect(result).toBeDefined();
+ expect(result.output?.stdout).toBe('Task executed successfully\n');
+ expect(result.status).toBe('completed');
});
it('should handle concurrent tasks across multiple agents', async () => {
@@ -174,7 +174,7 @@ describe('Orchestrator-Terminal Integration', () => {
profiles.map(profile => orchestrator.spawnAgent(profile))
);
- assertEquals(sessions.length, 3);
+ expect(sessions.length).toBe(3);
// Create concurrent tasks
const tasks: Task[] = profiles.map((profile, index) => ({
@@ -197,10 +197,10 @@ describe('Orchestrator-Terminal Integration', () => {
);
// Verify all tasks completed
- assertEquals(results.length, 3);
+ expect(results.length).toBe(3);
results.forEach((result, index) => {
- assertEquals(result.status, 'completed');
- assertExists(result.output?.stdout);
+ expect(result.status).toBe('completed');
+ expect(result.output?.stdout).toBeDefined();
assertEquals(
result.output.stdout.includes(`task ${index + 1}`),
true
@@ -213,15 +213,15 @@ describe('Orchestrator-Terminal Integration', () => {
const sessionId = await orchestrator.spawnAgent(profile);
// Verify agent and terminal are active
- assertEquals(orchestrator.getActiveSessions().length, 1);
- assertEquals(terminalManager.getActiveSessions().length, 1);
+ expect(orchestrator.getActiveSessions().length).toBe(1);
+ expect(terminalManager.getActiveSessions().length).toBe(1);
// Terminate agent
await orchestrator.terminateAgent(sessionId, 'Test cleanup');
// Verify cleanup
- assertEquals(orchestrator.getActiveSessions().length, 0);
- assertEquals(terminalManager.getActiveSessions().length, 0);
+ expect(orchestrator.getActiveSessions().length).toBe(0);
+ expect(terminalManager.getActiveSessions().length).toBe(0);
});
});
@@ -250,7 +250,7 @@ describe('Orchestrator-Terminal Integration', () => {
);
// Verify no sessions were created
- assertEquals(orchestrator.getActiveSessions().length, 0);
+ expect(orchestrator.getActiveSessions().length).toBe(0);
// Restore original method
terminalManager.spawnTerminal = originalSpawn;
@@ -285,9 +285,9 @@ describe('Orchestrator-Terminal Integration', () => {
const result = await orchestrator.executeTask(task);
- assertEquals(result.status, 'failed');
- assertExists(result.error);
- assertEquals(result.error.message.includes('timeout'), true);
+ expect(result.status).toBe('failed');
+ expect(result.error).toBeDefined();
+ expect(result.error.message.includes('timeout')).toBe(true);
});
it('should retry failed tasks', async () => {
@@ -329,9 +329,9 @@ describe('Orchestrator-Terminal Integration', () => {
const result = await orchestrator.executeTask(task);
- assertEquals(result.status, 'completed');
- assertEquals(result.output?.stdout, 'Success on retry');
- assertEquals(attemptCount, 3);
+ expect(result.status).toBe('completed');
+ expect(result.output?.stdout).toBe('Success on retry');
+ expect(attemptCount).toBe(3);
// Restore original method
terminalManager.executeCommand = originalExecute;
@@ -356,12 +356,12 @@ describe('Orchestrator-Terminal Integration', () => {
profiles.map(profile => orchestrator.spawnAgent(profile))
);
- assertEquals(sessions.length, 3);
+ expect(sessions.length).toBe(3);
// Verify terminal pool health
const health = await terminalManager.getHealthStatus();
- assertEquals(health.healthy, true);
- assertEquals(health.metrics?.activeSessions, 3);
+ expect(health.healthy).toBe(true);
+ expect(health.metrics?.activeSessions).toBe(3);
// Try to spawn one more (should work as it creates new terminal)
const extraProfile: AgentProfile = {
@@ -376,7 +376,7 @@ describe('Orchestrator-Terminal Integration', () => {
// This should succeed as terminals are created on demand
const extraSession = await orchestrator.spawnAgent(extraProfile);
- assertExists(extraSession);
+ expect(extraSession).toBeDefined();
});
it('should perform maintenance operations', async () => {
@@ -402,9 +402,9 @@ describe('Orchestrator-Terminal Integration', () => {
await orchestrator.performMaintenance();
// Verify maintenance was performed
- assertEquals(maintenanceEvents.length, 1);
- assertExists(maintenanceEvents[0].timestamp);
- assertExists(maintenanceEvents[0].activeSessions);
+ expect(maintenanceEvents.length).toBe(1);
+ expect(maintenanceEvents[0].timestamp).toBeDefined();
+ expect(maintenanceEvents[0].activeSessions).toBeDefined();
});
});
@@ -465,10 +465,10 @@ describe('Orchestrator-Terminal Integration', () => {
// Verify events were emitted
const eventTypesSeen = events.map(e => e.type);
- assertEquals(eventTypesSeen.includes('agent:spawned'), true);
- assertEquals(eventTypesSeen.includes('task:started'), true);
- assertEquals(eventTypesSeen.includes('task:completed'), true);
- assertEquals(eventTypesSeen.includes('agent:terminated'), true);
+ expect(eventTypesSeen.includes('agent:spawned')).toBe(true);
+ expect(eventTypesSeen.includes('task:started')).toBe(true);
+ expect(eventTypesSeen.includes('task:completed')).toBe(true);
+ expect(eventTypesSeen.includes('agent:terminated')).toBe(true);
});
it('should handle cross-component error propagation', async () => {
@@ -511,14 +511,14 @@ describe('Orchestrator-Terminal Integration', () => {
const result = await orchestrator.executeTask(task);
- assertEquals(result.status, 'failed');
- assertExists(result.error);
+ expect(result.status).toBe('failed');
+ expect(result.error).toBeDefined();
// Wait for events to propagate
await delay(100);
// Verify error event was emitted
- assertEquals(errorEvents.length > 0, true);
+ expect(errorEvents.length > 0).toBe(true);
// Restore original method
terminalManager.executeCommand = originalExecute;
@@ -540,7 +540,7 @@ describe('Orchestrator-Terminal Integration', () => {
const sessionId = await orchestrator.spawnAgent(profile);
// Verify memory operations were called
- assertEquals(memoryManager.storeEntry.calls.length > 0, true);
+ expect(memoryManager.storeEntry.calls.length > 0).toBe(true);
const storedEntries = memoryManager.storeEntry.calls.map(call => call.args[0]);
const spawnEntry = storedEntries.find(entry =>
@@ -548,9 +548,9 @@ describe('Orchestrator-Terminal Integration', () => {
entry.content.includes('Agent spawned')
);
- assertExists(spawnEntry);
- assertEquals(spawnEntry.agentId, profile.id);
- assertEquals(spawnEntry.sessionId, sessionId);
+ expect(spawnEntry).toBeDefined();
+ expect(spawnEntry.agentId).toBe(profile.id);
+ expect(spawnEntry.sessionId).toBe(sessionId);
});
it('should store task execution history', async () => {
@@ -586,7 +586,7 @@ describe('Orchestrator-Terminal Integration', () => {
.map(call => call.args[0])
.filter(entry => entry.content.includes('Task'));
- assertEquals(taskEntries.length >= 2, true); // Start and completion
+ expect(taskEntries.length >= 2).toBe(true); // Start and completion
const startEntry = taskEntries.find(entry =>
entry.content.includes('started')
@@ -595,8 +595,8 @@ describe('Orchestrator-Terminal Integration', () => {
entry.content.includes('completed')
);
- assertExists(startEntry);
- assertExists(completeEntry);
+ expect(startEntry).toBeDefined();
+ expect(completeEntry).toBeDefined();
});
});
});
\ No newline at end of file
diff --git a/tests/integration/start-command.test.ts b/tests/integration/start-command.test.ts
index b6ef8ea924..80930ed1bb 100644
--- a/tests/integration/start-command.test.ts
+++ b/tests/integration/start-command.test.ts
@@ -2,8 +2,8 @@
* Integration tests for the start command
*/
-import { assertEquals, assertExists } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { beforeAll, beforeEach, afterAll, describe, it } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { startCommand } from '../../src/cli/commands/start/start-command.ts';
import { Command } from '@cliffy/command';
@@ -54,15 +54,15 @@ describe('Start Command Integration', () => {
describe('command structure', () => {
it('should be a valid Cliffy command', () => {
- assertExists(startCommand);
- assertEquals(startCommand instanceof Command, true);
+ expect(startCommand).toBeDefined();
+ expect(startCommand instanceof Command).toBe(true);
});
it('should have correct description', () => {
const desc = (startCommand as any)._globalParent?._description ||
(startCommand as any).getDescription();
- assertEquals(typeof desc, 'string');
- assertEquals(desc.includes('orchestration'), true);
+ expect(typeof desc).toBe('string');
+ expect(desc.includes('orchestration')).toBe(true);
});
it('should have all expected options', () => {
@@ -70,10 +70,10 @@ describe('Start Command Integration', () => {
const options = command.options || command.getOptions?.() || [];
const optionNames = options.map((opt: any) => opt.name);
- assertEquals(optionNames.includes('daemon'), true);
- assertEquals(optionNames.includes('port'), true);
- assertEquals(optionNames.includes('ui'), true);
- assertEquals(optionNames.includes('verbose'), true);
+ expect(optionNames.includes('daemon')).toBe(true);
+ expect(optionNames.includes('port')).toBe(true);
+ expect(optionNames.includes('ui')).toBe(true);
+ expect(optionNames.includes('verbose')).toBe(true);
});
});
@@ -84,8 +84,8 @@ describe('Start Command Integration', () => {
.command('start', startCommand);
const help = await command.getHelp();
- assertExists(help);
- assertEquals(help.includes('start'), true);
+ expect(help).toBeDefined();
+ expect(help.includes('start')).toBe(true);
});
});
});
\ No newline at end of file
diff --git a/tests/integration/start-compatibility.test.ts b/tests/integration/start-compatibility.test.ts
index 023df7a5bc..a69d0e6d6f 100644
--- a/tests/integration/start-compatibility.test.ts
+++ b/tests/integration/start-compatibility.test.ts
@@ -2,26 +2,26 @@
* Tests to ensure backward compatibility with existing start command functionality
*/
-import { assertEquals, assertExists } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { describe, it } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
describe('Start Command Backward Compatibility', () => {
describe('CLI imports', () => {
it('should export startCommand from main CLI index', async () => {
const module = await import('../../src/cli/index.ts');
// The module imports startCommand, so it should work
- assertExists(module);
+ expect(module).toBeDefined();
});
it('should export startCommand from commands/start.ts', async () => {
const { startCommand } = await import('../../src/cli/commands/start.ts');
- assertExists(startCommand);
+ expect(startCommand).toBeDefined();
});
it('should export startCommand from simple-commands', async () => {
const { startCommand } = await import('../../src/cli/simple-commands/start.js');
- assertExists(startCommand);
- assertEquals(typeof startCommand, 'function');
+ expect(startCommand).toBeDefined();
+ expect(typeof startCommand).toBe('function');
});
});
@@ -39,7 +39,7 @@ describe('Start Command Backward Compatibility', () => {
};
await startCommand(['--help'], {});
- assertEquals(helpShown, true);
+ expect(helpShown).toBe(true);
// Restore
console.log = originalLog;
@@ -59,7 +59,7 @@ describe('Start Command Backward Compatibility', () => {
};
await startCommand(['--help'], {});
- assertEquals(uiOptionShown, true);
+ expect(uiOptionShown).toBe(true);
// Restore
console.log = originalLog;
@@ -97,7 +97,7 @@ describe('Start Command Backward Compatibility', () => {
await startCommand(['--daemon'], { daemon: true });
// Verify warning about missing dirs was shown
- assertEquals(daemonMode || console.log.toString().includes('Missing required'), true);
+ expect(daemonMode || console.log.toString().includes('Missing required')).toBe(true);
// Restore
console.log = originalLog;
@@ -119,7 +119,7 @@ describe('Start Command Backward Compatibility', () => {
options.some((o: any) => o.name === opt || o.flags?.includes(opt))
);
- assertEquals(hasAllOptions, true);
+ expect(hasAllOptions).toBe(true);
});
});
@@ -128,12 +128,12 @@ describe('Start Command Backward Compatibility', () => {
// The setupEventListeners function was part of the original implementation
// Verify the event handling is still in place by checking imports
const module = await import('../../src/cli/commands/start/start-command.ts');
- assertExists(module.startCommand);
+ expect(module.startCommand).toBeDefined();
// Check that it imports eventBus
const sourceCode = await Deno.readTextFile('src/cli/commands/start/start-command.ts');
- assertEquals(sourceCode.includes('eventBus'), true);
- assertEquals(sourceCode.includes('SystemEvents'), true);
+ expect(sourceCode.includes('eventBus')).toBe(true);
+ expect(sourceCode.includes('SystemEvents')).toBe(true);
});
});
});
\ No newline at end of file
diff --git a/tests/integration/terminal.test.ts b/tests/integration/terminal.test.ts
index 3c80c74cf2..ee26b1e497 100644
--- a/tests/integration/terminal.test.ts
+++ b/tests/integration/terminal.test.ts
@@ -2,7 +2,7 @@
* Integration tests for terminal functionality
*/
-import { assertEquals, assertExists, assertRejects } from 'https://deno.land/[email protected]/assert/mod.ts';
+import { assertEquals, assertExists, assertRejects } from "../test.utils.ts";
import { TerminalManager } from '../../src/terminal/manager.ts';
import { NativeAdapter } from '../../src/terminal/adapters/native.ts';
import { VSCodeAdapter } from '../../src/terminal/adapters/vscode.ts';
@@ -50,17 +50,17 @@ Deno.test('NativeAdapter - creates and destroys terminals', async () => {
// Create terminal
const terminal = await adapter.createTerminal();
- assertExists(terminal);
- assertExists(terminal.id);
- assertEquals(terminal.isAlive(), true);
+ expect(terminal).toBeDefined();
+ expect(terminal.id).toBeDefined();
+ expect(terminal.isAlive()).toBe(true);
// Execute command
const output = await terminal.executeCommand('echo "Hello World"');
- assertEquals(output.trim(), 'Hello World');
+ expect(output.trim()).toBe('Hello World');
// Destroy terminal
await adapter.destroyTerminal(terminal);
- assertEquals(terminal.isAlive(), false);
+ expect(terminal.isAlive()).toBe(false);
await adapter.shutdown();
});
@@ -78,11 +78,11 @@ Deno.test('NativeAdapter - handles multiple shells', async () => {
if (platform === 'windows') {
// Windows specific test
const output = await terminal.executeCommand('echo %CLAUDE_FLOW_TERMINAL%');
- assertEquals(output.trim(), 'true');
+ expect(output.trim()).toBe('true');
} else {
// Unix-like specific test
const output = await terminal.executeCommand('echo $CLAUDE_FLOW_TERMINAL');
- assertEquals(output.trim(), 'true');
+ expect(output.trim()).toBe('true');
}
await adapter.destroyTerminal(terminal);
@@ -104,9 +104,9 @@ Deno.test('TerminalPool - manages terminal lifecycle', async () => {
const term1 = await pool.acquire();
const term2 = await pool.acquire();
- assertExists(term1);
- assertExists(term2);
- assertEquals(term1.id !== term2.id, true);
+ expect(term1).toBeDefined();
+ expect(term2).toBeDefined();
+ expect(term1.id !== term2.id).toBe(true);
// Release terminals
await pool.release(term1);
@@ -114,8 +114,8 @@ Deno.test('TerminalPool - manages terminal lifecycle', async () => {
// Check health status
const health = await pool.getHealthStatus();
- assertEquals(health.healthy, true);
- assertEquals(health.size >= 2, true);
+ expect(health.healthy).toBe(true);
+ expect(health.size >= 2).toBe(true);
await pool.shutdown();
await adapter.shutdown();
@@ -135,11 +135,11 @@ Deno.test('TerminalPool - recycles terminals after use count', async () => {
// Use and release twice to trigger recycling
await pool.release(terminal);
const term2 = await pool.acquire();
- assertEquals(term2.id, originalId); // Should get same terminal
+ expect(term2.id).toBe(originalId); // Should get same terminal
await pool.release(term2);
const term3 = await pool.acquire();
- assertEquals(term3.id !== originalId, true); // Should get new terminal after recycling
+ expect(term3.id !== originalId).toBe(true); // Should get new terminal after recycling
await pool.shutdown();
await adapter.shutdown();
@@ -161,15 +161,15 @@ Deno.test('TerminalSession - manages command execution', async () => {
// Execute command
const output = await session.executeCommand('echo "Session test"');
- assertEquals(output.trim(), 'Session test');
+ expect(output.trim()).toBe('Session test');
// Check command history
const history = session.getCommandHistory();
- assertEquals(history.length, 1);
- assertEquals(history[0], 'echo "Session test"');
+ expect(history.length).toBe(1);
+ expect(history[0]).toBe('echo "Session test"');
// Check health
- assertEquals(session.isHealthy(), true);
+ expect(session.isHealthy()).toBe(true);
await session.cleanup();
await adapter.destroyTerminal(terminal);
@@ -199,7 +199,7 @@ Deno.test('TerminalSession - handles output streaming', async () => {
// Check streamed output
await delay(100); // Allow output to be processed
- assertEquals(outputs.length > 0, true);
+ expect(outputs.length > 0).toBe(true);
unsubscribe();
await session.cleanup();
@@ -221,28 +221,28 @@ Deno.test('TerminalManager - complete workflow', async () => {
// Spawn terminal for agent
const profile = createTestProfile('manager-test');
const terminalId = await manager.spawnTerminal(profile);
- assertExists(terminalId);
+ expect(terminalId).toBeDefined();
// Execute command
const output = await manager.executeCommand(terminalId, 'echo "Manager test"');
- assertEquals(output.trim(), 'Manager test');
+ expect(output.trim()).toBe('Manager test');
// Get active sessions
const sessions = manager.getActiveSessions();
- assertEquals(sessions.length, 1);
- assertEquals(sessions[0].agentId, profile.id);
+ expect(sessions.length).toBe(1);
+ expect(sessions[0].agentId).toBe(profile.id);
// Check health
const health = await manager.getHealthStatus();
- assertEquals(health.healthy, true);
- assertEquals(health.metrics?.activeSessions, 1);
+ expect(health.healthy).toBe(true);
+ expect(health.metrics?.activeSessions).toBe(1);
// Terminate terminal
await manager.terminateTerminal(terminalId);
// Verify cleanup
const sessionsAfter = manager.getActiveSessions();
- assertEquals(sessionsAfter.length, 0);
+ expect(sessionsAfter.length).toBe(0);
await manager.shutdown();
});
@@ -269,8 +269,8 @@ Deno.test('TerminalManager - handles maintenance', async () => {
await manager.performMaintenance();
// Check event was emitted
- assertExists(maintenanceEvent);
- assertEquals(maintenanceEvent.activeSessions, 1);
+ expect(maintenanceEvent).toBeDefined();
+ expect(maintenanceEvent.activeSessions).toBe(1);
await manager.terminateTerminal(terminalId);
await manager.shutdown();
@@ -341,9 +341,9 @@ Deno.test('Terminal - handles cross-platform commands', async () => {
terminal.executeCommand('echo "Test 3"'),
]);
- assertEquals(outputs[0].trim(), 'Test 1');
- assertEquals(outputs[1].trim(), 'Test 2');
- assertEquals(outputs[2].trim(), 'Test 3');
+ expect(outputs[0].trim()).toBe('Test 1');
+ expect(outputs[1].trim()).toBe('Test 2');
+ expect(outputs[2].trim()).toBe('Test 3');
await adapter.destroyTerminal(terminal);
await adapter.shutdown();
@@ -360,11 +360,11 @@ if (typeof (globalThis as any).vscode !== 'undefined') {
await adapter.initialize();
const terminal = await adapter.createTerminal();
- assertExists(terminal);
- assertExists(terminal.id);
+ expect(terminal).toBeDefined();
+ expect(terminal.id).toBeDefined();
const output = await terminal.executeCommand('echo "VSCode test"');
- assertEquals(output.trim(), 'VSCode test');
+ expect(output.trim()).toBe('VSCode test');
await adapter.destroyTerminal(terminal);
await adapter.shutdown();
diff --git a/tests/integration/workflow-engine.test.ts b/tests/integration/workflow-engine.test.ts
index 33a4e6c99b..75538b190f 100644
--- a/tests/integration/workflow-engine.test.ts
+++ b/tests/integration/workflow-engine.test.ts
@@ -2,8 +2,8 @@
* Integration tests for the Workflow Engine
*/
-import { assertEquals, assertExists, assertThrows } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { describe, it, beforeEach, afterEach } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { WorkflowEngine, WorkflowDefinition, ExecutionOptions } from '../../package/src/workflow/engine.ts';
describe('Workflow Engine Integration Tests', () => {
@@ -42,9 +42,9 @@ describe('Workflow Engine Integration Tests', () => {
await Deno.writeTextFile(workflowPath, JSON.stringify(workflow, null, 2));
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Test Workflow');
- assertEquals(loadedWorkflow.tasks.length, 1);
- assertEquals(loadedWorkflow.tasks[0].id, 'test-task');
+ expect(loadedWorkflow.name).toBe('Test Workflow');
+ expect(loadedWorkflow.tasks.length).toBe(1);
+ expect(loadedWorkflow.tasks[0].id).toBe('test-task');
});
it('should load YAML workflow files', async () => {
@@ -62,9 +62,9 @@ tasks:
await Deno.writeTextFile(workflowPath, yamlContent);
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'YAML Test Workflow');
- assertEquals(loadedWorkflow.tasks.length, 1);
- assertEquals(loadedWorkflow.tasks[0].id, 'yaml-task');
+ expect(loadedWorkflow.name).toBe('YAML Test Workflow');
+ expect(loadedWorkflow.tasks.length).toBe(1);
+ expect(loadedWorkflow.tasks[0].id).toBe('yaml-task');
});
it('should handle invalid workflow files', async () => {
@@ -99,8 +99,8 @@ tasks:
};
const validation = await engine.validateWorkflow(workflow);
- assertEquals(validation.valid, true);
- assertEquals(validation.errors.length, 0);
+ expect(validation.valid).toBe(true);
+ expect(validation.errors.length).toBe(0);
});
it('should detect missing required fields', async () => {
@@ -110,9 +110,9 @@ tasks:
};
const validation = await engine.validateWorkflow(workflow);
- assertEquals(validation.valid, false);
- assertEquals(validation.errors.includes('Workflow name is required'), true);
- assertEquals(validation.errors.includes('At least one task is required'), true);
+ expect(validation.valid).toBe(false);
+ expect(validation.errors.includes('Workflow name is required')).toBe(true);
+ expect(validation.errors.includes('At least one task is required')).toBe(true);
});
it('should detect circular dependencies', async () => {
@@ -135,8 +135,8 @@ tasks:
};
const validation = await engine.validateWorkflow(workflow, true);
- assertEquals(validation.valid, false);
- assertEquals(validation.errors.includes('Circular dependencies detected'), true);
+ expect(validation.valid).toBe(false);
+ expect(validation.errors.includes('Circular dependencies detected')).toBe(true);
});
it('should validate agent assignments', async () => {
@@ -165,8 +165,8 @@ tasks:
};
const validation = await engine.validateWorkflow(workflow);
- assertEquals(validation.valid, false);
- assertEquals(validation.errors.some(e => e.includes('unknown agent nonexistent-agent')), true);
+ expect(validation.valid).toBe(false);
+ expect(validation.errors.some(e => e.includes('unknown agent nonexistent-agent'))).toBe(true);
});
});
@@ -189,13 +189,13 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.workflowName, 'Simple Execution Test');
- assertEquals(execution.status, 'completed');
- assertEquals(execution.progress.total, 1);
- assertEquals(execution.progress.completed, 1);
- assertEquals(execution.progress.failed, 0);
- assertExists(execution.completedAt);
- assertExists(execution.duration);
+ expect(execution.workflowName).toBe('Simple Execution Test');
+ expect(execution.status).toBe('completed');
+ expect(execution.progress.total).toBe(1);
+ expect(execution.progress.completed).toBe(1);
+ expect(execution.progress.failed).toBe(0);
+ expect(execution.completedAt).toBeDefined();
+ expect(execution.duration).toBeDefined();
});
it('should execute workflow with dependencies', async () => {
@@ -224,24 +224,24 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'completed');
- assertEquals(execution.progress.total, 3);
- assertEquals(execution.progress.completed, 3);
+ expect(execution.status).toBe('completed');
+ expect(execution.progress.total).toBe(3);
+ expect(execution.progress.completed).toBe(3);
// Verify execution order
const task1 = execution.tasks.find(t => t.taskId === 'task1')!;
const task2 = execution.tasks.find(t => t.taskId === 'task2')!;
const task3 = execution.tasks.find(t => t.taskId === 'task3')!;
- assertEquals(task1.status, 'completed');
- assertEquals(task2.status, 'completed');
- assertEquals(task3.status, 'completed');
+ expect(task1.status).toBe('completed');
+ expect(task2.status).toBe('completed');
+ expect(task3.status).toBe('completed');
// Task 1 should complete before task 2
- assertEquals(task1.completedAt! <= task2.startedAt!, true);
+ expect(task1.completedAt! <= task2.startedAt!).toBe(true);
// Tasks 1 and 2 should complete before task 3
- assertEquals(task1.completedAt! <= task3.startedAt!, true);
- assertEquals(task2.completedAt! <= task3.startedAt!, true);
+ expect(task1.completedAt! <= task3.startedAt!).toBe(true);
+ expect(task2.completedAt! <= task3.startedAt!).toBe(true);
});
it('should handle parallel execution', async () => {
@@ -276,13 +276,13 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
const endTime = Date.now();
- assertEquals(execution.status, 'completed');
- assertEquals(execution.progress.total, 3);
- assertEquals(execution.progress.completed, 3);
+ expect(execution.status).toBe('completed');
+ expect(execution.progress.total).toBe(3);
+ expect(execution.progress.completed).toBe(3);
// Parallel execution should be faster than sequential
const executionTime = endTime - startTime;
- assertEquals(executionTime < 5000, true); // Should complete in less than 5 seconds
+ expect(executionTime < 5000).toBe(true); // Should complete in less than 5 seconds
});
it('should handle conditional execution', async () => {
@@ -315,16 +315,16 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'completed');
- assertEquals(execution.progress.total, 2);
- assertEquals(execution.progress.completed, 1);
- assertEquals(execution.progress.skipped, 1);
+ expect(execution.status).toBe('completed');
+ expect(execution.progress.total).toBe(2);
+ expect(execution.progress.completed).toBe(1);
+ expect(execution.progress.skipped).toBe(1);
const requiredTask = execution.tasks.find(t => t.taskId === 'required-task')!;
const optionalTask = execution.tasks.find(t => t.taskId === 'optional-task')!;
- assertEquals(requiredTask.status, 'completed');
- assertEquals(optionalTask.status, 'skipped');
+ expect(requiredTask.status).toBe('completed');
+ expect(optionalTask.status).toBe('skipped');
});
it('should handle task retries on failure', async () => {
@@ -357,13 +357,13 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'completed');
- assertEquals(execution.progress.completed, 1);
- assertEquals(execution.progress.failed, 0);
+ expect(execution.status).toBe('completed');
+ expect(execution.progress.completed).toBe(1);
+ expect(execution.progress.failed).toBe(0);
const task = execution.tasks.find(t => t.taskId === 'flaky-task')!;
- assertEquals(task.status, 'completed');
- assertEquals(task.retryCount, 1);
+ expect(task.status).toBe('completed');
+ expect(task.retryCount).toBe(1);
});
it('should handle workflow timeout', async () => {
@@ -388,8 +388,8 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
// The workflow should handle the timeout gracefully
- assertEquals(execution.status, 'failed');
- assertEquals(execution.progress.failed, 1);
+ expect(execution.status).toBe('failed');
+ expect(execution.progress.failed).toBe(1);
});
});
@@ -409,9 +409,9 @@ tasks:
const execution2 = await engine.executeWorkflow(workflow2);
const executions = engine.listExecutions();
- assertEquals(executions.length, 2);
- assertEquals(executions.some(e => e.id === execution1.id), true);
- assertEquals(executions.some(e => e.id === execution2.id), true);
+ expect(executions.length).toBe(2);
+ expect(executions.some(e => e.id === execution1.id)).toBe(true);
+ expect(executions.some(e => e.id === execution2.id)).toBe(true);
});
it('should filter workflow executions', async () => {
@@ -423,15 +423,15 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
const filteredByName = engine.listExecutions({ workflowName: 'Filter Test' });
- assertEquals(filteredByName.length, 1);
- assertEquals(filteredByName[0].id, execution.id);
+ expect(filteredByName.length).toBe(1);
+ expect(filteredByName[0].id).toBe(execution.id);
const filteredByStatus = engine.listExecutions({ status: 'completed' });
- assertEquals(filteredByStatus.length, 1);
- assertEquals(filteredByStatus[0].id, execution.id);
+ expect(filteredByStatus.length).toBe(1);
+ expect(filteredByStatus[0].id).toBe(execution.id);
const filteredByDifferentName = engine.listExecutions({ workflowName: 'Nonexistent' });
- assertEquals(filteredByDifferentName.length, 0);
+ expect(filteredByDifferentName.length).toBe(0);
});
it('should cancel workflow execution', async () => {
@@ -459,12 +459,12 @@ tasks:
await new Promise(resolve => setTimeout(resolve, 100));
const executions = engine.listExecutions();
- assertEquals(executions.length, 1);
+ expect(executions.length).toBe(1);
await engine.cancelExecution(executions[0].id);
const execution = await executionPromise;
- assertEquals(execution.status, 'cancelled');
+ expect(execution.status).toBe('cancelled');
});
});
@@ -499,15 +499,15 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'failed');
- assertEquals(execution.progress.failed, 1);
- assertEquals(execution.progress.completed, 0);
+ expect(execution.status).toBe('failed');
+ expect(execution.progress.failed).toBe(1);
+ expect(execution.progress.completed).toBe(0);
const failingTask = execution.tasks.find(t => t.taskId === 'failing-task')!;
const subsequentTask = execution.tasks.find(t => t.taskId === 'subsequent-task')!;
- assertEquals(failingTask.status, 'failed');
- assertEquals(subsequentTask.status, 'pending'); // Should not have started
+ expect(failingTask.status).toBe('failed');
+ expect(subsequentTask.status).toBe('pending'); // Should not have started
});
it('should handle task failures with continue policy', async () => {
@@ -540,15 +540,15 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'failed'); // Overall failed due to one failure
- assertEquals(execution.progress.failed, 1);
- assertEquals(execution.progress.completed, 1);
+ expect(execution.status).toBe('failed'); // Overall failed due to one failure
+ expect(execution.progress.failed).toBe(1);
+ expect(execution.progress.completed).toBe(1);
const failingTask = execution.tasks.find(t => t.taskId === 'failing-task')!;
const successTask = execution.tasks.find(t => t.taskId === 'success-task')!;
- assertEquals(failingTask.status, 'failed');
- assertEquals(successTask.status, 'completed');
+ expect(failingTask.status).toBe('failed');
+ expect(successTask.status).toBe('completed');
});
});
@@ -575,9 +575,9 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'completed');
- assertEquals(execution.context.variables.testValue, 'Hello World');
- assertEquals(execution.context.variables.numericValue, 42);
+ expect(execution.status).toBe('completed');
+ expect(execution.context.variables.testValue).toBe('Hello World');
+ expect(execution.context.variables.numericValue).toBe(42);
});
it('should handle output storage and retrieval', async () => {
@@ -615,9 +615,9 @@ tasks:
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'completed');
- assertEquals(execution.context.outputs['producer-task.result'], 'produced data');
- assertEquals(execution.context.outputs['producer-task.data'].value, 123);
+ expect(execution.status).toBe('completed');
+ expect(execution.context.outputs['producer-task.result']).toBe('produced data');
+ expect(execution.context.outputs['producer-task.data'].value).toBe(123);
});
});
});
\ No newline at end of file
diff --git a/tests/integration/workflow-yaml-json.test.ts b/tests/integration/workflow-yaml-json.test.ts
index 052c229f18..fe87ea8499 100644
--- a/tests/integration/workflow-yaml-json.test.ts
+++ b/tests/integration/workflow-yaml-json.test.ts
@@ -2,8 +2,8 @@
* Integration tests for YAML and JSON workflow format support
*/
-import { assertEquals, assertExists, assertThrows } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { describe, it, beforeEach, afterEach } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { WorkflowEngine } from '../../package/src/workflow/engine.ts';
describe('Workflow Format Integration Tests', () => {
@@ -66,14 +66,14 @@ describe('Workflow Format Integration Tests', () => {
await Deno.writeTextFile(workflowPath, JSON.stringify(workflow, null, 2));
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Basic JSON Workflow');
- assertEquals(loadedWorkflow.tasks.length, 3);
- assertEquals(loadedWorkflow.variables!.environment, 'test');
- assertEquals(loadedWorkflow.settings!.maxConcurrency, 2);
+ expect(loadedWorkflow.name).toBe('Basic JSON Workflow');
+ expect(loadedWorkflow.tasks.length).toBe(3);
+ expect(loadedWorkflow.variables!.environment).toBe('test');
+ expect(loadedWorkflow.settings!.maxConcurrency).toBe(2);
const execution = await engine.executeWorkflow(loadedWorkflow);
- assertEquals(execution.status, 'completed');
- assertEquals(execution.progress.total, 3);
+ expect(execution.status).toBe('completed');
+ expect(execution.progress.total).toBe(3);
});
it('should handle complex JSON workflow with agents and conditions', async () => {
@@ -168,14 +168,14 @@ describe('Workflow Format Integration Tests', () => {
await Deno.writeTextFile(workflowPath, JSON.stringify(workflow, null, 2));
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Complex JSON Workflow');
- assertEquals(loadedWorkflow.agents!.length, 2);
- assertEquals(loadedWorkflow.conditions!.length, 1);
- assertEquals(loadedWorkflow.integrations!.length, 1);
- assertEquals(loadedWorkflow.metadata!.author, 'Test Suite');
+ expect(loadedWorkflow.name).toBe('Complex JSON Workflow');
+ expect(loadedWorkflow.agents!.length).toBe(2);
+ expect(loadedWorkflow.conditions!.length).toBe(1);
+ expect(loadedWorkflow.integrations!.length).toBe(1);
+ expect(loadedWorkflow.metadata!.author).toBe('Test Suite');
const validation = await engine.validateWorkflow(loadedWorkflow, true);
- assertEquals(validation.valid, true);
+ expect(validation.valid).toBe(true);
});
});
@@ -221,15 +221,15 @@ settings:
await Deno.writeTextFile(workflowPath, yamlContent);
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Basic YAML Workflow');
- assertEquals(loadedWorkflow.tasks.length, 3);
- assertEquals(loadedWorkflow.variables!.environment, 'test');
- assertEquals(loadedWorkflow.variables!.debug, true);
- assertEquals(loadedWorkflow.settings!.maxConcurrency, 2);
+ expect(loadedWorkflow.name).toBe('Basic YAML Workflow');
+ expect(loadedWorkflow.tasks.length).toBe(3);
+ expect(loadedWorkflow.variables!.environment).toBe('test');
+ expect(loadedWorkflow.variables!.debug).toBe(true);
+ expect(loadedWorkflow.settings!.maxConcurrency).toBe(2);
const execution = await engine.executeWorkflow(loadedWorkflow);
- assertEquals(execution.status, 'completed');
- assertEquals(execution.progress.total, 3);
+ expect(execution.status).toBe('completed');
+ expect(execution.progress.total).toBe(3);
});
it('should handle complex YAML workflow with advanced features', async () => {
@@ -469,18 +469,18 @@ settings:
await Deno.writeTextFile(workflowPath, yamlContent);
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Advanced YAML Workflow');
- assertEquals(loadedWorkflow.agents!.length, 3);
- assertEquals(loadedWorkflow.tasks.length, 7);
- assertEquals(loadedWorkflow.conditions!.length, 2);
- assertEquals(loadedWorkflow.loops!.length, 1);
- assertEquals(loadedWorkflow.integrations!.length, 2);
- assertEquals(loadedWorkflow.metadata!.author, 'YAML Test Suite');
- assertEquals(loadedWorkflow.variables!.project_name, 'test-project');
- assertEquals(loadedWorkflow.variables!.config.database.port, 5432);
+ expect(loadedWorkflow.name).toBe('Advanced YAML Workflow');
+ expect(loadedWorkflow.agents!.length).toBe(3);
+ expect(loadedWorkflow.tasks.length).toBe(7);
+ expect(loadedWorkflow.conditions!.length).toBe(2);
+ expect(loadedWorkflow.loops!.length).toBe(1);
+ expect(loadedWorkflow.integrations!.length).toBe(2);
+ expect(loadedWorkflow.metadata!.author).toBe('YAML Test Suite');
+ expect(loadedWorkflow.variables!.project_name).toBe('test-project');
+ expect(loadedWorkflow.variables!.config.database.port).toBe(5432);
const validation = await engine.validateWorkflow(loadedWorkflow, true);
- assertEquals(validation.valid, true);
+ expect(validation.valid).toBe(true);
});
it('should handle YAML with different indentation styles', async () => {
@@ -516,10 +516,10 @@ settings:
await Deno.writeTextFile(workflowPath, yamlContent);
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Indentation Test');
- assertEquals(loadedWorkflow.tasks.length, 2);
- assertEquals(loadedWorkflow.tasks[0].input!.param1, 'value1');
- assertEquals(loadedWorkflow.tasks[1].input!.nested.deep1, 'deep_value1');
+ expect(loadedWorkflow.name).toBe('Indentation Test');
+ expect(loadedWorkflow.tasks.length).toBe(2);
+ expect(loadedWorkflow.tasks[0].input!.param1).toBe('value1');
+ expect(loadedWorkflow.tasks[1].input!.nested.deep1).toBe('deep_value1');
});
});
@@ -534,7 +534,7 @@ settings:
await Deno.writeTextFile(workflowPath, JSON.stringify(workflow));
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Auto-detect JSON');
+ expect(loadedWorkflow.name).toBe('Auto-detect JSON');
});
it('should auto-detect YAML format without extension', async () => {
@@ -550,7 +550,7 @@ tasks:
await Deno.writeTextFile(workflowPath, yamlContent);
const loadedWorkflow = await engine.loadWorkflow(workflowPath);
- assertEquals(loadedWorkflow.name, 'Auto-detect YAML');
+ expect(loadedWorkflow.name).toBe('Auto-detect YAML');
});
it('should handle invalid format gracefully', async () => {
@@ -636,20 +636,20 @@ settings:
const yamlWorkflow = await engine.loadWorkflow(yamlPath);
// Compare key properties
- assertEquals(jsonWorkflow.name, yamlWorkflow.name);
- assertEquals(jsonWorkflow.version, yamlWorkflow.version);
- assertEquals(jsonWorkflow.tasks.length, yamlWorkflow.tasks.length);
- assertEquals(jsonWorkflow.variables!.test_var, yamlWorkflow.variables!.test_var);
- assertEquals(jsonWorkflow.variables!.numeric_var, yamlWorkflow.variables!.numeric_var);
- assertEquals(jsonWorkflow.settings!.maxConcurrency, yamlWorkflow.settings!.maxConcurrency);
+ expect(jsonWorkflow.name).toBe(yamlWorkflow.name);
+ expect(jsonWorkflow.version).toBe(yamlWorkflow.version);
+ expect(jsonWorkflow.tasks.length).toBe(yamlWorkflow.tasks.length);
+ expect(jsonWorkflow.variables!.test_var).toBe(yamlWorkflow.variables!.test_var);
+ expect(jsonWorkflow.variables!.numeric_var).toBe(yamlWorkflow.variables!.numeric_var);
+ expect(jsonWorkflow.settings!.maxConcurrency).toBe(yamlWorkflow.settings!.maxConcurrency);
// Execute both and compare results
const jsonExecution = await engine.executeWorkflow(jsonWorkflow);
const yamlExecution = await engine.executeWorkflow(yamlWorkflow);
- assertEquals(jsonExecution.status, yamlExecution.status);
- assertEquals(jsonExecution.progress.total, yamlExecution.progress.total);
- assertEquals(jsonExecution.progress.completed, yamlExecution.progress.completed);
+ expect(jsonExecution.status).toBe(yamlExecution.status);
+ expect(jsonExecution.progress.total).toBe(yamlExecution.progress.total);
+ expect(jsonExecution.progress.completed).toBe(yamlExecution.progress.completed);
});
});
@@ -660,18 +660,18 @@ settings:
try {
const workflow = await engine.loadWorkflow(examplePath);
- assertEquals(workflow.name, 'Advanced Research Workflow');
+ expect(workflow.name).toBe('Advanced Research Workflow');
const validation = await engine.validateWorkflow(workflow, true);
- assertEquals(validation.valid, true);
+ expect(validation.valid).toBe(true);
// Test execution with modified settings for faster testing
const testWorkflow = { ...workflow };
testWorkflow.settings = { ...testWorkflow.settings, timeout: 30000 };
const execution = await engine.executeWorkflow(testWorkflow);
- assertExists(execution.id);
- assertExists(execution.startedAt);
+ expect(execution.id).toBeDefined();
+ expect(execution.startedAt).toBeDefined();
} catch (error) {
// If the example file doesn't exist, create a minimal version for testing
console.warn('Research workflow example not found, creating test version');
@@ -705,7 +705,7 @@ settings:
await Deno.writeTextFile(testWorkflowPath, minimalResearchWorkflow);
const workflow = await engine.loadWorkflow(testWorkflowPath);
const execution = await engine.executeWorkflow(workflow);
- assertEquals(execution.status, 'completed');
+ expect(execution.status).toBe('completed');
}
});
@@ -715,17 +715,17 @@ settings:
try {
const workflow = await engine.loadWorkflow(examplePath);
- assertEquals(workflow.name, 'Full-Stack Development Workflow');
+ expect(workflow.name).toBe('Full-Stack Development Workflow');
const validation = await engine.validateWorkflow(workflow, true);
- assertEquals(validation.valid, true);
+ expect(validation.valid).toBe(true);
// Verify complex structure
- assertExists(workflow.agents);
- assertExists(workflow.conditions);
- assertExists(workflow.integrations);
- assertEquals(workflow.agents!.length > 0, true);
- assertEquals(workflow.tasks.length > 0, true);
+ expect(workflow.agents).toBeDefined();
+ expect(workflow.conditions).toBeDefined();
+ expect(workflow.integrations).toBeDefined();
+ expect(workflow.agents!.length > 0).toBe(true);
+ expect(workflow.tasks.length > 0).toBe(true);
} catch (error) {
// If the example file doesn't exist, create a minimal version for testing
@@ -762,7 +762,7 @@ settings:
await Deno.writeTextFile(testWorkflowPath, JSON.stringify(minimalDevWorkflow, null, 2));
const workflow = await engine.loadWorkflow(testWorkflowPath);
const validation = await engine.validateWorkflow(workflow, true);
- assertEquals(validation.valid, true);
+ expect(validation.valid).toBe(true);
}
});
});
diff --git a/tests/performance/cli/init/init-performance.test.ts b/tests/performance/cli/init/init-performance.test.ts
index 16f51500d7..d7596f4ca8 100644
--- a/tests/performance/cli/init/init-performance.test.ts
+++ b/tests/performance/cli/init/init-performance.test.ts
@@ -43,15 +43,15 @@ describe("Init Command Performance Tests", () => {
const endTime = performance.now();
const duration = endTime - startTime;
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should complete within 10 seconds for basic init
- assertEquals(duration < 10000, true);
+ expect(duration < 10000).toBe(true);
// Should create expected files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
console.log(`Basic init completed in ${duration.toFixed(2)}ms`);
});
@@ -100,7 +100,7 @@ describe("Init Command Performance Tests", () => {
const fullDuration = performance.now() - fullStartTime;
// Minimal should be faster or comparable
- assertEquals(minimalDuration <= fullDuration * 1.5, true); // Allow 50% tolerance
+ expect(minimalDuration <= fullDuration * 1.5).toBe(true); // Allow 50% tolerance
console.log(`Minimal init: ${minimalDuration.toFixed(2)}ms`);
console.log(`Full init: ${fullDuration.toFixed(2)}ms`);
@@ -128,14 +128,14 @@ describe("Init Command Performance Tests", () => {
const endTime = performance.now();
const duration = endTime - startTime;
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// SPARC init may take longer due to external processes
- assertEquals(duration < 30000, true); // 30 seconds max
+ expect(duration < 30000).toBe(true); // 30 seconds max
// Should create SPARC structure
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
console.log(`SPARC init completed in ${duration.toFixed(2)}ms`);
});
@@ -169,11 +169,11 @@ describe("Init Command Performance Tests", () => {
const duration = endTime - startTime;
// Should still complete successfully with fallback
- assertEquals(duration < 15000, true); // Should be faster than full external process
+ expect(duration < 15000).toBe(true); // Should be faster than full external process
// Should create basic SPARC structure manually
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
console.log(`SPARC fallback completed in ${duration.toFixed(2)}ms`);
});
@@ -214,18 +214,18 @@ describe("Init Command Performance Tests", () => {
// All should succeed
for (const result of results) {
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
}
// Concurrent execution should be faster than sequential
// (though this depends on system resources)
- assertEquals(duration < 20000, true); // 20 seconds for 3 concurrent inits
+ expect(duration < 20000).toBe(true); // 20 seconds for 3 concurrent inits
// Verify all directories were initialized
for (const dir of testDirs) {
- assertExists(await exists(join(dir, "CLAUDE.md")));
- assertExists(await exists(join(dir, "memory-bank.md")));
- assertExists(await exists(join(dir, "coordination.md")));
+ expect(await exists(join(dir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(dir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(dir, "coordination.md").toBeDefined()));
}
// Cleanup
@@ -274,15 +274,15 @@ describe("Init Command Performance Tests", () => {
const endTime = performance.now();
const duration = endTime - startTime;
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should not be significantly slower due to existing files
- assertEquals(duration < 15000, true);
+ expect(duration < 15000).toBe(true);
// Should create init files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
console.log(`Init in large project (${numFiles} files) completed in ${duration.toFixed(2)}ms`);
});
@@ -309,11 +309,11 @@ describe("Init Command Performance Tests", () => {
const result = await command.output();
const finalMemory = Deno.memoryUsage();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Memory increase should be reasonable (less than 50MB)
const memoryIncrease = finalMemory.heapUsed - initialMemory.heapUsed;
- assertEquals(memoryIncrease < 50 * 1024 * 1024, true);
+ expect(memoryIncrease < 50 * 1024 * 1024).toBe(true);
console.log(`Memory usage increase: ${(memoryIncrease / 1024 / 1024).toFixed(2)}MB`);
});
@@ -343,14 +343,14 @@ describe("Init Command Performance Tests", () => {
const endTime = performance.now();
const duration = endTime - startTime;
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Force overwrite should not be significantly slower
- assertEquals(duration < 10000, true);
+ expect(duration < 10000).toBe(true);
// Files should be overwritten
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(claudeContent.includes("existing content"), false);
+ expect(claudeContent.includes("existing content")).toBe(false);
console.log(`Force overwrite completed in ${duration.toFixed(2)}ms`);
});
@@ -400,7 +400,7 @@ describe("Init Command Performance Tests", () => {
// Should create directories efficiently
const dirCreationRate = createdDirs / (duration / 1000); // dirs per second
- assertEquals(dirCreationRate > 10, true); // Should create > 10 dirs/second
+ expect(dirCreationRate > 10).toBe(true); // Should create > 10 dirs/second
console.log(`Created ${createdDirs} directories in ${duration.toFixed(2)}ms (${dirCreationRate.toFixed(2)} dirs/sec)`);
});
@@ -452,7 +452,7 @@ describe("Init Command Performance Tests", () => {
// Should write files efficiently
const writeRate = totalSize / (duration / 1000); // bytes per second
- assertEquals(writeRate > 1000, true); // Should write > 1KB/second
+ expect(writeRate > 1000).toBe(true); // Should write > 1KB/second
console.log(`Created ${createdFiles} files (${totalSize} bytes) in ${duration.toFixed(2)}ms (${(writeRate / 1024).toFixed(2)} KB/sec)`);
});
diff --git a/tests/performance/load-testing.test.ts b/tests/performance/load-testing.test.ts
index a48b9ff43a..90c90127ed 100644
--- a/tests/performance/load-testing.test.ts
+++ b/tests/performance/load-testing.test.ts
@@ -2,8 +2,8 @@
* Comprehensive performance and load testing suite
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists } from "https://deno.land/[email protected]/assert/mod.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { assertEquals, assertExists } from "../test.utils.ts";
import {
PerformanceTestUtils,
@@ -118,7 +118,7 @@ describe('Performance and Load Testing Suite', () => {
);
TestAssertions.assertInRange(results.averageResponseTime, 0, 1000);
- assertEquals(results.errors.length < results.totalRequests * 0.1, true); // Less than 10% errors
+ expect(results.errors.length < results.totalRequests * 0.1).toBe(true); // Less than 10% errors
console.log(`Stress test results:
- Total requests: ${results.totalRequests}
@@ -168,7 +168,7 @@ describe('Performance and Load Testing Suite', () => {
);
// Memory usage should be stable over time
- assertEquals(leaked, false);
+ expect(leaked).toBe(false);
// Analyze memory trend
const firstSnapshot = snapshots[0];
@@ -262,8 +262,8 @@ describe('Performance and Load Testing Suite', () => {
);
// Should handle pressure without crashing
- assertExists(finalChunks);
- assertEquals(typeof finalChunks, 'number');
+ expect(finalChunks).toBeDefined();
+ expect(typeof finalChunks).toBe('number');
console.log(`Memory pressure test completed with ${finalChunks} chunks`);
console.log(`Memory increase: ${(memoryIncrease / 1024 / 1024).toFixed(2)}MB`);
@@ -309,11 +309,11 @@ describe('Performance and Load Testing Suite', () => {
const analysisResults = await concurrentMemoryTest();
// All operations should complete successfully
- assertEquals(analysisResults.length, 20);
+ expect(analysisResults.length).toBe(20);
analysisResults.forEach((result, i) => {
- assertExists(result.result);
- assertEquals(result.result.count, 1000);
+ expect(result.result).toBeDefined();
+ expect(result.result.count).toBe(1000);
console.log(`Operation ${i}: peak=${(result.peakMemory / 1024 / 1024).toFixed(2)}MB, growth=${(result.memoryGrowth / 1024 / 1024).toFixed(2)}MB`);
});
@@ -417,7 +417,7 @@ describe('Performance and Load Testing Suite', () => {
const largeBatch = batchResults[batchResults.length - 1];
// Time per item should decrease with larger batches
- assertEquals(largeBatch.timePerItem < smallBatch.timePerItem, true);
+ expect(largeBatch.timePerItem < smallBatch.timePerItem).toBe(true);
});
it('should handle concurrent file operations', async () => {
@@ -569,7 +569,7 @@ describe('Performance and Load Testing Suite', () => {
// Connection operations should be efficient
TestAssertions.assertInRange(stats.mean, 0, 50);
- assertEquals(connectionPool.connections.size <= connectionPool.maxConnections, true);
+ expect(connectionPool.connections.size <= connectionPool.maxConnections).toBe(true);
});
it('should handle event-driven communication patterns', async () => {
@@ -628,7 +628,7 @@ describe('Performance and Load Testing Suite', () => {
// Verify all events were processed
const totalEvents = Array.from(handlerStats.callCounts.values()).reduce((sum, count) => sum + count, 0);
- assertEquals(totalEvents, 500);
+ expect(totalEvents).toBe(500);
});
});
@@ -871,7 +871,7 @@ describe('Performance and Load Testing Suite', () => {
// Verify baselines are reasonable
baselines.forEach(baseline => {
TestAssertions.assertInRange(baseline.baseline, 0, 10); // Should be very fast
- assertEquals(baseline.stdDev < baseline.baseline, true); // Low variance
+ expect(baseline.stdDev < baseline.baseline).toBe(true); // Low variance
});
});
@@ -919,8 +919,8 @@ describe('Performance and Load Testing Suite', () => {
const regressions = regressionReport.filter(r => r.isRegression);
const improvements = regressionReport.filter(r => r.isImprovement);
- assertEquals(regressions.length, 1); // Operation B
- assertEquals(improvements.length, 1); // Operation C
+ expect(regressions.length).toBe(1); // Operation B
+ expect(improvements.length).toBe(1); // Operation C
// Report summary
console.log(`Performance analysis: ${regressions.length} regressions, ${improvements.length} improvements`);
diff --git a/tests/test.config.ts b/tests/test.config.ts
index 329ca4e9b3..f6a474e28b 100644
--- a/tests/test.config.ts
+++ b/tests/test.config.ts
@@ -2,6 +2,8 @@
* Test configuration for Claude-Flow
*/
+import * as fs from 'fs';
+
export const TEST_CONFIG = {
// Test timeouts
timeout: {
@@ -71,7 +73,7 @@ export const TEST_CONFIG = {
export function setupTestEnv(): void {
// Set environment variables
Object.entries(TEST_CONFIG.env).forEach(([key, value]) => {
- Deno.env.set(key, value);
+ process.env[key] = value;
});
// Ensure test directories exist
@@ -81,7 +83,7 @@ export function setupTestEnv(): void {
/**
* Cleanup test environment
*/
-export async function cleanupTestEnv(): Promise<void> {
+export function cleanupTestEnv(): void {
// Remove test data directory
const cleanupPaths = [
TEST_CONFIG.env.CLAUDE_FLOW_DATA_DIR,
@@ -92,7 +94,7 @@ export async function cleanupTestEnv(): Promise<void> {
for (const path of cleanupPaths) {
try {
- await Deno.remove(path, { recursive: true });
+ fs.rmSync(path, { recursive: true, force: true });
} catch {
// Ignore if doesn't exist
}
@@ -106,7 +108,7 @@ function ensureTestDirectories(): void {
const directories = Object.values(TEST_CONFIG.directories);
directories.forEach(dir => {
try {
- Deno.mkdirSync(dir, { recursive: true });
+ fs.mkdirSync(dir, { recursive: true });
} catch {
// Directory already exists
}
@@ -122,7 +124,7 @@ function ensureTestDirectories(): void {
additionalDirs.forEach(dir => {
try {
- Deno.mkdirSync(dir, { recursive: true });
+ fs.mkdirSync(dir, { recursive: true });
} catch {
// Directory already exists
}
@@ -142,7 +144,7 @@ export function getTestTimeout(suiteType: keyof typeof TEST_CONFIG.timeout): num
export function validateTestEnvironment(): boolean {
// Check required environment variables
const requiredEnvVars = Object.keys(TEST_CONFIG.env);
- const missingVars = requiredEnvVars.filter(varName => !Deno.env.get(varName));
+ const missingVars = requiredEnvVars.filter(varName => !process.env[varName]);
if (missingVars.length > 0) {
console.error(`Missing test environment variables: ${missingVars.join(', ')}`);
@@ -153,8 +155,8 @@ export function validateTestEnvironment(): boolean {
const directories = Object.values(TEST_CONFIG.directories);
for (const dir of directories) {
try {
- const stat = Deno.statSync(dir);
- if (!stat.isDirectory) {
+ const stat = fs.statSync(dir);
+ if (!stat.isDirectory()) {
console.error(`Test path is not a directory: ${dir}`);
return false;
}
diff --git a/tests/test.utils.ts b/tests/test.utils.ts
index 1b83b7068e..d990022d33 100644
--- a/tests/test.utils.ts
+++ b/tests/test.utils.ts
@@ -2,29 +2,70 @@
* Test utilities for Claude-Flow
*/
-import { assertEquals, assertExists, assertRejects, assertThrows } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { describe, it, beforeEach, afterEach, beforeAll, afterAll } from 'https://deno.land/[email protected]/testing/bdd.ts';
-import { spy, stub, assertSpyCall, assertSpyCalls } from 'https://deno.land/[email protected]/testing/mock.ts';
-import { FakeTime } from 'https://deno.land/[email protected]/testing/time.ts';
+import { describe, it, beforeEach, afterEach, beforeAll, afterAll, expect, jest } from '@jest/globals';
+import * as fs from 'fs';
+import * as path from 'path';
+import * as os from 'os';
+import { spawn } from 'child_process';
+// Jest-compatible assertion helpers
+export function assertEquals<T>(actual: T, expected: T, message?: string): void {
+ expect(actual).toBe(expected);
+}
+
+export function assertExists<T>(value: T, message?: string): void {
+ expect(value).toBeDefined();
+}
+
+export function assertRejects(promise: Promise<any>, message?: string): void {
+ expect(promise).rejects.toThrow();
+}
+
+export function assertThrows(fn: () => any, message?: string): void {
+ expect(fn).toThrow();
+}
+
+// Re-export Jest testing utilities
export {
- assertEquals,
- assertExists,
- assertRejects,
- assertThrows,
describe,
it,
beforeEach,
afterEach,
beforeAll,
afterAll,
- spy,
- stub,
- assertSpyCall,
- assertSpyCalls,
- FakeTime,
+ expect,
+ jest,
};
+// Mock Jest spy utilities for compatibility
+export const spy = jest.fn;
+export const stub = jest.fn;
+export function assertSpyCall(mockFn: jest.Mock, callIndex: number, expectedArgs?: any[]): void {
+ expect(mockFn).toHaveBeenNthCalledWith(callIndex + 1, ...(expectedArgs || []));
+}
+export function assertSpyCalls(mockFn: jest.Mock, expectedCalls: number): void {
+ expect(mockFn).toHaveBeenCalledTimes(expectedCalls);
+}
+
+// Simple FakeTime implementation for Jest
+export class FakeTime {
+ private originalNow = Date.now;
+ private currentTime: number;
+
+ constructor(time?: number | Date) {
+ this.currentTime = time instanceof Date ? time.getTime() : time || Date.now();
+ Date.now = () => this.currentTime;
+ }
+
+ tick(ms: number): void {
+ this.currentTime += ms;
+ }
+
+ restore(): void {
+ Date.now = this.originalNow;
+ }
+}
+
/**
* Creates a test fixture
*/
@@ -125,58 +166,58 @@ export function captureConsole(): {
/**
* Creates a test file in a temporary directory
*/
-export async function createTestFile(
- path: string,
+export function createTestFile(
+ filePath: string,
content: string,
-): Promise<string> {
- const tempDir = await Deno.makeTempDir();
- const filePath = `${tempDir}/${path}`;
- const dir = filePath.substring(0, filePath.lastIndexOf('/'));
+): string {
+ const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'claude-flow-'));
+ const fullPath = path.join(tempDir, filePath);
+ const dir = path.dirname(fullPath);
- await Deno.mkdir(dir, { recursive: true });
- await Deno.writeTextFile(filePath, content);
+ fs.mkdirSync(dir, { recursive: true });
+ fs.writeFileSync(fullPath, content);
- return filePath;
+ return fullPath;
}
/**
* Runs a CLI command and captures output
*/
-export async function runCommand(
+export function runCommand(
args: string[],
options: { stdin?: string; env?: Record<string, string> } = {},
): Promise<{ stdout: string; stderr: string; code: number }> {
- const cmdOptions: Deno.CommandOptions = {
- args: ['run', '--allow-all', 'src/cli/index.ts', ...args],
- stdout: 'piped',
- stderr: 'piped',
- };
+ return new Promise((resolve, reject) => {
+ const env = { ...process.env, ...options.env };
+ const child = spawn('node', ['src/cli/index.ts', ...args], {
+ stdio: ['pipe', 'pipe', 'pipe'],
+ env,
+ });
- if (options.stdin) {
- cmdOptions.stdin = 'piped';
- }
+ let stdout = '';
+ let stderr = '';
- if (options.env) {
- cmdOptions.env = options.env;
- }
+ child.stdout.on('data', (data) => {
+ stdout += data.toString();
+ });
- const cmd = new Deno.Command(Deno.execPath(), cmdOptions);
+ child.stderr.on('data', (data) => {
+ stderr += data.toString();
+ });
- const child = cmd.spawn();
+ child.on('close', (code) => {
+ resolve({ stdout, stderr, code: code || 0 });
+ });
- if (options.stdin) {
- const writer = child.stdin.getWriter();
- await writer.write(new TextEncoder().encode(options.stdin));
- await writer.close();
- }
+ child.on('error', (error) => {
+ reject(error);
+ });
- const output = await child.output();
-
- return {
- stdout: new TextDecoder().decode(output.stdout),
- stderr: new TextDecoder().decode(output.stderr),
- code: output.code,
- };
+ if (options.stdin) {
+ child.stdin.write(options.stdin);
+ child.stdin.end();
+ }
+ });
}
/**
@@ -277,9 +318,9 @@ export function assertEventEmitted(
matcher?: (data: any) => boolean,
): void {
const emitted = events.find((e) => e.event === eventName);
- assertExists(emitted, `Expected event '${eventName}' to be emitted`);
+ expect(emitted).toBeDefined();
- if (matcher && !matcher(emitted.data)) {
+ if (matcher && emitted && !matcher(emitted.data)) {
throw new Error(`Event '${eventName}' data did not match expected criteria`);
}
}
@@ -289,5 +330,5 @@ export function assertNoEventEmitted(
eventName: string,
): void {
const emitted = events.find((e) => e.event === eventName);
- assertEquals(emitted, undefined, `Expected event '${eventName}' not to be emitted`);
+ expect(emitted).toBeUndefined();
}
\ No newline at end of file
diff --git a/tests/unit/cli/cli-commands.test.ts b/tests/unit/cli/cli-commands.test.ts
index c35d0c9ec5..63c8059c68 100644
--- a/tests/unit/cli/cli-commands.test.ts
+++ b/tests/unit/cli/cli-commands.test.ts
@@ -3,10 +3,10 @@
* Tests all CLI commands with mock interactions and argument validation
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertRejects, assertStringIncludes } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
-import { spy, stub } from "https://deno.land/[email protected]/testing/mock.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { assertEquals, assertExists, assertRejects, assertStringIncludes } from "../test.utils.ts";
+// FakeTime equivalent available in test.utils.ts
+import { spy, stub } from "../test.utils.ts";
import {
AsyncTestUtils,
@@ -210,7 +210,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['start']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'orchestrator starting');
assertStringIncludes(output.stdout.join(' '), 'port 8080');
assertStringIncludes(output.stdout.join(' '), 'Log level: info');
@@ -226,7 +226,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'test-config.json');
assertStringIncludes(output.stdout.join(' '), 'port 9000');
assertStringIncludes(output.stdout.join(' '), 'Log level: debug');
@@ -236,7 +236,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['start', '--daemon']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'daemon mode');
});
@@ -244,7 +244,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['start', '--port', 'invalid']);
const output = cli.getOutput();
- assertEquals(exitCode, 1);
+ expect(exitCode).toBe(1);
assertStringIncludes(output.stderr.join(' '), 'Error');
});
});
@@ -304,7 +304,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Creating agent: test-agent');
assertStringIncludes(output.stdout.join(' '), 'created successfully');
});
@@ -320,7 +320,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Creating agent: full-agent');
assertStringIncludes(output.stdout.join(' '), 'Role: analyzer');
assertStringIncludes(output.stdout.join(' '), 'Capabilities: code-analysis,testing,documentation');
@@ -330,7 +330,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['agent', '--action', 'list']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Active agents:');
assertStringIncludes(output.stdout.join(' '), 'agent-1');
assertStringIncludes(output.stdout.join(' '), 'agent-2');
@@ -345,24 +345,24 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Deleting agent: old-agent');
assertStringIncludes(output.stdout.join(' '), 'deleted successfully');
});
it('should require name for create and delete actions', async () => {
const createResult = await cli.execute(['agent', '--action', 'create']);
- assertEquals(createResult, 1);
+ expect(createResult).toBe(1);
const deleteResult = await cli.execute(['agent', '--action', 'delete']);
- assertEquals(deleteResult, 1);
+ expect(deleteResult).toBe(1);
});
it('should handle unknown actions', async () => {
const exitCode = await cli.execute(['agent', '--action', 'unknown']);
const output = cli.getOutput();
- assertEquals(exitCode, 1);
+ expect(exitCode).toBe(1);
assertStringIncludes(output.stderr.join(' '), 'Unknown action: unknown');
});
});
@@ -433,7 +433,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Running task:');
assertStringIncludes(output.stdout.join(' '), 'Command: echo "Hello World"');
assertStringIncludes(output.stdout.join(' '), 'completed successfully');
@@ -451,7 +451,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Command: npm test');
assertStringIncludes(output.stdout.join(' '), 'Agent: test-agent');
assertStringIncludes(output.stdout.join(' '), 'Priority: high');
@@ -462,7 +462,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['task', '--action', 'list']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Active tasks:');
assertStringIncludes(output.stdout.join(' '), 'task-001');
assertStringIncludes(output.stdout.join(' '), 'task-002');
@@ -477,7 +477,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Cancelling task: task-123');
assertStringIncludes(output.stdout.join(' '), 'cancelled successfully');
});
@@ -486,7 +486,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['task', '--action', 'run']);
const output = cli.getOutput();
- assertEquals(exitCode, 1);
+ expect(exitCode).toBe(1);
assertStringIncludes(output.stderr.join(' '), 'Command is required');
});
@@ -494,7 +494,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['task', '--action', 'cancel']);
const output = cli.getOutput();
- assertEquals(exitCode, 1);
+ expect(exitCode).toBe(1);
assertStringIncludes(output.stderr.join(' '), 'Task ID is required');
});
});
@@ -564,7 +564,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Setting memory: default:test-key');
assertStringIncludes(output.stdout.join(' '), 'Value: test-value');
assertStringIncludes(output.stdout.join(' '), 'stored successfully');
@@ -582,7 +582,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Setting memory: project:project-key');
assertStringIncludes(output.stdout.join(' '), 'Tags: important,work');
});
@@ -596,7 +596,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Retrieving memory: default:existing-key');
assertStringIncludes(output.stdout.join(' '), 'Value: example-value-for-existing-key');
});
@@ -605,7 +605,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['memory', '--action', 'list']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Memory entries in namespace');
assertStringIncludes(output.stdout.join(' '), 'key1: value1');
assertStringIncludes(output.stdout.join(' '), 'key2: value2');
@@ -620,29 +620,29 @@ describe('CLI Commands - Comprehensive Tests', () => {
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Deleting memory: default:old-key');
assertStringIncludes(output.stdout.join(' '), 'deleted successfully');
});
it('should require key and value for set action', async () => {
const exitCode1 = await cli.execute(['memory', '--action', 'set', '--key', 'test']);
- assertEquals(exitCode1, 1);
+ expect(exitCode1).toBe(1);
cli.clearOutput();
const exitCode2 = await cli.execute(['memory', '--action', 'set', '--value', 'test']);
- assertEquals(exitCode2, 1);
+ expect(exitCode2).toBe(1);
});
it('should require key for get and delete actions', async () => {
const exitCode1 = await cli.execute(['memory', '--action', 'get']);
- assertEquals(exitCode1, 1);
+ expect(exitCode1).toBe(1);
cli.clearOutput();
const exitCode2 = await cli.execute(['memory', '--action', 'delete']);
- assertEquals(exitCode2, 1);
+ expect(exitCode2).toBe(1);
});
});
@@ -689,7 +689,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['help']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Claude-Flow CLI');
assertStringIncludes(output.stdout.join(' '), 'Commands:');
assertStringIncludes(output.stdout.join(' '), 'start');
@@ -702,7 +702,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['help', '--command', 'start']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Help for command: start');
});
@@ -710,7 +710,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['version']);
const output = cli.getOutput();
- assertEquals(exitCode, 0);
+ expect(exitCode).toBe(0);
assertStringIncludes(output.stdout.join(' '), 'Claude-Flow v1.0.0');
assertStringIncludes(output.stdout.join(' '), 'Deno Runtime');
assertStringIncludes(output.stdout.join(' '), 'Build:');
@@ -720,7 +720,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['unknown-command']);
const output = cli.getOutput();
- assertEquals(exitCode, 1);
+ expect(exitCode).toBe(1);
assertStringIncludes(output.stderr.join(' '), 'Unknown command: unknown-command');
});
@@ -728,7 +728,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(['help', '--invalid-option', 'value']);
const output = cli.getOutput();
- assertEquals(exitCode, 1);
+ expect(exitCode).toBe(1);
assertStringIncludes(output.stderr.join(' '), 'Unknown option: invalid-option');
});
});
@@ -780,7 +780,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
const exitCode = await cli.execute(scenario.command);
const output = cli.getOutput();
- assertEquals(exitCode, scenario.expectedExitCode);
+ expect(exitCode).toBe(scenario.expectedExitCode);
if (scenario.expectedOutput) {
const outputText = output.stdout.join(' ');
@@ -820,7 +820,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
// All commands in workflow should succeed
results.forEach(result => {
- assertEquals(result.exitCode, 0);
+ expect(result.exitCode).toBe(0);
});
console.log(`Workflow completed with ${results.length} steps`);
@@ -876,8 +876,8 @@ describe('CLI Commands - Comprehensive Tests', () => {
// All concurrent operations should succeed
results.forEach(result => {
- assertEquals(result.exitCode, 0);
- assertExists(result.output.stdout[0]);
+ expect(result.exitCode).toBe(0);
+ expect(result.output.stdout[0]).toBeDefined();
});
console.log(`${results.length} concurrent CLI operations completed successfully`);
@@ -904,11 +904,11 @@ describe('CLI Commands - Comprehensive Tests', () => {
console.log(`Step ${index + 1}: ${command.join(' ')} -> exit code ${exitCode}`);
}
- assertEquals(actualResults, expectedResults);
+ expect(actualResults).toBe(expectedResults);
// Verify that successful commands completed despite intervening errors
- assertEquals(actualResults.filter(code => code === 0).length, 3);
- assertEquals(actualResults.filter(code => code === 1).length, 2);
+ expect(actualResults.filter(code => code === 0).length).toBe(3);
+ expect(actualResults.filter(code => code === 1).length).toBe(2);
});
});
@@ -943,7 +943,7 @@ describe('CLI Commands - Comprehensive Tests', () => {
return cli.execute(['perf-test', '--iterations', '10', '--delay', '0']);
});
- assertEquals(result, 0);
+ expect(result).toBe(0);
TestAssertions.assertInRange(duration, 0, 1000); // Should complete within 1 second
console.log(`Fast CLI execution: ${duration.toFixed(2)}ms`);
diff --git a/tests/unit/cli/commands/init/init-command.test.ts b/tests/unit/cli/commands/init/init-command.test.ts
index e11b5e8b89..5d50128c81 100644
--- a/tests/unit/cli/commands/init/init-command.test.ts
+++ b/tests/unit/cli/commands/init/init-command.test.ts
@@ -37,34 +37,34 @@ describe("Init Command Unit Tests", () => {
await initCommand([], {});
// Check basic files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
// Check directories
- assertExists(await exists(join(testDir, "memory")));
- assertExists(await exists(join(testDir, "memory/agents")));
- assertExists(await exists(join(testDir, "memory/sessions")));
- assertExists(await exists(join(testDir, "coordination")));
- assertExists(await exists(join(testDir, ".claude")));
- assertExists(await exists(join(testDir, ".claude/commands")));
+ expect(await exists(join(testDir, "memory").toBeDefined()));
+ expect(await exists(join(testDir, "memory/agents").toBeDefined()));
+ expect(await exists(join(testDir, "memory/sessions").toBeDefined()));
+ expect(await exists(join(testDir, "coordination").toBeDefined()));
+ expect(await exists(join(testDir, ".claude").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands").toBeDefined()));
});
it("should create minimal structure with --minimal flag", async () => {
await initCommand(["--minimal"], {});
// Check files exist
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
// Check content is minimal (smaller size)
const claudeMd = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
const memoryBankMd = await Deno.readTextFile(join(testDir, "memory-bank.md"));
// Minimal versions should be shorter
- assertEquals(claudeMd.includes("Minimal project configuration"), true);
- assertEquals(memoryBankMd.includes("Simple memory tracking"), true);
+ expect(claudeMd.includes("Minimal project configuration")).toBe(true);
+ expect(memoryBankMd.includes("Simple memory tracking")).toBe(true);
});
it("should handle help flag correctly", async () => {
@@ -116,8 +116,8 @@ describe("Init Command Unit Tests", () => {
const memoryBankMd = await Deno.readTextFile(join(testDir, "memory-bank.md"));
// Should not contain old content
- assertEquals(claudeMd.includes("old content"), false);
- assertEquals(memoryBankMd.includes("old memory"), false);
+ expect(claudeMd.includes("old content")).toBe(false);
+ expect(memoryBankMd.includes("old memory")).toBe(false);
// Should contain new content
assertStringIncludes(claudeMd, "Claude Code Configuration");
@@ -130,8 +130,8 @@ describe("Init Command Unit Tests", () => {
await initCommand(["--sparc"], {});
// Check SPARC-specific files
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// Check CLAUDE.md contains SPARC content
const claudeMd = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
@@ -144,10 +144,10 @@ describe("Init Command Unit Tests", () => {
await initCommand(["--sparc", "--force"], {});
// Check manual SPARC structure
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roo/templates")));
- assertExists(await exists(join(testDir, ".roo/workflows")));
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/templates").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/workflows").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
});
});
@@ -157,12 +157,12 @@ describe("Init Command Unit Tests", () => {
// Check claude-flow-data.json is valid JSON
const dataPath = join(testDir, "memory/claude-flow-data.json");
- assertExists(await exists(dataPath));
+ expect(await exists(dataPath).toBeDefined());
const data = JSON.parse(await Deno.readTextFile(dataPath));
- assertEquals(Array.isArray(data.agents), true);
- assertEquals(Array.isArray(data.tasks), true);
- assertEquals(typeof data.lastUpdated, "number");
+ expect(Array.isArray(data.agents)).toBe(true);
+ expect(Array.isArray(data.tasks)).toBe(true);
+ expect(typeof data.lastUpdated).toBe("number");
});
it("should create proper README files", async () => {
@@ -195,7 +195,7 @@ describe("Init Command Unit Tests", () => {
console.error = originalError;
// Should have attempted to create directory
- assertEquals(errors.length > 0, true);
+ expect(errors.length > 0).toBe(true);
});
it("should continue when some operations fail", async () => {
@@ -221,7 +221,7 @@ describe("Init Command Unit Tests", () => {
await initCommand(["--sparc", "--minimal"], {});
// Should create SPARC structure
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// But with minimal content
const claudeMd = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
@@ -242,18 +242,18 @@ describe("Init Command Unit Tests", () => {
// Should overwrite and create SPARC structure
const claudeMd = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
assertStringIncludes(claudeMd, "SPARC");
- assertEquals(claudeMd.includes("old content"), false);
+ expect(claudeMd.includes("old content")).toBe(false);
// Should preserve or recreate .roomodes
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
});
it("should handle all flags together", async () => {
await initCommand(["--sparc", "--minimal", "--force"], {});
// Should create minimal SPARC structure
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
const claudeMd = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
assertStringIncludes(claudeMd, "SPARC");
diff --git a/tests/unit/cli/commands/init/rollback.test.ts b/tests/unit/cli/commands/init/rollback.test.ts
index 6d192673d3..28c2b20d8e 100644
--- a/tests/unit/cli/commands/init/rollback.test.ts
+++ b/tests/unit/cli/commands/init/rollback.test.ts
@@ -48,7 +48,7 @@ describe("Init Command Rollback Tests", () => {
console.error = originalError;
// Should fail due to directory conflict
- assertEquals(result.success, false);
+ expect(result.success).toBe(false);
// Should not leave partial state (other files should not be created if first fails)
// Note: This depends on the implementation - some files might be created before failure
@@ -75,7 +75,7 @@ describe("Init Command Rollback Tests", () => {
const result = await command.output();
// Should handle the error
- assertEquals(result.success, false);
+ expect(result.success).toBe(false);
// Should report the error appropriately
const stderr = new TextDecoder().decode(result.stderr);
@@ -106,12 +106,12 @@ describe("Init Command Rollback Tests", () => {
const output = new TextDecoder().decode(result.stdout);
// Should fall back to manual creation
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
console.log("SPARC fallback output:", output);
// Should still create SPARC structure
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
});
it("should handle partial SPARC structure creation", async () => {
@@ -138,8 +138,8 @@ describe("Init Command Rollback Tests", () => {
console.log("SPARC structure conflict:", stderr);
// Basic init should still work
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
});
});
@@ -166,7 +166,7 @@ describe("Init Command Rollback Tests", () => {
await Deno.chmod(testDir, 0o755);
// Should fail due to permissions
- assertEquals(result.success, false);
+ expect(result.success).toBe(false);
const stderr = new TextDecoder().decode(result.stderr);
console.log("Permission error:", stderr);
@@ -246,7 +246,7 @@ describe("Init Command Rollback Tests", () => {
console.log("Init result:", result.success);
// Original files should still exist
- assertExists(await exists(join(testDir, "existing.txt")));
+ expect(await exists(join(testDir, "existing.txt").toBeDefined()));
});
it("should handle concurrent access conflicts", async () => {
@@ -283,11 +283,11 @@ describe("Init Command Rollback Tests", () => {
// At least one should succeed
const anySucceeded = result1.success || result2.success;
- assertEquals(anySucceeded, true);
+ expect(anySucceeded).toBe(true);
// Files should be created
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
console.log("Concurrent init results:", result1.success, result2.success);
});
@@ -315,17 +315,17 @@ describe("Init Command Rollback Tests", () => {
});
const result = await command.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should have complete structure now
- assertExists(await exists(join(testDir, "CLAUDE.md")));
- assertExists(await exists(join(testDir, "memory-bank.md")));
- assertExists(await exists(join(testDir, "coordination.md")));
- assertExists(await exists(join(testDir, "memory")));
+ expect(await exists(join(testDir, "CLAUDE.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory-bank.md").toBeDefined()));
+ expect(await exists(join(testDir, "coordination.md").toBeDefined()));
+ expect(await exists(join(testDir, "memory").toBeDefined()));
// CLAUDE.md should be overwritten
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(claudeContent.includes("partial content"), false);
+ expect(claudeContent.includes("partial content")).toBe(false);
});
it("should handle recovery with existing directories", async () => {
@@ -351,16 +351,16 @@ describe("Init Command Rollback Tests", () => {
});
const result = await command.output();
- assertEquals(result.success, true);
+ expect(result.success).toBe(true);
// Should work with existing directories
- assertExists(await exists(join(testDir, "memory")));
- assertExists(await exists(join(testDir, "memory/agents")));
- assertExists(await exists(join(testDir, "coordination")));
+ expect(await exists(join(testDir, "memory").toBeDefined()));
+ expect(await exists(join(testDir, "memory/agents").toBeDefined()));
+ expect(await exists(join(testDir, "coordination").toBeDefined()));
// File should be overwritten
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(claudeContent.includes("old content"), false);
+ expect(claudeContent.includes("old content")).toBe(false);
});
});
@@ -413,7 +413,7 @@ describe("Init Command Rollback Tests", () => {
console.log("Temp files:", tempFiles);
// Should not create excessive temporary files
- assertEquals(tempFiles.length === 0, true);
+ expect(tempFiles.length === 0).toBe(true);
});
it("should handle interrupted initialization", async () => {
@@ -442,12 +442,12 @@ describe("Init Command Rollback Tests", () => {
const output = new TextDecoder().decode(result.stdout);
// Should detect existing file and warn
- assertEquals(output.includes("already exist"), true);
- assertEquals(output.includes("--force"), true);
+ expect(output.includes("already exist")).toBe(true);
+ expect(output.includes("--force")).toBe(true);
// Original file should be unchanged
const claudeContent = await Deno.readTextFile(join(testDir, "CLAUDE.md"));
- assertEquals(claudeContent.includes("Incomplete..."), true);
+ expect(claudeContent.includes("Incomplete...")).toBe(true);
});
});
});
\ No newline at end of file
diff --git a/tests/unit/cli/commands/init/sparc-structure.test.ts b/tests/unit/cli/commands/init/sparc-structure.test.ts
index 20787dcd2c..c0e8483ce5 100644
--- a/tests/unit/cli/commands/init/sparc-structure.test.ts
+++ b/tests/unit/cli/commands/init/sparc-structure.test.ts
@@ -26,43 +26,43 @@ describe("SPARC Structure Creation Tests", () => {
await createSparcStructureManually();
// Check main directories
- assertExists(await exists(join(testDir, ".roo")));
- assertExists(await exists(join(testDir, ".roo/templates")));
- assertExists(await exists(join(testDir, ".roo/workflows")));
- assertExists(await exists(join(testDir, ".roo/modes")));
- assertExists(await exists(join(testDir, ".roo/configs")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/templates").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/workflows").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/modes").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/configs").toBeDefined()));
});
it("should create .roomodes configuration file", async () => {
await createSparcStructureManually();
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
// Check content is valid JSON
const roomodesContent = await Deno.readTextFile(join(testDir, ".roomodes"));
const roomodesData = JSON.parse(roomodesContent);
- assertEquals(typeof roomodesData, "object");
- assertEquals(roomodesData !== null, true);
+ expect(typeof roomodesData).toBe("object");
+ expect(roomodesData !== null).toBe(true);
});
it("should create workflow templates", async () => {
await createSparcStructureManually();
- assertExists(await exists(join(testDir, ".roo/workflows/basic-tdd.json")));
+ expect(await exists(join(testDir, ".roo/workflows/basic-tdd.json").toBeDefined()));
// Check workflow is valid JSON
const workflowContent = await Deno.readTextFile(join(testDir, ".roo/workflows/basic-tdd.json"));
const workflowData = JSON.parse(workflowContent);
- assertEquals(typeof workflowData, "object");
+ expect(typeof workflowData).toBe("object");
assertStringIncludes(workflowContent, "tdd");
});
it("should create README for .roo directory", async () => {
await createSparcStructureManually();
- assertExists(await exists(join(testDir, ".roo/README.md")));
+ expect(await exists(join(testDir, ".roo/README.md").toBeDefined()));
const readmeContent = await Deno.readTextFile(join(testDir, ".roo/README.md"));
assertStringIncludes(readmeContent, "# SPARC Development Environment");
@@ -72,9 +72,9 @@ describe("SPARC Structure Creation Tests", () => {
it("should create Claude commands directory", async () => {
await createSparcStructureManually();
- assertExists(await exists(join(testDir, ".claude")));
- assertExists(await exists(join(testDir, ".claude/commands")));
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".claude").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands").toBeDefined()));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
});
});
@@ -90,7 +90,7 @@ describe("SPARC Structure Creation Tests", () => {
await createSparcStructureManually();
const preservedContent = await Deno.readTextFile(join(testDir, ".roomodes"));
- assertEquals(preservedContent, existingContent);
+ expect(preservedContent).toBe(existingContent);
});
it("should handle existing directories gracefully", async () => {
@@ -102,9 +102,9 @@ describe("SPARC Structure Creation Tests", () => {
await createSparcStructureManually();
// Should still create missing directories
- assertExists(await exists(join(testDir, ".roo/workflows")));
- assertExists(await exists(join(testDir, ".roo/modes")));
- assertExists(await exists(join(testDir, ".roo/configs")));
+ expect(await exists(join(testDir, ".roo/workflows").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/modes").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/configs").toBeDefined()));
});
});
@@ -116,14 +116,14 @@ describe("SPARC Structure Creation Tests", () => {
const roomodesData = JSON.parse(roomodesContent);
// Should have SPARC modes
- assertEquals(typeof roomodesData.modes, "object");
- assertEquals(roomodesData.modes !== null, true);
+ expect(typeof roomodesData.modes).toBe("object");
+ expect(roomodesData.modes !== null).toBe(true);
// Should have basic modes
- assertExists(roomodesData.modes.architect);
- assertExists(roomodesData.modes.code);
- assertExists(roomodesData.modes.tdd);
- assertExists(roomodesData.modes["spec-pseudocode"]);
+ expect(roomodesData.modes.architect).toBeDefined();
+ expect(roomodesData.modes.code).toBeDefined();
+ expect(roomodesData.modes.tdd).toBeDefined();
+ expect(roomodesData.modes["spec-pseudocode"]).toBeDefined();
});
it("should create valid workflow JSON", async () => {
@@ -133,9 +133,9 @@ describe("SPARC Structure Creation Tests", () => {
const workflowData = JSON.parse(workflowContent);
// Should have workflow structure
- assertEquals(typeof workflowData.name, "string");
- assertEquals(Array.isArray(workflowData.steps), true);
- assertEquals(workflowData.steps.length > 0, true);
+ expect(typeof workflowData.name).toBe("string");
+ expect(Array.isArray(workflowData.steps)).toBe(true);
+ expect(workflowData.steps.length > 0).toBe(true);
});
it("should create proper README format", async () => {
@@ -211,7 +211,7 @@ describe("SPARC Structure Creation Tests", () => {
await createSparcStructureManually();
// Check for command files
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
// Check for specific command files (they should be created by createClaudeSlashCommands)
const commandsDir = join(testDir, ".claude/commands/sparc");
@@ -228,7 +228,7 @@ describe("SPARC Structure Creation Tests", () => {
}
// Should have created command files
- assertEquals(commandFiles.length >= 0, true);
+ expect(commandFiles.length >= 0).toBe(true);
});
});
@@ -248,7 +248,7 @@ describe("SPARC Structure Creation Tests", () => {
];
for (const dir of expectedDirs) {
- assertExists(await exists(join(testDir, dir)));
+ expect(await exists(join(testDir, dir).toBeDefined()));
}
});
@@ -262,7 +262,7 @@ describe("SPARC Structure Creation Tests", () => {
];
for (const file of expectedFiles) {
- assertExists(await exists(join(testDir, file)));
+ expect(await exists(join(testDir, file).toBeDefined()));
}
});
diff --git a/tests/unit/cli/commands/init/validation.test.ts b/tests/unit/cli/commands/init/validation.test.ts
index 6c3bedaeab..7b0a6663ee 100644
--- a/tests/unit/cli/commands/init/validation.test.ts
+++ b/tests/unit/cli/commands/init/validation.test.ts
@@ -41,24 +41,24 @@ describe("Init Command Validation Tests", () => {
// Validate claude-flow-data.json
const dataPath = join(testDir, "memory/claude-flow-data.json");
- assertExists(await exists(dataPath));
+ expect(await exists(dataPath).toBeDefined());
const dataContent = await Deno.readTextFile(dataPath);
const data = JSON.parse(dataContent);
// Validate structure
- assertEquals(Array.isArray(data.agents), true);
- assertEquals(Array.isArray(data.tasks), true);
- assertEquals(typeof data.lastUpdated, "number");
- assertEquals(data.lastUpdated > 0, true);
+ expect(Array.isArray(data.agents)).toBe(true);
+ expect(Array.isArray(data.tasks)).toBe(true);
+ expect(typeof data.lastUpdated).toBe("number");
+ expect(data.lastUpdated > 0).toBe(true);
// Validate arrays are initially empty
- assertEquals(data.agents.length, 0);
- assertEquals(data.tasks.length, 0);
+ expect(data.agents.length).toBe(0);
+ expect(data.tasks.length).toBe(0);
// Validate timestamp is recent (within last minute)
const now = Date.now();
- assertEquals(Math.abs(now - data.lastUpdated) < 60000, true);
+ expect(Math.abs(now - data.lastUpdated) < 60000).toBe(true);
});
it("should create valid SPARC JSON files", async () => {
@@ -83,14 +83,14 @@ describe("Init Command Validation Tests", () => {
const roomodesData = JSON.parse(roomodesContent);
// Should have modes object
- assertEquals(typeof roomodesData.modes, "object");
- assertEquals(roomodesData.modes !== null, true);
+ expect(typeof roomodesData.modes).toBe("object");
+ expect(roomodesData.modes !== null).toBe(true);
// Should have essential SPARC modes
const requiredModes = ["architect", "code", "tdd", "spec-pseudocode", "integration"];
for (const mode of requiredModes) {
- assertExists(roomodesData.modes[mode]);
- assertEquals(typeof roomodesData.modes[mode], "object");
+ expect(roomodesData.modes[mode]).toBeDefined();
+ expect(typeof roomodesData.modes[mode]).toBe("object");
}
}
@@ -101,14 +101,14 @@ describe("Init Command Validation Tests", () => {
const workflowData = JSON.parse(workflowContent);
// Should have workflow structure
- assertEquals(typeof workflowData.name, "string");
- assertEquals(Array.isArray(workflowData.steps), true);
- assertEquals(workflowData.steps.length > 0, true);
+ expect(typeof workflowData.name).toBe("string");
+ expect(Array.isArray(workflowData.steps)).toBe(true);
+ expect(workflowData.steps.length > 0).toBe(true);
// Validate step structure
for (const step of workflowData.steps) {
- assertEquals(typeof step.name, "string");
- assertEquals(typeof step.description, "string");
+ expect(typeof step.name).toBe("string");
+ expect(typeof step.description).toBe("string");
}
}
});
@@ -138,20 +138,20 @@ describe("Init Command Validation Tests", () => {
for (const file of markdownFiles) {
const filePath = join(testDir, file);
- assertExists(await exists(filePath));
+ expect(await exists(filePath).toBeDefined());
const content = await Deno.readTextFile(filePath);
// Should start with header
- assertEquals(content.startsWith("#"), true);
+ expect(content.startsWith("#")).toBe(true);
// Should not have Windows line endings
- assertEquals(content.includes("\r"), false);
+ expect(content.includes("\r")).toBe(false);
// Should not have trailing spaces
const lines = content.split("\n");
for (const line of lines) {
- assertEquals(line.endsWith(" "), false);
+ expect(line.endsWith(" ")).toBe(false);
}
// Should have consistent header levels (no skipping)
@@ -160,12 +160,12 @@ describe("Init Command Validation Tests", () => {
.map(line => line.match(/^#+/)?.[0].length || 0);
// First header should be level 1
- assertEquals(headerLevels[0], 1);
+ expect(headerLevels[0]).toBe(1);
// No skipping levels (can't go from # to ###)
for (let i = 1; i < headerLevels.length; i++) {
const diff = headerLevels[i] - headerLevels[i - 1];
- assertEquals(diff <= 1, true); // Can only increase by 1 level at a time
+ expect(diff <= 1).toBe(true); // Can only increase by 1 level at a time
}
}
});
@@ -186,17 +186,17 @@ describe("Init Command Validation Tests", () => {
await command.output();
const executablePath = join(testDir, "claude-flow");
- assertExists(await exists(executablePath));
+ expect(await exists(executablePath).toBeDefined());
// Check file stats
const stat = await Deno.stat(executablePath);
- assertEquals(stat.isFile, true);
+ expect(stat.isFile).toBe(true);
// On Unix-like systems, check if it's executable
if (Deno.build.os !== "windows") {
- assertEquals(stat.mode !== null, true);
+ expect(stat.mode !== null).toBe(true);
// Check if user execute bit is set (at least 0o100)
- assertEquals((stat.mode! & 0o100) !== 0, true);
+ expect((stat.mode! & 0o100) !== 0).toBe(true);
}
});
});
@@ -233,21 +233,21 @@ describe("Init Command Validation Tests", () => {
for (const dir of requiredDirs) {
const dirPath = join(testDir, dir);
- assertExists(await exists(dirPath));
+ expect(await exists(dirPath).toBeDefined());
const stat = await Deno.stat(dirPath);
- assertEquals(stat.isDirectory, true);
+ expect(stat.isDirectory).toBe(true);
}
// Validate directory hierarchy
- assertExists(await exists(join(testDir, "memory")));
- assertExists(await exists(join(testDir, "memory/agents")));
- assertExists(await exists(join(testDir, "memory/sessions")));
+ expect(await exists(join(testDir, "memory").toBeDefined()));
+ expect(await exists(join(testDir, "memory/agents").toBeDefined()));
+ expect(await exists(join(testDir, "memory/sessions").toBeDefined()));
- assertExists(await exists(join(testDir, "coordination")));
- assertExists(await exists(join(testDir, "coordination/memory_bank")));
- assertExists(await exists(join(testDir, "coordination/subtasks")));
- assertExists(await exists(join(testDir, "coordination/orchestration")));
+ expect(await exists(join(testDir, "coordination").toBeDefined()));
+ expect(await exists(join(testDir, "coordination/memory_bank").toBeDefined()));
+ expect(await exists(join(testDir, "coordination/subtasks").toBeDefined()));
+ expect(await exists(join(testDir, "coordination/orchestration").toBeDefined()));
});
it("should create SPARC configuration correctly", async () => {
@@ -276,16 +276,16 @@ describe("Init Command Validation Tests", () => {
];
for (const dir of sparcDirs) {
- assertExists(await exists(join(testDir, dir)));
+ expect(await exists(join(testDir, dir).toBeDefined()));
}
// Validate SPARC configuration files
- assertExists(await exists(join(testDir, ".roomodes")));
- assertExists(await exists(join(testDir, ".roo/README.md")));
- assertExists(await exists(join(testDir, ".roo/workflows/basic-tdd.json")));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/README.md").toBeDefined()));
+ expect(await exists(join(testDir, ".roo/workflows/basic-tdd.json").toBeDefined()));
// Validate Claude commands for SPARC
- assertExists(await exists(join(testDir, ".claude/commands/sparc")));
+ expect(await exists(join(testDir, ".claude/commands/sparc").toBeDefined()));
});
it("should validate CLAUDE.md content structure", async () => {
@@ -545,10 +545,10 @@ describe("Init Command Validation Tests", () => {
// SPARC references should point to existing paths
if (claudeContent.includes(".roo/")) {
- assertExists(await exists(join(testDir, ".roo")));
+ expect(await exists(join(testDir, ".roo").toBeDefined()));
}
if (claudeContent.includes(".roomodes")) {
- assertExists(await exists(join(testDir, ".roomodes")));
+ expect(await exists(join(testDir, ".roomodes").toBeDefined()));
}
});
});
@@ -573,13 +573,13 @@ describe("Init Command Validation Tests", () => {
const data = JSON.parse(dataContent);
// Validate timestamp format
- assertEquals(typeof data.lastUpdated, "number");
- assertEquals(data.lastUpdated > 1000000000000, true); // After year 2001
- assertEquals(data.lastUpdated < 10000000000000, true); // Before year 2286
+ expect(typeof data.lastUpdated).toBe("number");
+ expect(data.lastUpdated > 1000000000000).toBe(true); // After year 2001
+ expect(data.lastUpdated < 10000000000000).toBe(true); // Before year 2286
// Should be a valid Date
const date = new Date(data.lastUpdated);
- assertEquals(isNaN(date.getTime()), false);
+ expect(isNaN(date.getTime())).toBe(false);
});
it("should validate workflow step format", async () => {
@@ -604,16 +604,16 @@ describe("Init Command Validation Tests", () => {
const workflow = JSON.parse(workflowContent);
// Validate workflow structure
- assertEquals(typeof workflow.name, "string");
- assertEquals(workflow.name.length > 0, true);
- assertEquals(Array.isArray(workflow.steps), true);
+ expect(typeof workflow.name).toBe("string");
+ expect(workflow.name.length > 0).toBe(true);
+ expect(Array.isArray(workflow.steps)).toBe(true);
// Validate each step
for (const step of workflow.steps) {
- assertEquals(typeof step.name, "string");
- assertEquals(step.name.length > 0, true);
- assertEquals(typeof step.description, "string");
- assertEquals(step.description.length > 0, true);
+ expect(typeof step.name).toBe("string");
+ expect(step.name.length > 0).toBe(true);
+ expect(typeof step.description).toBe("string");
+ expect(step.description.length > 0).toBe(true);
}
}
});
diff --git a/tests/unit/cli/start/process-manager.test.ts b/tests/unit/cli/start/process-manager.test.ts
index d20edfdf93..4f26003b97 100644
--- a/tests/unit/cli/start/process-manager.test.ts
+++ b/tests/unit/cli/start/process-manager.test.ts
@@ -2,8 +2,8 @@
* Comprehensive test suite for ProcessManager
*/
-import { assertEquals, assertExists, assertRejects, assertThrows } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { beforeEach, describe, it } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { ProcessManager } from '../../../../src/cli/commands/start/process-manager.ts';
import { ProcessStatus, ProcessType } from '../../../../src/cli/commands/start/types.ts';
@@ -17,61 +17,61 @@ describe('ProcessManager', () => {
describe('initialization', () => {
it('should initialize with all process definitions', () => {
const processes = processManager.getAllProcesses();
- assertEquals(processes.length, 6);
+ expect(processes.length).toBe(6);
const processIds = processes.map(p => p.id);
- assertEquals(processIds.includes('event-bus'), true);
- assertEquals(processIds.includes('orchestrator'), true);
- assertEquals(processIds.includes('memory-manager'), true);
- assertEquals(processIds.includes('terminal-pool'), true);
- assertEquals(processIds.includes('mcp-server'), true);
- assertEquals(processIds.includes('coordinator'), true);
+ expect(processIds.includes('event-bus')).toBe(true);
+ expect(processIds.includes('orchestrator')).toBe(true);
+ expect(processIds.includes('memory-manager')).toBe(true);
+ expect(processIds.includes('terminal-pool')).toBe(true);
+ expect(processIds.includes('mcp-server')).toBe(true);
+ expect(processIds.includes('coordinator')).toBe(true);
});
it('should initialize all processes with STOPPED status', () => {
const processes = processManager.getAllProcesses();
processes.forEach(process => {
- assertEquals(process.status, ProcessStatus.STOPPED);
+ expect(process.status).toBe(ProcessStatus.STOPPED);
});
});
it('should load configuration', async () => {
await processManager.initialize();
// Configuration should be loaded without errors
- assertExists(processManager);
+ expect(processManager).toBeDefined();
});
});
describe('getProcess', () => {
it('should return process by id', () => {
const process = processManager.getProcess('orchestrator');
- assertExists(process);
- assertEquals(process?.id, 'orchestrator');
- assertEquals(process?.type, ProcessType.ORCHESTRATOR);
+ expect(process).toBeDefined();
+ expect(process?.id).toBe('orchestrator');
+ expect(process?.type).toBe(ProcessType.ORCHESTRATOR);
});
it('should return undefined for unknown process', () => {
const process = processManager.getProcess('unknown');
- assertEquals(process, undefined);
+ expect(process).toBe(undefined);
});
});
describe('getAllProcesses', () => {
it('should return all processes', () => {
const processes = processManager.getAllProcesses();
- assertEquals(Array.isArray(processes), true);
- assertEquals(processes.length, 6);
+ expect(Array.isArray(processes)).toBe(true);
+ expect(processes.length).toBe(6);
});
});
describe('getSystemStats', () => {
it('should return correct initial stats', () => {
const stats = processManager.getSystemStats();
- assertEquals(stats.totalProcesses, 6);
- assertEquals(stats.runningProcesses, 0);
- assertEquals(stats.stoppedProcesses, 6);
- assertEquals(stats.errorProcesses, 0);
- assertEquals(stats.systemUptime, 0);
+ expect(stats.totalProcesses).toBe(6);
+ expect(stats.runningProcesses).toBe(0);
+ expect(stats.stoppedProcesses).toBe(6);
+ expect(stats.errorProcesses).toBe(0);
+ expect(stats.systemUptime).toBe(0);
});
});
@@ -97,9 +97,9 @@ describe('ProcessManager', () => {
await processManager.startProcess(processId);
const process = processManager.getProcess(processId);
- assertEquals(process?.status, ProcessStatus.RUNNING);
- assertEquals(statusChanges.includes(ProcessStatus.STARTING), true);
- assertEquals(statusChanges.includes(ProcessStatus.RUNNING), true);
+ expect(process?.status).toBe(ProcessStatus.RUNNING);
+ expect(statusChanges.includes(ProcessStatus.STARTING)).toBe(true);
+ expect(statusChanges.includes(ProcessStatus.RUNNING)).toBe(true);
});
it('should set process start time', async () => {
@@ -108,8 +108,8 @@ describe('ProcessManager', () => {
await processManager.startProcess(processId);
const process = processManager.getProcess(processId);
- assertExists(process?.startTime);
- assertEquals(typeof process?.startTime, 'number');
+ expect(process?.startTime).toBeDefined();
+ expect(typeof process?.startTime).toBe('number');
});
it('should reject starting already running process', async () => {
@@ -135,9 +135,9 @@ describe('ProcessManager', () => {
await processManager.initialize();
await processManager.startProcess(processId);
- assertExists(eventData);
- assertEquals(eventData.processId, processId);
- assertExists(eventData.process);
+ expect(eventData).toBeDefined();
+ expect(eventData.processId).toBe(processId);
+ expect(eventData.process).toBeDefined();
});
it('should handle process start errors', async () => {
@@ -157,8 +157,8 @@ describe('ProcessManager', () => {
'Required components not initialized'
);
- assertExists(errorEvent);
- assertEquals(errorEvent.processId, processId);
+ expect(errorEvent).toBeDefined();
+ expect(errorEvent.processId).toBe(processId);
});
});
@@ -187,7 +187,7 @@ describe('ProcessManager', () => {
await processManager.stopProcess(processId);
const process = processManager.getProcess(processId);
- assertEquals(process?.status, ProcessStatus.STOPPED);
+ expect(process?.status).toBe(ProcessStatus.STOPPED);
});
it('should emit processStopped event', async () => {
@@ -202,8 +202,8 @@ describe('ProcessManager', () => {
await processManager.startProcess(processId);
await processManager.stopProcess(processId);
- assertExists(stoppedEvent);
- assertEquals(stoppedEvent.processId, processId);
+ expect(stoppedEvent).toBeDefined();
+ expect(stoppedEvent.processId).toBe(processId);
});
});
@@ -221,10 +221,10 @@ describe('ProcessManager', () => {
await processManager.restartProcess(processId);
const process = processManager.getProcess(processId);
- assertEquals(process?.status, ProcessStatus.RUNNING);
- assertExists(process?.startTime);
+ expect(process?.status).toBe(ProcessStatus.RUNNING);
+ expect(process?.startTime).toBeDefined();
// New start time should be different
- assertEquals(process?.startTime !== firstStartTime, true);
+ expect(process?.startTime !== firstStartTime).toBe(true);
});
});
@@ -249,7 +249,7 @@ describe('ProcessManager', () => {
'orchestrator'
];
- assertEquals(startedProcesses.slice(0, 5), expectedOrder.slice(0, 5));
+ expect(startedProcesses.slice(0).toBe(5), expectedOrder.slice(0, 5));
// Orchestrator might fail due to missing dependencies, that's ok
});
@@ -258,7 +258,7 @@ describe('ProcessManager', () => {
await processManager.startAll();
const stats = processManager.getSystemStats();
- assertEquals(stats.runningProcesses >= 5, true); // At least core processes
+ expect(stats.runningProcesses >= 5).toBe(true); // At least core processes
});
});
@@ -278,8 +278,8 @@ describe('ProcessManager', () => {
await processManager.stopAll();
// Should stop in reverse order
- assertEquals(stoppedProcesses[0], 'memory-manager');
- assertEquals(stoppedProcesses[1], 'event-bus');
+ expect(stoppedProcesses[0]).toBe('memory-manager');
+ expect(stoppedProcesses[1]).toBe('event-bus');
});
it('should handle stopping already stopped processes', async () => {
@@ -288,15 +288,15 @@ describe('ProcessManager', () => {
await processManager.stopAll(); // Should not throw
const stats = processManager.getSystemStats();
- assertEquals(stats.runningProcesses, 0);
+ expect(stats.runningProcesses).toBe(0);
});
});
describe('process logs', () => {
it('should return placeholder logs', async () => {
const logs = await processManager.getProcessLogs('event-bus', 10);
- assertEquals(Array.isArray(logs), true);
- assertEquals(logs.length, 2); // Placeholder returns 2 logs
+ expect(Array.isArray(logs)).toBe(true);
+ expect(logs.length).toBe(2); // Placeholder returns 2 logs
});
});
@@ -308,7 +308,7 @@ describe('ProcessManager', () => {
});
await processManager.initialize();
- assertEquals(initialized, true);
+ expect(initialized).toBe(true);
});
it('should emit error event on initialization failure', async () => {
@@ -326,7 +326,7 @@ describe('ProcessManager', () => {
// Expected to throw
}
- assertEquals(errorEmitted, true);
+ expect(errorEmitted).toBe(true);
});
});
@@ -342,8 +342,8 @@ describe('ProcessManager', () => {
}
const process = processManager.getProcess(processId);
- assertExists(process?.metrics?.lastError);
- assertEquals(process?.metrics?.lastError, 'Required components not initialized');
+ expect(process?.metrics?.lastError).toBeDefined();
+ expect(process?.metrics?.lastError).toBe('Required components not initialized');
});
});
});
\ No newline at end of file
diff --git a/tests/unit/cli/start/process-ui.test.ts b/tests/unit/cli/start/process-ui.test.ts
index f1362f5107..f6bf3c5f84 100644
--- a/tests/unit/cli/start/process-ui.test.ts
+++ b/tests/unit/cli/start/process-ui.test.ts
@@ -2,8 +2,8 @@
* Test suite for ProcessUI
*/
-import { assertEquals, assertExists } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { beforeEach, describe, it } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { ProcessUI } from '../../../../src/cli/commands/start/process-ui.ts';
import { ProcessManager } from '../../../../src/cli/commands/start/process-manager.ts';
import { ProcessStatus } from '../../../../src/cli/commands/start/types.ts';
@@ -19,7 +19,7 @@ describe('ProcessUI', () => {
describe('initialization', () => {
it('should create ProcessUI instance', () => {
- assertExists(processUI);
+ expect(processUI).toBeDefined();
});
it('should setup event listeners on ProcessManager', () => {
@@ -43,11 +43,11 @@ describe('ProcessUI', () => {
it('should format uptime correctly', () => {
const formatUptime = processUI['formatUptime'].bind(processUI);
- assertEquals(formatUptime(1000), '1s');
- assertEquals(formatUptime(60000), '1m 0s');
- assertEquals(formatUptime(3600000), '1h 0m');
- assertEquals(formatUptime(86400000), '1d 0h');
- assertEquals(formatUptime(90061000), '1d 1h'); // 1 day, 1 hour, 1 minute, 1 second
+ expect(formatUptime(1000)).toBe('1s');
+ expect(formatUptime(60000)).toBe('1m 0s');
+ expect(formatUptime(3600000)).toBe('1h 0m');
+ expect(formatUptime(86400000)).toBe('1d 0h');
+ expect(formatUptime(90061000)).toBe('1d 1h'); // 1 day, 1 hour, 1 minute, 1 second
});
it('should display correct status icons', () => {
@@ -65,8 +65,8 @@ describe('ProcessUI', () => {
// All should be defined and unique
const values = Object.values(displays);
- assertEquals(values.length, 6);
- assertEquals(new Set(values).size, 6); // All unique
+ expect(values.length).toBe(6);
+ expect(new Set(values).size).toBe(6); // All unique
});
});
@@ -84,7 +84,7 @@ describe('ProcessUI', () => {
};
await handleCommand('h');
- assertEquals(helpShown, true);
+ expect(helpShown).toBe(true);
// Restore
console.log = originalLog;
@@ -99,7 +99,7 @@ describe('ProcessUI', () => {
};
await handleCommand('r');
- assertEquals(renderCalled, true);
+ expect(renderCalled).toBe(true);
});
it('should handle invalid commands', async () => {
@@ -115,7 +115,7 @@ describe('ProcessUI', () => {
};
await handleCommand('xyz');
- assertEquals(invalidMessageShown, true);
+ expect(invalidMessageShown).toBe(true);
// Restore
console.log = originalLog;
@@ -132,8 +132,8 @@ describe('ProcessUI', () => {
};
await handleCommand('1');
- assertExists(menuShownForProcess);
- assertEquals(menuShownForProcess.id, 'event-bus');
+ expect(menuShownForProcess).toBeDefined();
+ expect(menuShownForProcess.id).toBe('event-bus');
});
});
@@ -148,7 +148,7 @@ describe('ProcessUI', () => {
await startProcess('event-bus');
const process = processManager.getProcess('event-bus');
- assertEquals(process?.status, ProcessStatus.RUNNING);
+ expect(process?.status).toBe(ProcessStatus.RUNNING);
});
it('should stop process', async () => {
@@ -160,7 +160,7 @@ describe('ProcessUI', () => {
await stopProcess('event-bus');
const process = processManager.getProcess('event-bus');
- assertEquals(process?.status, ProcessStatus.STOPPED);
+ expect(process?.status).toBe(ProcessStatus.STOPPED);
});
it('should restart process', async () => {
@@ -174,8 +174,8 @@ describe('ProcessUI', () => {
await restartProcess('event-bus');
const process = processManager.getProcess('event-bus');
- assertEquals(process?.status, ProcessStatus.RUNNING);
- assertEquals(process?.startTime !== firstStartTime, true);
+ expect(process?.status).toBe(ProcessStatus.RUNNING);
+ expect(process?.startTime !== firstStartTime).toBe(true);
});
it('should start all processes', async () => {
@@ -184,7 +184,7 @@ describe('ProcessUI', () => {
await startAll();
const stats = processManager.getSystemStats();
- assertEquals(stats.runningProcesses >= 5, true);
+ expect(stats.runningProcesses >= 5).toBe(true);
});
it('should stop all processes', async () => {
@@ -197,7 +197,7 @@ describe('ProcessUI', () => {
await stopAll();
const stats = processManager.getSystemStats();
- assertEquals(stats.runningProcesses, 0);
+ expect(stats.runningProcesses).toBe(0);
});
});
@@ -217,7 +217,7 @@ describe('ProcessUI', () => {
const mockProcess = processManager.getProcess('event-bus')!;
showProcessDetails(mockProcess);
- assertEquals(detailsShown, true);
+ expect(detailsShown).toBe(true);
// Restore
console.log = originalLog;
@@ -245,7 +245,7 @@ describe('ProcessUI', () => {
showProcessDetails(mockProcess);
- assertEquals(metricsShown, true);
+ expect(metricsShown).toBe(true);
// Restore
console.log = originalLog;
@@ -284,8 +284,8 @@ describe('ProcessUI', () => {
await handleExit();
- assertEquals(promptShown, true);
- assertEquals(stopCalled, true);
+ expect(promptShown).toBe(true);
+ expect(stopCalled).toBe(true);
// Restore
console.log = originalLog;
diff --git a/tests/unit/cli/start/system-monitor.test.ts b/tests/unit/cli/start/system-monitor.test.ts
index e17b00bd60..a565106820 100644
--- a/tests/unit/cli/start/system-monitor.test.ts
+++ b/tests/unit/cli/start/system-monitor.test.ts
@@ -2,8 +2,8 @@
* Test suite for SystemMonitor
*/
-import { assertEquals, assertExists } from 'https://deno.land/[email protected]/assert/mod.ts';
-import { beforeEach, describe, it } from 'https://deno.land/[email protected]/testing/bdd.ts';
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
+import { describe, it, beforeEach, afterEach, expect } from "../test.utils.ts";
import { SystemMonitor } from '../../../../src/cli/commands/start/system-monitor.ts';
import { ProcessManager } from '../../../../src/cli/commands/start/process-manager.ts';
import { eventBus } from '../../../../src/core/event-bus.ts';
@@ -20,7 +20,7 @@ describe('SystemMonitor', () => {
describe('initialization', () => {
it('should create SystemMonitor instance', () => {
- assertExists(systemMonitor);
+ expect(systemMonitor).toBeDefined();
});
it('should setup event listeners', () => {
@@ -32,7 +32,7 @@ describe('SystemMonitor', () => {
eventBus.emit(SystemEvents.TASK_COMPLETED, { taskId: 'task-1' });
const events = monitor.getRecentEvents(10);
- assertEquals(events.length >= 2, true);
+ expect(events.length >= 2).toBe(true);
});
});
@@ -46,9 +46,9 @@ describe('SystemMonitor', () => {
const events = systemMonitor.getRecentEvents(10);
const agentEvent = events.find(e => e.type === 'agent_spawned');
- assertExists(agentEvent);
- assertEquals(agentEvent?.data.agentId, 'agent-123');
- assertEquals(agentEvent?.level, 'info');
+ expect(agentEvent).toBeDefined();
+ expect(agentEvent?.data.agentId).toBe('agent-123');
+ expect(agentEvent?.level).toBe('info');
});
it('should track agent terminated events', () => {
@@ -60,9 +60,9 @@ describe('SystemMonitor', () => {
const events = systemMonitor.getRecentEvents(10);
const event = events.find(e => e.type === 'agent_terminated');
- assertExists(event);
- assertEquals(event?.data.reason, 'Task completed');
- assertEquals(event?.level, 'warning');
+ expect(event).toBeDefined();
+ expect(event?.data.reason).toBe('Task completed');
+ expect(event?.level).toBe('warning');
});
it('should track task events', () => {
@@ -86,13 +86,13 @@ describe('SystemMonitor', () => {
const completed = events.find(e => e.type === 'task_completed');
const failed = events.find(e => e.type === 'task_failed');
- assertExists(assigned);
- assertExists(completed);
- assertExists(failed);
+ expect(assigned).toBeDefined();
+ expect(completed).toBeDefined();
+ expect(failed).toBeDefined();
- assertEquals(assigned?.level, 'info');
- assertEquals(completed?.level, 'success');
- assertEquals(failed?.level, 'error');
+ expect(assigned?.level).toBe('info');
+ expect(completed?.level).toBe('success');
+ expect(failed?.level).toBe('error');
});
it('should track system errors', () => {
@@ -104,9 +104,9 @@ describe('SystemMonitor', () => {
const events = systemMonitor.getRecentEvents(10);
const errorEvent = events.find(e => e.type === 'system_error');
- assertExists(errorEvent);
- assertEquals(errorEvent?.data.component, 'TestComponent');
- assertEquals(errorEvent?.level, 'error');
+ expect(errorEvent).toBeDefined();
+ expect(errorEvent?.data.component).toBe('TestComponent');
+ expect(errorEvent?.level).toBe('error');
});
it('should track process manager events', () => {
@@ -130,9 +130,9 @@ describe('SystemMonitor', () => {
const stopped = events.find(e => e.type === 'process_stopped');
const error = events.find(e => e.type === 'process_error');
- assertExists(started);
- assertExists(stopped);
- assertExists(error);
+ expect(started).toBeDefined();
+ expect(stopped).toBeDefined();
+ expect(error).toBeDefined();
});
it('should limit stored events to maxEvents', () => {
@@ -145,7 +145,7 @@ describe('SystemMonitor', () => {
}
const events = systemMonitor.getRecentEvents(200);
- assertEquals(events.length <= 100, true);
+ expect(events.length <= 100).toBe(true);
});
});
@@ -157,39 +157,39 @@ describe('SystemMonitor', () => {
type: 'agent_spawned',
data: { agentId: 'agent-1', profile: { type: 'researcher' } }
});
- assertEquals(agentSpawnedMsg.includes('Agent spawned'), true);
- assertEquals(agentSpawnedMsg.includes('agent-1'), true);
- assertEquals(agentSpawnedMsg.includes('researcher'), true);
+ expect(agentSpawnedMsg.includes('Agent spawned')).toBe(true);
+ expect(agentSpawnedMsg.includes('agent-1')).toBe(true);
+ expect(agentSpawnedMsg.includes('researcher')).toBe(true);
const taskCompletedMsg = formatMessage({
type: 'task_completed',
data: { taskId: 'task-1' }
});
- assertEquals(taskCompletedMsg.includes('Task completed'), true);
- assertEquals(taskCompletedMsg.includes('task-1'), true);
+ expect(taskCompletedMsg.includes('Task completed')).toBe(true);
+ expect(taskCompletedMsg.includes('task-1')).toBe(true);
const systemErrorMsg = formatMessage({
type: 'system_error',
data: { component: 'TestComp', error: { message: 'Error msg' } }
});
- assertEquals(systemErrorMsg.includes('System error'), true);
- assertEquals(systemErrorMsg.includes('TestComp'), true);
- assertEquals(systemErrorMsg.includes('Error msg'), true);
+ expect(systemErrorMsg.includes('System error')).toBe(true);
+ expect(systemErrorMsg.includes('TestComp')).toBe(true);
+ expect(systemErrorMsg.includes('Error msg')).toBe(true);
});
it('should get correct event icons', () => {
const getIcon = systemMonitor['getEventIcon'].bind(systemMonitor);
- assertEquals(getIcon('agent_spawned'), 'πŸ€–');
- assertEquals(getIcon('agent_terminated'), 'πŸ”š');
- assertEquals(getIcon('task_assigned'), 'πŸ“Œ');
- assertEquals(getIcon('task_completed'), 'βœ…');
- assertEquals(getIcon('task_failed'), '❌');
- assertEquals(getIcon('system_error'), '⚠️');
- assertEquals(getIcon('process_started'), '▢️');
- assertEquals(getIcon('process_stopped'), '⏹️');
- assertEquals(getIcon('process_error'), '🚨');
- assertEquals(getIcon('unknown'), 'β€’');
+ expect(getIcon('agent_spawned')).toBe('πŸ€–');
+ expect(getIcon('agent_terminated')).toBe('πŸ”š');
+ expect(getIcon('task_assigned')).toBe('πŸ“Œ');
+ expect(getIcon('task_completed')).toBe('βœ…');
+ expect(getIcon('task_failed')).toBe('❌');
+ expect(getIcon('system_error')).toBe('⚠️');
+ expect(getIcon('process_started')).toBe('▢️');
+ expect(getIcon('process_stopped')).toBe('⏹️');
+ expect(getIcon('process_error')).toBe('🚨');
+ expect(getIcon('unknown')).toBe('β€’');
});
});
@@ -205,11 +205,11 @@ describe('SystemMonitor', () => {
}) as any;
globalThis.clearInterval = ((id: number) => {
- assertEquals(id, intervalId);
+ expect(id).toBe(intervalId);
}) as any;
systemMonitor.start();
- assertExists(intervalId);
+ expect(intervalId).toBeDefined();
systemMonitor.stop();
@@ -226,10 +226,10 @@ describe('SystemMonitor', () => {
systemMonitor['collectMetrics']();
const process = processManager.getProcess('event-bus');
- assertExists(process?.metrics?.cpu);
- assertExists(process?.metrics?.memory);
- assertEquals(typeof process?.metrics?.cpu, 'number');
- assertEquals(typeof process?.metrics?.memory, 'number');
+ expect(process?.metrics?.cpu).toBeDefined();
+ expect(process?.metrics?.memory).toBeDefined();
+ expect(typeof process?.metrics?.cpu).toBe('number');
+ expect(typeof process?.metrics?.memory).toBe('number');
});
});
@@ -250,9 +250,9 @@ describe('SystemMonitor', () => {
// Check output contains expected content
const output = logOutput.join('\n');
- assertEquals(output.includes('Recent System Events'), true);
- assertEquals(output.includes('Agent spawned'), true);
- assertEquals(output.includes('Task completed'), true);
+ expect(output.includes('Recent System Events')).toBe(true);
+ expect(output.includes('Agent spawned')).toBe(true);
+ expect(output.includes('Task completed')).toBe(true);
// Restore
console.log = originalLog;
@@ -275,11 +275,11 @@ describe('SystemMonitor', () => {
// Check output contains expected content
const output = logOutput.join('\n');
- assertEquals(output.includes('System Health'), true);
- assertEquals(output.includes('Status:'), true);
- assertEquals(output.includes('Uptime:'), true);
- assertEquals(output.includes('Process Status:'), true);
- assertEquals(output.includes('System Metrics:'), true);
+ expect(output.includes('System Health')).toBe(true);
+ expect(output.includes('Status:')).toBe(true);
+ expect(output.includes('Uptime:')).toBe(true);
+ expect(output.includes('Process Status:')).toBe(true);
+ expect(output.includes('System Metrics:')).toBe(true);
// Restore
console.log = originalLog;
@@ -303,8 +303,8 @@ describe('SystemMonitor', () => {
// Check output contains error section
const output = logOutput.join('\n');
- assertEquals(output.includes('Recent Errors:'), true);
- assertEquals(output.includes('TestComponent'), true);
+ expect(output.includes('Recent Errors:')).toBe(true);
+ expect(output.includes('TestComponent')).toBe(true);
// Restore
console.log = originalLog;
@@ -315,11 +315,11 @@ describe('SystemMonitor', () => {
it('should format uptime correctly', () => {
const formatUptime = systemMonitor['formatUptime'].bind(systemMonitor);
- assertEquals(formatUptime(1000), '1s');
- assertEquals(formatUptime(60000), '1m 0s');
- assertEquals(formatUptime(3600000), '1h 0m 0s');
- assertEquals(formatUptime(86400000), '1d 0h 0m');
- assertEquals(formatUptime(90061000), '1d 1h 1m');
+ expect(formatUptime(1000)).toBe('1s');
+ expect(formatUptime(60000)).toBe('1m 0s');
+ expect(formatUptime(3600000)).toBe('1h 0m 0s');
+ expect(formatUptime(86400000)).toBe('1d 0h 0m');
+ expect(formatUptime(90061000)).toBe('1d 1h 1m');
});
});
});
\ No newline at end of file
diff --git a/tests/unit/coordination/coordination-system.test.ts b/tests/unit/coordination/coordination-system.test.ts
index bed06d54bd..f2545d95ed 100644
--- a/tests/unit/coordination/coordination-system.test.ts
+++ b/tests/unit/coordination/coordination-system.test.ts
@@ -3,10 +3,10 @@
* Tests deadlock detection, task scheduling, and resource management
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertRejects, assertThrows } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
-import { spy, stub } from "https://deno.land/[email protected]/testing/mock.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { expect } from "@jest/globals";
+// FakeTime equivalent available in test.utils.ts
+import { spy, stub } from "../test.utils.ts";
import { CoordinationManager } from '../../../src/coordination/manager.ts';
import { TaskScheduler } from '../../../src/coordination/scheduler.ts';
@@ -88,9 +88,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// Verify all tasks completed
- assertEquals(results.length, 4);
+ expect(results.length).toBe(4);
tasks.forEach(task => {
- assertEquals(task.execute.calls.length, 1);
+ expect(task.execute.calls.length).toBe(1);
});
});
@@ -137,9 +137,9 @@ describe('Coordination System - Comprehensive Tests', () => {
await Promise.all(promises);
// Verify execution order respected dependencies
- assertEquals(executionOrder[0], 'task-a');
- assertEquals(executionOrder[1], 'task-b');
- assertEquals(executionOrder[2], 'task-c');
+ expect(executionOrder[0]).toBe('task-a');
+ expect(executionOrder[1]).toBe('task-b');
+ expect(executionOrder[2]).toBe('task-c');
});
it('should detect and handle circular dependencies', async () => {
@@ -158,11 +158,11 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.allSettled(promises);
const failures = results.filter(r => r.status === 'rejected');
- assertEquals(failures.length >= 1, true);
+ expect(failures.length >= 1).toBe(true);
// Verify circular dependency was detected
const error = failures[0] as PromiseRejectedResult;
- assertEquals(error.reason.message.includes('circular'), true);
+ expect(error.reason.message.includes('circular')).toBe(true);
});
it('should handle task timeouts correctly', async () => {
@@ -194,9 +194,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
- assertEquals(results.length, 20);
+ expect(results.length).toBe(20);
results.forEach((result, i) => {
- assertEquals(result, `result-${tasks[i].id}`);
+ expect(result).toBe(`result-${tasks[i].id}`);
});
});
@@ -282,7 +282,7 @@ describe('Coordination System - Comprehensive Tests', () => {
const failures = results.filter(r => r.status === 'rejected');
// Deadlock detection should prevent both from hanging
- assertEquals(successes.length + failures.length, 2);
+ expect(successes.length + failures.length).toBe(2);
});
it('should prevent resource starvation', async () => {
@@ -320,8 +320,8 @@ describe('Coordination System - Comprehensive Tests', () => {
const successes = allResults.filter(r => r.status === 'fulfilled');
// Low priority task should eventually complete (no starvation)
- assertEquals(successes.length, 6);
- assertEquals(lowPriorityTask.execute.calls.length, 1);
+ expect(successes.length).toBe(6);
+ expect(lowPriorityTask.execute.calls.length).toBe(1);
});
it('should handle complex dependency chains without deadlock', async () => {
@@ -342,9 +342,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
- assertEquals(results.length, 7);
+ expect(results.length).toBe(7);
tasks.forEach(task => {
- assertEquals(task.execute.calls.length, 1);
+ expect(task.execute.calls.length).toBe(1);
});
});
@@ -381,8 +381,8 @@ describe('Coordination System - Comprehensive Tests', () => {
const successes = results.filter(r => r.status === 'fulfilled');
const failures = results.filter(r => r.status === 'rejected');
- assertEquals(successes.length >= 1, true);
- assertEquals(failures.length >= 1, true);
+ expect(successes.length >= 1).toBe(true);
+ expect(failures.length >= 1).toBe(true);
});
});
@@ -410,11 +410,11 @@ describe('Coordination System - Comprehensive Tests', () => {
await AsyncTestUtils.delay(50);
const resourceStatus = await resourceManager.getResourceStatus();
- assertExists(resourceStatus);
+ expect(resourceStatus).toBeDefined();
// Should track active resource usage
- assertEquals(typeof resourceStatus.memoryUsage, 'number');
- assertEquals(typeof resourceStatus.activeResources, 'object');
+ expect(typeof resourceStatus.memoryUsage).toBe('number');
+ expect(typeof resourceStatus.activeResources).toBe('object');
await Promise.all(promises);
});
@@ -466,9 +466,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// All tasks should complete, but serialized due to exclusive resource
- assertEquals(results.length, 3);
+ expect(results.length).toBe(3);
tasks.forEach(task => {
- assertEquals(task.execute.calls.length, 1);
+ expect(task.execute.calls.length).toBe(1);
});
});
@@ -527,7 +527,7 @@ describe('Coordination System - Comprehensive Tests', () => {
// Resource should be cleaned up and available for next task
const result = await coordinationManager.submitTask('followup-task', followupTask);
- assertEquals(result, 'followup-complete');
+ expect(result).toBe('followup-complete');
});
});
@@ -565,9 +565,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// Both should complete, high priority first
- assertEquals(results.length, 2);
- assertEquals(results.includes('high-priority'), true);
- assertEquals(results.includes('low-priority'), true);
+ expect(results.length).toBe(2);
+ expect(results.includes('high-priority')).toBe(true);
+ expect(results.includes('low-priority')).toBe(true);
});
it('should handle timestamp-based conflict resolution', async () => {
@@ -604,8 +604,8 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all([firstPromise, secondPromise]);
// First submitted should win
- assertEquals(results[0], 'first');
- assertEquals(results[1], 'second');
+ expect(results[0]).toBe('first');
+ expect(results[1]).toBe('second');
});
it('should handle conflict escalation', async () => {
@@ -630,9 +630,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// All tasks should complete despite conflicts
- assertEquals(results.length, 5);
+ expect(results.length).toBe(5);
escalationTasks.forEach(task => {
- assertEquals(task.execute.calls.length, 1);
+ expect(task.execute.calls.length).toBe(1);
});
});
@@ -671,9 +671,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// Should resolve conflicts and complete all tasks
- assertEquals(results.length, 3);
+ expect(results.length).toBe(3);
nestedConflictTasks.forEach(task => {
- assertEquals(task.execute.calls.length, 1);
+ expect(task.execute.calls.length).toBe(1);
});
});
});
@@ -729,14 +729,14 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// All tasks should complete
- assertEquals(results.length, 12);
+ expect(results.length).toBe(12);
// Work stealing should have balanced the load
const agent1Results = results.filter(r => r.startsWith('agent1'));
const agent2Results = results.filter(r => r.startsWith('agent2'));
- assertEquals(agent1Results.length, 10);
- assertEquals(agent2Results.length, 2);
+ expect(agent1Results.length).toBe(10);
+ expect(agent2Results.length).toBe(2);
});
it('should implement priority aging', async () => {
@@ -765,9 +765,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// Priority aging should eventually elevate old low priority task
- assertEquals(results.length, 2);
- assertEquals(oldLowPriorityTask.execute.calls.length, 1);
- assertEquals(newHighPriorityTask.execute.calls.length, 1);
+ expect(results.length).toBe(2);
+ expect(oldLowPriorityTask.execute.calls.length).toBe(1);
+ expect(newHighPriorityTask.execute.calls.length).toBe(1);
});
it('should support dynamic priority adjustment', async () => {
@@ -790,7 +790,7 @@ describe('Coordination System - Comprehensive Tests', () => {
await advancedScheduler.adjustTaskPriority('adjustable', 'critical');
const result = await taskPromise;
- assertEquals(result, 'adjustable-complete');
+ expect(result).toBe('adjustable-complete');
});
it('should handle load balancing across multiple schedulers', async () => {
@@ -817,9 +817,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const results = await Promise.all(promises);
// Load balancing should distribute tasks across schedulers
- assertEquals(results.length, 30);
+ expect(results.length).toBe(30);
tasks.forEach(task => {
- assertEquals(task.execute.calls.length, 1);
+ expect(task.execute.calls.length).toBe(1);
});
});
});
@@ -860,7 +860,7 @@ describe('Coordination System - Comprehensive Tests', () => {
const duration = Date.now() - startTime;
- assertEquals(results.length, 1000);
+ expect(results.length).toBe(1000);
TestAssertions.assertInRange(duration, 0, 10000); // Should complete within 10 seconds
console.log(`Large batch (1000 tasks) completed in ${duration}ms`);
@@ -887,7 +887,7 @@ describe('Coordination System - Comprehensive Tests', () => {
await Promise.all(promises);
});
- assertEquals(leaked, false);
+ expect(leaked).toBe(false);
});
it('should handle load testing scenario', async () => {
@@ -934,7 +934,7 @@ describe('Coordination System - Comprehensive Tests', () => {
await coordinationManager.submitTask(`error-task-${scenario.name}`, failingTask);
} catch (error) {
// May still fail after retries
- assertExists(error);
+ expect(error).toBeDefined();
}
} else {
// Should fail fast for non-recoverable errors
@@ -967,8 +967,8 @@ describe('Coordination System - Comprehensive Tests', () => {
// Should eventually succeed after scheduler recovers
const result = await coordinationManager.submitTask('resilient-task', resilientTask);
- assertEquals(result, 'recovered');
- assertEquals(failureCount, 3);
+ expect(result).toBe('recovered');
+ expect(failureCount).toBe(3);
});
it('should handle resource manager failures', async () => {
@@ -992,7 +992,7 @@ describe('Coordination System - Comprehensive Tests', () => {
// Should recover from resource manager failure
const result = await coordinationManager.submitTask('resource-task', resourceTask);
- assertEquals(result, 'resource-task-complete');
+ expect(result).toBe('resource-task-complete');
});
it('should handle partial system failures', async () => {
@@ -1017,12 +1017,12 @@ describe('Coordination System - Comprehensive Tests', () => {
const failures = results.filter(r => r.status === 'rejected');
// Should have partial success
- assertEquals(successes.length, 7); // 7 out of 10 should succeed
- assertEquals(failures.length, 3);
+ expect(successes.length).toBe(7); // 7 out of 10 should succeed
+ expect(failures.length).toBe(3);
// System should remain functional
const healthStatus = await coordinationManager.getHealthStatus();
- assertEquals(healthStatus.healthy, true);
+ expect(healthStatus.healthy).toBe(true);
});
it('should implement circuit breaker pattern', async () => {
@@ -1051,7 +1051,7 @@ describe('Coordination System - Comprehensive Tests', () => {
}
// Circuit should be open now
- assertEquals(circuitBreaker.getState().state, 'open');
+ expect(circuitBreaker.getState().state).toBe('open');
// Should fail fast while open
await TestAssertions.assertThrowsAsync(
@@ -1065,7 +1065,7 @@ describe('Coordination System - Comprehensive Tests', () => {
// Should succeed after circuit resets
const result = await circuitBreaker.execute(flakyService);
- assertEquals(result, 'service-success');
+ expect(result).toBe('service-success');
});
});
@@ -1089,13 +1089,13 @@ describe('Coordination System - Comprehensive Tests', () => {
const metrics = await coordinationManager.getMetrics();
- assertExists(metrics);
- assertEquals(typeof metrics.totalTasksSubmitted, 'number');
- assertEquals(typeof metrics.totalTasksCompleted, 'number');
- assertEquals(typeof metrics.averageExecutionTime, 'number');
- assertEquals(typeof metrics.currentActiveTasks, 'number');
+ expect(metrics).toBeDefined();
+ expect(typeof metrics.totalTasksSubmitted).toBe('number');
+ expect(typeof metrics.totalTasksCompleted).toBe('number');
+ expect(typeof metrics.averageExecutionTime).toBe('number');
+ expect(typeof metrics.currentActiveTasks).toBe('number');
- assertEquals(metrics.totalTasksCompleted, 10);
+ expect(metrics.totalTasksCompleted).toBe(10);
TestAssertions.assertInRange(metrics.averageExecutionTime, 10, 100);
});
@@ -1118,23 +1118,23 @@ describe('Coordination System - Comprehensive Tests', () => {
const resourceMetrics = await resourceManager.getMetrics();
- assertExists(resourceMetrics);
- assertEquals(typeof resourceMetrics.peakMemoryUsage, 'number');
- assertEquals(typeof resourceMetrics.averageMemoryUsage, 'number');
- assertEquals(typeof resourceMetrics.resourceUtilization, 'object');
+ expect(resourceMetrics).toBeDefined();
+ expect(typeof resourceMetrics.peakMemoryUsage).toBe('number');
+ expect(typeof resourceMetrics.averageMemoryUsage).toBe('number');
+ expect(typeof resourceMetrics.resourceUtilization).toBe('object');
});
it('should provide health status information', async () => {
const healthStatus = await coordinationManager.getHealthStatus();
- assertExists(healthStatus);
- assertEquals(typeof healthStatus.healthy, 'boolean');
- assertEquals(typeof healthStatus.components, 'object');
+ expect(healthStatus).toBeDefined();
+ expect(typeof healthStatus.healthy).toBe('boolean');
+ expect(typeof healthStatus.components).toBe('object');
// Check individual component health
- assertEquals(typeof healthStatus.components.scheduler, 'object');
- assertEquals(typeof healthStatus.components.resourceManager, 'object');
- assertEquals(typeof healthStatus.components.conflictResolver, 'object');
+ expect(typeof healthStatus.components.scheduler).toBe('object');
+ expect(typeof healthStatus.components.resourceManager).toBe('object');
+ expect(typeof healthStatus.components.conflictResolver).toBe('object');
});
it('should detect performance degradation', async () => {
@@ -1158,9 +1158,9 @@ describe('Coordination System - Comprehensive Tests', () => {
const performanceMetrics = await coordinationManager.getPerformanceMetrics();
- assertExists(performanceMetrics);
- assertEquals(typeof performanceMetrics.throughput, 'number');
- assertEquals(typeof performanceMetrics.latency, 'object');
+ expect(performanceMetrics).toBeDefined();
+ expect(typeof performanceMetrics.throughput).toBe('number');
+ expect(typeof performanceMetrics.latency).toBe('object');
// Should detect degradation in throughput
TestAssertions.assertInRange(performanceMetrics.throughput, 0.01, 1.0); // tasks per ms
diff --git a/tests/unit/coordination/coordination.test.ts b/tests/unit/coordination/coordination.test.ts
index ec419adda6..7b9979984f 100644
--- a/tests/unit/coordination/coordination.test.ts
+++ b/tests/unit/coordination/coordination.test.ts
@@ -61,7 +61,7 @@ describe('CoordinationManager', () => {
it('should initialize all components', async () => {
await manager.initialize();
- assertEquals(mocks.logger.hasLog('info', 'Coordination manager initialized'), true);
+ expect(mocks.logger.hasLog('info').toBe('Coordination manager initialized'), true);
});
it('should start deadlock detection if enabled', async () => {
@@ -71,7 +71,7 @@ describe('CoordinationManager', () => {
// Fast forward to trigger deadlock detection
await time.tickAsync(10000);
- assertEquals(mocks.logger.hasLog('debug', 'Check for deadlock'), false); // No deadlocks expected
+ expect(mocks.logger.hasLog('debug').toBe('Check for deadlock'), false); // No deadlocks expected
});
it('should not initialize twice', async () => {
@@ -94,7 +94,7 @@ describe('CoordinationManager', () => {
await manager.assignTask(task, agentId);
const taskCount = await manager.getAgentTaskCount(agentId);
- assertEquals(taskCount, 1);
+ expect(taskCount).toBe(1);
});
it('should get agent tasks', async () => {
@@ -104,8 +104,8 @@ describe('CoordinationManager', () => {
await manager.assignTask(task, agentId);
const tasks = await manager.getAgentTasks(agentId);
- assertEquals(tasks.length, 1);
- assertEquals(tasks[0].id, task.id);
+ expect(tasks.length).toBe(1);
+ expect(tasks[0].id).toBe(task.id);
});
it('should cancel task', async () => {
@@ -116,7 +116,7 @@ describe('CoordinationManager', () => {
await manager.cancelTask(task.id);
const taskCount = await manager.getAgentTaskCount(agentId);
- assertEquals(taskCount, 0);
+ expect(taskCount).toBe(0);
});
});
@@ -166,7 +166,7 @@ describe('CoordinationManager', () => {
// Verify message was sent via event
const events = mocks.eventBus.getEvents();
const messageEvent = events.find(e => e.event === SystemEvents.MESSAGE_SENT);
- assertExists(messageEvent);
+ expect(messageEvent).toBeDefined();
});
});
@@ -186,7 +186,7 @@ describe('CoordinationManager', () => {
await time.tickAsync(10000);
// No errors should occur
- assertEquals(mocks.logger.hasLog('error', 'Error during deadlock detection'), false);
+ expect(mocks.logger.hasLog('error').toBe('Error during deadlock detection'), false);
});
});
@@ -198,8 +198,8 @@ describe('CoordinationManager', () => {
it('should return healthy status', async () => {
const health = await manager.getHealthStatus();
- assertEquals(health.healthy, true);
- assertExists(health.metrics);
+ expect(health.healthy).toBe(true);
+ expect(health.metrics).toBeDefined();
});
it('should handle component failures', async () => {
@@ -207,7 +207,7 @@ describe('CoordinationManager', () => {
// This would require mocking the internal components
const health = await manager.getHealthStatus();
- assertExists(health);
+ expect(health).toBeDefined();
});
});
@@ -220,7 +220,7 @@ describe('CoordinationManager', () => {
await manager.performMaintenance();
// Verify maintenance was performed
- assertEquals(mocks.logger.hasLog('debug', 'Performing coordination manager maintenance'), true);
+ expect(mocks.logger.hasLog('debug').toBe('Performing coordination manager maintenance'), true);
});
});
});
@@ -252,7 +252,7 @@ describe('WorkStealingCoordinator', () => {
it('should initialize when enabled', async () => {
await coordinator.initialize();
- assertEquals(mocks.logger.hasLog('info', 'Initializing work stealing coordinator'), true);
+ expect(mocks.logger.hasLog('info').toBe('Initializing work stealing coordinator'), true);
});
it('should not initialize when disabled', async () => {
@@ -261,7 +261,7 @@ describe('WorkStealingCoordinator', () => {
await coordinator.initialize();
- assertEquals(mocks.logger.hasLog('info', 'Work stealing is disabled'), true);
+ expect(mocks.logger.hasLog('info').toBe('Work stealing is disabled'), true);
});
it('should update agent workload', () => {
@@ -276,7 +276,7 @@ describe('WorkStealingCoordinator', () => {
});
const stats = coordinator.getWorkloadStats();
- assertEquals(stats.totalAgents, 1);
+ expect(stats.totalAgents).toBe(1);
});
it('should record task duration', () => {
@@ -285,7 +285,7 @@ describe('WorkStealingCoordinator', () => {
// Verify average is updated
const stats = coordinator.getWorkloadStats();
- assertExists(stats.workloads);
+ expect(stats.workloads).toBeDefined();
});
it('should find best agent for task', () => {
@@ -324,7 +324,7 @@ describe('WorkStealingCoordinator', () => {
});
const bestAgent = coordinator.findBestAgent(task, agents);
- assertEquals(bestAgent, 'agent-1'); // Better capability match
+ expect(bestAgent).toBe('agent-1'); // Better capability match
});
});
@@ -349,7 +349,7 @@ describe('DependencyGraph', () => {
});
graph.addTask(task);
- assertEquals(graph.isTaskReady('task-1'), true);
+ expect(graph.isTaskReady('task-1')).toBe(true);
});
it('should add task with completed dependencies', () => {
@@ -366,7 +366,7 @@ describe('DependencyGraph', () => {
graph.markCompleted('task-1');
graph.addTask(task2);
- assertEquals(graph.isTaskReady('task-2'), true);
+ expect(graph.isTaskReady('task-2')).toBe(true);
});
it('should handle task completion and mark dependents ready', () => {
@@ -382,11 +382,11 @@ describe('DependencyGraph', () => {
graph.addTask(task1);
graph.addTask(task2);
- assertEquals(graph.isTaskReady('task-2'), false);
+ expect(graph.isTaskReady('task-2')).toBe(false);
const readyTasks = graph.markCompleted('task-1');
- assertEquals(readyTasks, ['task-2']);
- assertEquals(graph.isTaskReady('task-2'), true);
+ expect(readyTasks).toBe(['task-2']);
+ expect(graph.isTaskReady('task-2')).toBe(true);
});
it('should detect circular dependencies', () => {
@@ -406,7 +406,7 @@ describe('DependencyGraph', () => {
// In real implementation, this would be caught during validation
const cycles = graph.detectCycles();
// No cycles yet since we haven't added the circular dependency
- assertEquals(cycles.length, 0);
+ expect(cycles.length).toBe(0);
});
it('should perform topological sort', () => {
@@ -428,10 +428,10 @@ describe('DependencyGraph', () => {
graph.addTask(task3);
const sorted = graph.topologicalSort();
- assertExists(sorted);
- assertEquals(sorted[0], 'task-1');
- assertEquals(sorted[1], 'task-2');
- assertEquals(sorted[2], 'task-3');
+ expect(sorted).toBeDefined();
+ expect(sorted[0]).toBe('task-1');
+ expect(sorted[1]).toBe('task-2');
+ expect(sorted[2]).toBe('task-3');
});
it('should find critical path', () => {
@@ -448,8 +448,8 @@ describe('DependencyGraph', () => {
graph.addTask(task2);
const criticalPath = graph.findCriticalPath();
- assertExists(criticalPath);
- assertEquals(criticalPath.path.length, 2);
+ expect(criticalPath).toBeDefined();
+ expect(criticalPath.path.length).toBe(2);
});
it('should export to DOT format', () => {
@@ -466,8 +466,8 @@ describe('DependencyGraph', () => {
graph.addTask(task2);
const dot = graph.toDot();
- assertEquals(dot.includes('digraph TaskDependencies'), true);
- assertEquals(dot.includes('"task-1" -> "task-2"'), true);
+ expect(dot.includes('digraph TaskDependencies')).toBe(true);
+ expect(dot.includes('"task-1" -> "task-2"')).toBe(true);
});
});
@@ -495,12 +495,12 @@ describe('CircuitBreaker', () => {
});
it('should start in closed state', () => {
- assertEquals(breaker.getState(), CircuitState.CLOSED);
+ expect(breaker.getState()).toBe(CircuitState.CLOSED);
});
it('should execute function successfully', async () => {
const result = await breaker.execute(async () => 'success');
- assertEquals(result, 'success');
+ expect(result).toBe('success');
});
it('should open after failure threshold', async () => {
@@ -513,7 +513,7 @@ describe('CircuitBreaker', () => {
} catch {}
}
- assertEquals(breaker.getState(), CircuitState.OPEN);
+ expect(breaker.getState()).toBe(CircuitState.OPEN);
});
it('should reject requests when open', async () => {
@@ -539,16 +539,16 @@ describe('CircuitBreaker', () => {
await breaker.execute(async () => 'success');
} catch {}
- assertEquals(breaker.getState(), CircuitState.CLOSED); // Should close after success
+ expect(breaker.getState()).toBe(CircuitState.CLOSED); // Should close after success
});
it('should track metrics', () => {
const metrics = breaker.getMetrics();
- assertExists(metrics.state);
- assertEquals(metrics.failures, 0);
- assertEquals(metrics.successes, 0);
- assertEquals(metrics.totalRequests, 0);
+ expect(metrics.state).toBeDefined();
+ expect(metrics.failures).toBe(0);
+ expect(metrics.successes).toBe(0);
+ expect(metrics.totalRequests).toBe(0);
});
});
@@ -569,10 +569,10 @@ describe('ConflictResolver', () => {
it('should report resource conflict', async () => {
const conflict = await resolver.reportResourceConflict('resource-1', ['agent-1', 'agent-2']);
- assertExists(conflict.id);
- assertEquals(conflict.resourceId, 'resource-1');
- assertEquals(conflict.agents, ['agent-1', 'agent-2']);
- assertEquals(conflict.resolved, false);
+ expect(conflict.id).toBeDefined();
+ expect(conflict.resourceId).toBe('resource-1');
+ expect(conflict.agents).toBe(['agent-1', 'agent-2']);
+ expect(conflict.resolved).toBe(false);
});
it('should report task conflict', async () => {
@@ -582,10 +582,10 @@ describe('ConflictResolver', () => {
'assignment'
);
- assertExists(conflict.id);
- assertEquals(conflict.taskId, 'task-1');
- assertEquals(conflict.type, 'assignment');
- assertEquals(conflict.resolved, false);
+ expect(conflict.id).toBeDefined();
+ expect(conflict.taskId).toBe('task-1');
+ expect(conflict.type).toBe('assignment');
+ expect(conflict.resolved).toBe(false);
});
it('should resolve conflict using priority strategy', async () => {
@@ -600,9 +600,9 @@ describe('ConflictResolver', () => {
const resolution = await resolver.resolveConflict(conflict.id, 'priority', context);
- assertEquals(resolution.type, 'priority');
- assertEquals(resolution.winner, 'agent-2'); // Higher priority
- assertEquals(conflict.resolved, true);
+ expect(resolution.type).toBe('priority');
+ expect(resolution.winner).toBe('agent-2'); // Higher priority
+ expect(conflict.resolved).toBe(true);
});
it('should resolve conflict using timestamp strategy', async () => {
@@ -618,8 +618,8 @@ describe('ConflictResolver', () => {
const resolution = await resolver.resolveConflict(conflict.id, 'timestamp', context);
- assertEquals(resolution.type, 'timestamp');
- assertEquals(resolution.winner, 'agent-1'); // Earlier request
+ expect(resolution.type).toBe('timestamp');
+ expect(resolution.winner).toBe('agent-1'); // Earlier request
});
it('should auto-resolve conflicts', async () => {
@@ -627,8 +627,8 @@ describe('ConflictResolver', () => {
const resolution = await resolver.autoResolve(conflict.id, 'priority');
- assertEquals(resolution.type, 'priority');
- assertExists(resolution.winner);
+ expect(resolution.type).toBe('priority');
+ expect(resolution.winner).toBeDefined();
});
it('should track conflict statistics', async () => {
@@ -637,11 +637,11 @@ describe('ConflictResolver', () => {
const stats = resolver.getStats();
- assertEquals(stats.totalConflicts, 2);
- assertEquals(stats.activeConflicts, 2);
- assertEquals(stats.resolvedConflicts, 0);
- assertEquals(stats.conflictsByType.resource, 1);
- assertEquals(stats.conflictsByType.task, 1);
+ expect(stats.totalConflicts).toBe(2);
+ expect(stats.activeConflicts).toBe(2);
+ expect(stats.resolvedConflicts).toBe(0);
+ expect(stats.conflictsByType.resource).toBe(1);
+ expect(stats.conflictsByType.task).toBe(1);
});
it('should cleanup old conflicts', async () => {
@@ -653,6 +653,6 @@ describe('ConflictResolver', () => {
// Cleanup old conflicts (immediate cleanup for test)
const removed = resolver.cleanupOldConflicts(0);
- assertEquals(removed, 1);
+ expect(removed).toBe(1);
});
});
\ No newline at end of file
diff --git a/tests/unit/core/config.test.ts b/tests/unit/core/config.test.ts
index c3aff7d540..fff9cd65d2 100644
--- a/tests/unit/core/config.test.ts
+++ b/tests/unit/core/config.test.ts
@@ -62,7 +62,7 @@ describe('ConfigManager', () => {
it('should be a singleton', () => {
const instance1 = ConfigManager.getInstance();
const instance2 = ConfigManager.getInstance();
- assertEquals(instance1, instance2);
+ expect(instance1).toBe(instance2);
});
});
@@ -70,17 +70,17 @@ describe('ConfigManager', () => {
it('should load default configuration', async () => {
const config = await configManager.load();
- assertExists(config.orchestrator);
- assertExists(config.terminal);
- assertExists(config.memory);
- assertExists(config.coordination);
- assertExists(config.mcp);
- assertExists(config.logging);
+ expect(config.orchestrator).toBeDefined();
+ expect(config.terminal).toBeDefined();
+ expect(config.memory).toBeDefined();
+ expect(config.coordination).toBeDefined();
+ expect(config.mcp).toBeDefined();
+ expect(config.logging).toBeDefined();
// Check some defaults
- assertEquals(config.orchestrator.maxConcurrentAgents, 10);
- assertEquals(config.terminal.type, 'auto');
- assertEquals(config.memory.backend, 'hybrid');
+ expect(config.orchestrator.maxConcurrentAgents).toBe(10);
+ expect(config.terminal.type).toBe('auto');
+ expect(config.memory.backend).toBe('hybrid');
});
it('should load configuration from file', async () => {
@@ -96,17 +96,17 @@ describe('ConfigManager', () => {
const configFile = await createTestFile('config.json', JSON.stringify(configData));
const config = await configManager.load(configFile);
- assertEquals(config.orchestrator.maxConcurrentAgents, 20);
- assertEquals(config.logging.level, 'debug');
+ expect(config.orchestrator.maxConcurrentAgents).toBe(20);
+ expect(config.logging.level).toBe('debug');
// Other values should still be defaults
- assertEquals(config.terminal.type, 'auto');
+ expect(config.terminal.type).toBe('auto');
});
it('should handle non-existent config file gracefully', async () => {
const config = await configManager.load('/non/existent/file.json');
// Should use defaults
- assertEquals(config.orchestrator.maxConcurrentAgents, 10);
+ expect(config.orchestrator.maxConcurrentAgents).toBe(10);
});
it('should throw on invalid JSON in config file', async () => {
@@ -129,12 +129,12 @@ describe('ConfigManager', () => {
const config = await configManager.load();
- assertEquals(config.orchestrator.maxConcurrentAgents, 5);
- assertEquals(config.terminal.type, 'vscode');
- assertEquals(config.memory.backend, 'sqlite');
- assertEquals(config.mcp.transport, 'http');
- assertEquals(config.mcp.port, 9000);
- assertEquals(config.logging.level, 'debug');
+ expect(config.orchestrator.maxConcurrentAgents).toBe(5);
+ expect(config.terminal.type).toBe('vscode');
+ expect(config.memory.backend).toBe('sqlite');
+ expect(config.mcp.transport).toBe('http');
+ expect(config.mcp.port).toBe(9000);
+ expect(config.logging.level).toBe('debug');
});
it('should merge file and env configuration with env taking precedence', async () => {
@@ -152,8 +152,8 @@ describe('ConfigManager', () => {
const config = await configManager.load(configFile);
- assertEquals(config.orchestrator.maxConcurrentAgents, 15); // Env wins
- assertEquals(config.logging.level, 'info'); // From file
+ expect(config.orchestrator.maxConcurrentAgents).toBe(15); // Env wins
+ expect(config.logging.level).toBe('info'); // From file
});
it('should ignore invalid env values', async () => {
@@ -162,7 +162,7 @@ describe('ConfigManager', () => {
const config = await configManager.load();
// Should use default
- assertEquals(config.terminal.type, 'auto');
+ expect(config.terminal.type).toBe('auto');
});
});
@@ -258,11 +258,11 @@ describe('ConfigManager', () => {
it('should get current configuration', () => {
const config = configManager.get();
- assertExists(config.orchestrator);
- assertExists(config.terminal);
+ expect(config.orchestrator).toBeDefined();
+ expect(config.terminal).toBeDefined();
// Should be a copy, not the original
config.orchestrator.maxConcurrentAgents = 999;
- assertEquals(configManager.get().orchestrator.maxConcurrentAgents, 10);
+ expect(configManager.get().orchestrator.maxConcurrentAgents).toBe(10);
});
it('should update configuration', () => {
@@ -277,10 +277,10 @@ describe('ConfigManager', () => {
const updatedConfig = configManager.update(updates);
- assertEquals(updatedConfig.orchestrator.maxConcurrentAgents, 25);
- assertEquals(updatedConfig.orchestrator.taskQueueSize, 200);
+ expect(updatedConfig.orchestrator.maxConcurrentAgents).toBe(25);
+ expect(updatedConfig.orchestrator.taskQueueSize).toBe(200);
// Other orchestrator values should remain
- assertExists(updatedConfig.orchestrator.healthCheckInterval);
+ expect(updatedConfig.orchestrator.healthCheckInterval).toBeDefined();
});
it('should validate updates', () => {
@@ -324,7 +324,7 @@ describe('ConfigManager', () => {
const savedContent = await Deno.readTextFile(savePath);
const savedConfig = JSON.parse(savedContent);
- assertEquals(savedConfig.orchestrator.maxConcurrentAgents, 15);
+ expect(savedConfig.orchestrator.maxConcurrentAgents).toBe(15);
});
it('should save to original file if no path specified', async () => {
@@ -347,7 +347,7 @@ describe('ConfigManager', () => {
const savedContent = await Deno.readTextFile(configFile);
const savedConfig = JSON.parse(savedContent);
- assertEquals(savedConfig.orchestrator.maxConcurrentAgents, 30);
+ expect(savedConfig.orchestrator.maxConcurrentAgents).toBe(30);
});
it('should throw if no save path available', async () => {
@@ -366,8 +366,8 @@ describe('ConfigManager', () => {
it('should load config with helper function', async () => {
const config = await loadConfig();
- assertExists(config.orchestrator);
- assertEquals(config.orchestrator.maxConcurrentAgents, 10);
+ expect(config.orchestrator).toBeDefined();
+ expect(config.orchestrator.maxConcurrentAgents).toBe(10);
});
it('should load config from specified path', async () => {
@@ -380,7 +380,7 @@ describe('ConfigManager', () => {
const configFile = await createTestFile('helper.json', JSON.stringify(configData));
const config = await loadConfig(configFile);
- assertEquals(config.logging.level, 'error');
+ expect(config.logging.level).toBe('error');
});
});
@@ -404,12 +404,12 @@ describe('ConfigManager', () => {
const configFile = await createTestFile('nested.json', JSON.stringify(configData));
const config = await configManager.load(configFile);
- assertEquals(config.orchestrator.maxConcurrentAgents, 15);
- assertEquals(config.memory.backend, 'sqlite');
- assertEquals(config.memory.cacheSizeMB, 50);
- assertEquals(config.logging.level, 'warn');
- assertEquals(config.logging.format, 'json');
- assertEquals(config.logging.destination, 'both');
+ expect(config.orchestrator.maxConcurrentAgents).toBe(15);
+ expect(config.memory.backend).toBe('sqlite');
+ expect(config.memory.cacheSizeMB).toBe(50);
+ expect(config.logging.level).toBe('warn');
+ expect(config.logging.format).toBe('json');
+ expect(config.logging.destination).toBe('both');
});
it('should handle partial configuration files', async () => {
@@ -424,14 +424,14 @@ describe('ConfigManager', () => {
const config = await configManager.load(configFile);
// Should have updated orchestrator
- assertEquals(config.orchestrator.maxConcurrentAgents, 20);
+ expect(config.orchestrator.maxConcurrentAgents).toBe(20);
// Should have defaults for other sections
- assertExists(config.terminal);
- assertExists(config.memory);
- assertExists(config.coordination);
- assertExists(config.mcp);
- assertExists(config.logging);
+ expect(config.terminal).toBeDefined();
+ expect(config.memory).toBeDefined();
+ expect(config.coordination).toBeDefined();
+ expect(config.mcp).toBeDefined();
+ expect(config.logging).toBeDefined();
});
it('should handle empty configuration file', async () => {
@@ -439,8 +439,8 @@ describe('ConfigManager', () => {
const config = await configManager.load(configFile);
// Should use all defaults
- assertEquals(config.orchestrator.maxConcurrentAgents, 10);
- assertEquals(config.terminal.type, 'auto');
+ expect(config.orchestrator.maxConcurrentAgents).toBe(10);
+ expect(config.terminal.type).toBe('auto');
});
});
});
\ No newline at end of file
diff --git a/tests/unit/core/enhanced-event-bus.test.ts b/tests/unit/core/enhanced-event-bus.test.ts
index 40bd06fa2b..c7436cae58 100644
--- a/tests/unit/core/enhanced-event-bus.test.ts
+++ b/tests/unit/core/enhanced-event-bus.test.ts
@@ -2,10 +2,10 @@
* Enhanced comprehensive unit tests for EventBus
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertThrows } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
-import { spy } from "https://deno.land/[email protected]/testing/mock.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { assertEquals, assertExists, assertThrows } from "../test.utils.ts";
+// FakeTime equivalent available in test.utils.ts
+import { spy } from "../test.utils.ts";
import { EventBus } from '../../../src/core/event-bus.ts';
import {
@@ -40,8 +40,8 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.on('test.event', handler);
eventBus.emit('test.event', { message: 'test data' });
- assertEquals(handler.calls.length, 1);
- assertEquals(handler.calls[0].args[0], { message: 'test data' });
+ expect(handler.calls.length).toBe(1);
+ expect(handler.calls[0].args[0]).toBe({ message: 'test data' });
});
it('should handle multiple handlers for same event', () => {
@@ -55,12 +55,12 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('multi.event', { data: 'multi' });
- assertEquals(handler1.calls.length, 1);
- assertEquals(handler2.calls.length, 1);
- assertEquals(handler3.calls.length, 1);
+ expect(handler1.calls.length).toBe(1);
+ expect(handler2.calls.length).toBe(1);
+ expect(handler3.calls.length).toBe(1);
[handler1, handler2, handler3].forEach(handler => {
- assertEquals(handler.calls[0].args[0], { data: 'multi' });
+ expect(handler.calls[0].args[0]).toBe({ data: 'multi' });
});
});
@@ -74,8 +74,8 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('task.completed', { taskId: '123' });
eventBus.emit('task.started', { taskId: '456' });
- assertEquals(wildHandler.calls.length, 2);
- assertEquals(specificHandler.calls.length, 1);
+ expect(wildHandler.calls.length).toBe(2);
+ expect(specificHandler.calls.length).toBe(1);
});
it('should handle once listeners correctly', () => {
@@ -86,8 +86,8 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('once.event', { first: true });
eventBus.emit('once.event', { second: true });
- assertEquals(handler.calls.length, 1);
- assertEquals(handler.calls[0].args[0], { first: true });
+ expect(handler.calls.length).toBe(1);
+ expect(handler.calls[0].args[0]).toBe({ first: true });
});
it('should remove event handlers correctly', () => {
@@ -99,8 +99,8 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.off('remove.event', handler);
eventBus.emit('remove.event', { after: true });
- assertEquals(handler.calls.length, 1);
- assertEquals(handler.calls[0].args[0], { before: true });
+ expect(handler.calls.length).toBe(1);
+ expect(handler.calls[0].args[0]).toBe({ before: true });
});
it('should handle removing non-existent handlers gracefully', () => {
@@ -114,7 +114,7 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.on('test.event', handler);
eventBus.emit('test.event', { data: 'test' });
- assertEquals(handler.calls.length, 1);
+ expect(handler.calls.length).toBe(1);
});
});
@@ -132,9 +132,9 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('app.module.other', { data: 'branch' });
eventBus.emit('app.other', { data: 'root' });
- assertEquals(rootHandler.calls.length, 3);
- assertEquals(branchHandler.calls.length, 2);
- assertEquals(leafHandler.calls.length, 1);
+ expect(rootHandler.calls.length).toBe(3);
+ expect(branchHandler.calls.length).toBe(2);
+ expect(leafHandler.calls.length).toBe(1);
});
it('should handle complex pattern matching', () => {
@@ -166,11 +166,11 @@ describe('EventBus - Enhanced Tests', () => {
});
// Verify pattern matches
- assertEquals(handlers[0].calls.length, 1); // user.*.created
- assertEquals(handlers[1].calls.length, 1); // user.*.updated
- assertEquals(handlers[2].calls.length, 2); // user.admin.*
- assertEquals(handlers[3].calls.length, 1); // system.*.error
- assertEquals(handlers[4].calls.length, 1); // system.*.warning
+ expect(handlers[0].calls.length).toBe(1); // user.*.created
+ expect(handlers[1].calls.length).toBe(1); // user.*.updated
+ expect(handlers[2].calls.length).toBe(2); // user.admin.*
+ expect(handlers[3].calls.length).toBe(1); // system.*.error
+ expect(handlers[4].calls.length).toBe(1); // system.*.warning
});
it('should handle event namespaces correctly', () => {
@@ -183,7 +183,7 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('namespace:other.event', { data: 3 });
eventBus.emit('test.event', { data: 4 });
- assertEquals(namespaceHandler.calls.length, 2);
+ expect(namespaceHandler.calls.length).toBe(2);
});
});
@@ -202,7 +202,7 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('priority.event', {});
// Should be called in priority order: high (10), normal (5), low (1)
- assertEquals(callOrder, [2, 3, 1]);
+ expect(callOrder).toBe([2, 3, 1]);
});
it('should handle async handlers in order', async () => {
@@ -229,10 +229,10 @@ describe('EventBus - Enhanced Tests', () => {
await eventBus.emitAsync('async.event', {});
// All handlers should complete, order depends on implementation
- assertEquals(handler1.calls.length, 1);
- assertEquals(handler2.calls.length, 1);
- assertEquals(handler3.calls.length, 1);
- assertEquals(callOrder.length, 3);
+ expect(handler1.calls.length).toBe(1);
+ expect(handler2.calls.length).toBe(1);
+ expect(handler3.calls.length).toBe(1);
+ expect(callOrder.length).toBe(3);
});
it('should handle handler errors gracefully', () => {
@@ -248,8 +248,8 @@ describe('EventBus - Enhanced Tests', () => {
// Should not throw, but continue with other handlers
eventBus.emit('error.event', {});
- assertEquals(errorHandler.calls.length, 1);
- assertEquals(successHandler.calls.length, 1);
+ expect(errorHandler.calls.length).toBe(1);
+ expect(successHandler.calls.length).toBe(1);
});
});
@@ -265,7 +265,7 @@ describe('EventBus - Enhanced Tests', () => {
{ iterations: 10000, concurrency: 1 }
);
- assertEquals(handler.calls.length, 10000);
+ expect(handler.calls.length).toBe(10000);
TestAssertions.assertInRange(stats.mean, 0, 1); // Should be very fast
console.log(`High-frequency event performance: ${stats.mean.toFixed(4)}ms per event`);
@@ -288,7 +288,7 @@ describe('EventBus - Enhanced Tests', () => {
// Verify all handlers were called
handlers.forEach(handler => {
- assertEquals(handler.calls.length, 100);
+ expect(handler.calls.length).toBe(100);
});
TestAssertions.assertInRange(stats.mean, 0, 50); // Should complete within 50ms
@@ -312,8 +312,8 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.removeAllListeners();
});
- assertEquals(leaked, false);
- assertEquals(handler.calls.length, 10000);
+ expect(leaked).toBe(false);
+ expect(handler.calls.length).toBe(10000);
});
it('should handle load testing scenario', async () => {
@@ -334,7 +334,7 @@ describe('EventBus - Enhanced Tests', () => {
}
);
- assertEquals(results.failedRequests, 0);
+ expect(results.failedRequests).toBe(0);
TestAssertions.assertInRange(results.successfulRequests, 4000, 6000); // ~5000 requests
TestAssertions.assertInRange(results.averageResponseTime, 0, 5);
@@ -360,11 +360,11 @@ describe('EventBus - Enhanced Tests', () => {
// Only remaining handlers should be called
handlers.slice(0, 50).forEach(handler => {
- assertEquals(handler.calls.length, 0);
+ expect(handler.calls.length).toBe(0);
});
handlers.slice(50).forEach(handler => {
- assertEquals(handler.calls.length, 1);
+ expect(handler.calls.length).toBe(1);
});
});
@@ -383,7 +383,7 @@ describe('EventBus - Enhanced Tests', () => {
}
handlers.forEach(handler => {
- assertEquals(handler.calls.length, 0);
+ expect(handler.calls.length).toBe(0);
});
});
@@ -405,11 +405,11 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('other.event', {});
specificHandlers.forEach(handler => {
- assertEquals(handler.calls.length, 0);
+ expect(handler.calls.length).toBe(0);
});
otherHandlers.forEach(handler => {
- assertEquals(handler.calls.length, 1);
+ expect(handler.calls.length).toBe(1);
});
});
});
@@ -441,7 +441,7 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.on('valid.event', handler);
eventBus.emit('valid.event', {});
- assertEquals(handler.calls.length >= 1, true);
+ expect(handler.calls.length >= 1).toBe(true);
});
it('should handle edge case data types', () => {
@@ -475,8 +475,8 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.on('recursive.event', recursiveHandler);
eventBus.emit('recursive.event', { count: 0 });
- assertEquals(recursiveHandler.calls.length, maxEmissions);
- assertEquals(emissionCount, maxEmissions);
+ expect(recursiveHandler.calls.length).toBe(maxEmissions);
+ expect(emissionCount).toBe(maxEmissions);
});
it('should handle handler that modifies handler list', () => {
@@ -497,7 +497,7 @@ describe('EventBus - Enhanced Tests', () => {
eventBus.emit('disruptive.event', {});
// Disruptive handler should have been called
- assertEquals(disruptiveHandler.calls.length, 1);
+ expect(disruptiveHandler.calls.length).toBe(1);
// Some or all of the other handlers may have been called
// depending on implementation details
@@ -522,8 +522,8 @@ describe('EventBus - Enhanced Tests', () => {
// Should not throw, even with async errors
await eventBus.emitAsync('async.error', {});
- assertEquals(errorHandler.calls.length, 1);
- assertEquals(successHandler.calls.length, 1);
+ expect(errorHandler.calls.length).toBe(1);
+ expect(successHandler.calls.length).toBe(1);
});
it('should handle timeout for slow async handlers', async () => {
@@ -546,8 +546,8 @@ describe('EventBus - Enhanced Tests', () => {
2000
);
- assertEquals(slowHandler.calls.length, 1);
- assertEquals(fastHandler.calls.length, 1);
+ expect(slowHandler.calls.length).toBe(1);
+ expect(fastHandler.calls.length).toBe(1);
});
});
@@ -565,11 +565,11 @@ describe('EventBus - Enhanced Tests', () => {
});
const history = eventBus.getEventHistory();
- assertEquals(history.length, 50);
+ expect(history.length).toBe(50);
// Most recent event should be last
- assertEquals(history[49].event, 'history.event.49');
- assertEquals(history[49].data, { index: 49 });
+ expect(history[49].event).toBe('history.event.49');
+ expect(history[49].data).toBe({ index: 49 });
});
it('should limit event history size', () => {
@@ -581,11 +581,11 @@ describe('EventBus - Enhanced Tests', () => {
}
const history = eventBus.getEventHistory();
- assertEquals(history.length, 10);
+ expect(history.length).toBe(10);
// Should contain only the last 10 events
- assertEquals(history[0].event, 'limited.history.10');
- assertEquals(history[9].event, 'limited.history.19');
+ expect(history[0].event).toBe('limited.history.10');
+ expect(history[9].event).toBe('limited.history.19');
});
it('should provide event statistics', () => {
@@ -600,12 +600,12 @@ describe('EventBus - Enhanced Tests', () => {
const stats = eventBus.getEventStats();
- assertEquals(typeof stats.totalEvents, 'number');
- assertEquals(typeof stats.uniqueEventTypes, 'number');
- assertEquals(typeof stats.totalHandlers, 'number');
+ expect(typeof stats.totalEvents).toBe('number');
+ expect(typeof stats.uniqueEventTypes).toBe('number');
+ expect(typeof stats.totalHandlers).toBe('number');
- assertEquals(stats.totalEvents >= 4, true);
- assertEquals(stats.uniqueEventTypes >= 3, true);
+ expect(stats.totalEvents >= 4).toBe(true);
+ expect(stats.uniqueEventTypes >= 3).toBe(true);
});
});
});
\ No newline at end of file
diff --git a/tests/unit/core/enhanced-orchestrator.test.ts b/tests/unit/core/enhanced-orchestrator.test.ts
index e360a49709..29aa8ba393 100644
--- a/tests/unit/core/enhanced-orchestrator.test.ts
+++ b/tests/unit/core/enhanced-orchestrator.test.ts
@@ -2,10 +2,10 @@
* Enhanced comprehensive unit tests for Orchestrator
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertRejects, assertThrows } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
-import { stub, spy } from "https://deno.land/[email protected]/testing/mock.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { expect } from "@jest/globals";
+// FakeTime equivalent available in test.utils.ts
+import { stub, spy } from "../test.utils.ts";
import { Orchestrator } from '../../../src/core/orchestrator.ts';
import {
@@ -68,16 +68,16 @@ describe('Orchestrator - Enhanced Tests', () => {
await orchestrator.initialize();
// Verify initialization order and calls
- assertEquals(mocks.eventBus.clearEvents().length, 0);
- assertEquals(mocks.terminalManager.initialize.calls.length, 1);
- assertEquals(mocks.memoryManager.initialize.calls.length, 1);
- assertEquals(mocks.coordinationManager.initialize.calls.length, 1);
- assertEquals(mocks.mcpServer.start.calls.length, 1);
+ expect(mocks.eventBus.clearEvents().length).toBe(0);
+ expect(mocks.terminalManager.initialize.calls.length).toBe(1);
+ expect(mocks.memoryManager.initialize.calls.length).toBe(1);
+ expect(mocks.coordinationManager.initialize.calls.length).toBe(1);
+ expect(mocks.mcpServer.start.calls.length).toBe(1);
// Check that events were emitted
const events = mocks.eventBus.getEvents();
const initEvent = events.find(e => e.event === 'orchestrator.initialized');
- assertExists(initEvent);
+ expect(initEvent).toBeDefined();
});
it('should handle partial initialization failure gracefully', async () => {
@@ -93,7 +93,7 @@ describe('Orchestrator - Enhanced Tests', () => {
);
// Verify cleanup was attempted
- assertEquals(mocks.terminalManager.shutdown.calls.length, 1);
+ expect(mocks.terminalManager.shutdown.calls.length).toBe(1);
});
it('should timeout initialization after configured time', async () => {
@@ -118,8 +118,8 @@ describe('Orchestrator - Enhanced Tests', () => {
const successful = results.filter(r => r.status === 'fulfilled');
const failed = results.filter(r => r.status === 'rejected');
- assertEquals(successful.length, 1);
- assertEquals(failed.length, 4);
+ expect(successful.length).toBe(1);
+ expect(failed.length).toBe(4);
});
});
@@ -139,10 +139,10 @@ describe('Orchestrator - Enhanced Tests', () => {
const result = await orchestrator.createAndExecuteTask(agentProfile, task);
- assertEquals(mocks.terminalManager.spawnTerminal.calls.length, 1);
- assertEquals(mocks.terminalManager.sendCommand.calls.length, 1);
- assertEquals(mocks.coordinationManager.assignTask.calls.length, 1);
- assertExists(result);
+ expect(mocks.terminalManager.spawnTerminal.calls.length).toBe(1);
+ expect(mocks.terminalManager.sendCommand.calls.length).toBe(1);
+ expect(mocks.coordinationManager.assignTask.calls.length).toBe(1);
+ expect(result).toBeDefined();
});
it('should handle task dependencies correctly', async () => {
@@ -155,7 +155,7 @@ describe('Orchestrator - Enhanced Tests', () => {
}
// Verify task scheduling respected dependencies
- assertEquals(mocks.coordinationManager.assignTask.calls.length, 5);
+ expect(mocks.coordinationManager.assignTask.calls.length).toBe(5);
});
it('should handle concurrent task execution', async () => {
@@ -172,10 +172,10 @@ describe('Orchestrator - Enhanced Tests', () => {
);
const results = await Promise.all(promises);
- assertEquals(results.length, 10);
+ expect(results.length).toBe(10);
// Verify all tasks were processed
- assertEquals(mocks.coordinationManager.assignTask.calls.length, 10);
+ expect(mocks.coordinationManager.assignTask.calls.length).toBe(10);
});
it('should handle task timeouts properly', async () => {
@@ -221,8 +221,8 @@ describe('Orchestrator - Enhanced Tests', () => {
};
const result = await orchestrator.createAndExecuteTask(agentProfile, task);
- assertEquals(result, 'Success on third attempt');
- assertEquals(mocks.terminalManager.sendCommand.calls.length, 3);
+ expect(result).toBe('Success on third attempt');
+ expect(mocks.terminalManager.sendCommand.calls.length).toBe(3);
});
});
@@ -234,13 +234,13 @@ describe('Orchestrator - Enhanced Tests', () => {
it('should report overall health status correctly', async () => {
const health = await orchestrator.getHealthStatus();
- assertEquals(health.healthy, true);
- assertExists(health.components);
- assertEquals(Object.keys(health.components).length, 5); // 5 components
+ expect(health.healthy).toBe(true);
+ expect(health.components).toBeDefined();
+ expect(Object.keys(health.components).length).toBe(5); // 5 components
// All components should be healthy in this test
Object.values(health.components).forEach(componentHealth => {
- assertEquals(componentHealth.healthy, true);
+ expect(componentHealth.healthy).toBe(true);
});
});
@@ -254,9 +254,9 @@ describe('Orchestrator - Enhanced Tests', () => {
const health = await orchestrator.getHealthStatus();
- assertEquals(health.healthy, false);
- assertEquals(health.components.terminal.healthy, false);
- assertEquals(health.components.terminal.error, 'Terminal manager is down');
+ expect(health.healthy).toBe(false);
+ expect(health.components.terminal.healthy).toBe(false);
+ expect(health.components.terminal.error).toBe('Terminal manager is down');
});
it('should track performance metrics', async () => {
@@ -274,11 +274,11 @@ describe('Orchestrator - Enhanced Tests', () => {
}
const health = await orchestrator.getHealthStatus();
- assertExists(health.metrics);
+ expect(health.metrics).toBeDefined();
if (health.metrics) {
- assertEquals(typeof health.metrics.tasksExecuted, 'number');
- assertEquals(typeof health.metrics.averageExecutionTime, 'number');
+ expect(typeof health.metrics.tasksExecuted).toBe('number');
+ expect(typeof health.metrics.averageExecutionTime).toBe('number');
}
});
});
@@ -292,15 +292,15 @@ describe('Orchestrator - Enhanced Tests', () => {
const agentId = 'test-agent';
const bankId = await orchestrator.createMemoryBank(agentId);
- assertExists(bankId);
- assertEquals(mocks.memoryManager.createBank.calls.length, 1);
- assertEquals(mocks.memoryManager.createBank.calls[0].args[0], agentId);
+ expect(bankId).toBeDefined();
+ expect(mocks.memoryManager.createBank.calls.length).toBe(1);
+ expect(mocks.memoryManager.createBank.calls[0].args[0]).toBe(agentId);
await orchestrator.storeMemory(bankId, 'test-key', { data: 'test-value' });
- assertEquals(mocks.memoryManager.store.calls.length, 1);
+ expect(mocks.memoryManager.store.calls.length).toBe(1);
const retrieved = await orchestrator.retrieveMemory(bankId, 'test-key');
- assertEquals(retrieved, { data: 'test-value' });
+ expect(retrieved).toBe({ data: 'test-value' });
});
it('should handle memory operations under load', async () => {
@@ -314,11 +314,11 @@ describe('Orchestrator - Enhanced Tests', () => {
});
const results = await Promise.all(operations);
- assertEquals(results.length, 100);
+ expect(results.length).toBe(100);
// Verify all values were stored and retrieved correctly
results.forEach((result, i) => {
- assertEquals(result, { value: i });
+ expect(result).toBe({ value: i });
});
});
@@ -342,7 +342,7 @@ describe('Orchestrator - Enhanced Tests', () => {
});
// Should not leak significant memory
- assertEquals(leaked, false);
+ expect(leaked).toBe(false);
});
});
@@ -419,7 +419,7 @@ describe('Orchestrator - Enhanced Tests', () => {
// Load test assertions
TestAssertions.assertInRange(results.successfulRequests / results.totalRequests, 0.95, 1.0);
- assertEquals(results.failedRequests, 0);
+ expect(results.failedRequests).toBe(0);
TestAssertions.assertInRange(results.averageResponseTime, 0, 1000);
console.log(`Load test results: ${results.successfulRequests}/${results.totalRequests} successful, avg=${results.averageResponseTime.toFixed(2)}ms`);
@@ -509,7 +509,7 @@ describe('Orchestrator - Enhanced Tests', () => {
// System should still be healthy
const health = await orchestrator.getHealthStatus();
- assertEquals(health.healthy, true);
+ expect(health.healthy).toBe(true);
});
it('should recover from temporary component failures', async () => {
@@ -534,8 +534,8 @@ describe('Orchestrator - Enhanced Tests', () => {
};
const result = await orchestrator.createAndExecuteTask(agentProfile, task);
- assertEquals(result, 'Success after 4 attempts');
- assertEquals(failureCount, 4);
+ expect(result).toBe('Success after 4 attempts');
+ expect(failureCount).toBe(4);
});
});
@@ -550,15 +550,15 @@ describe('Orchestrator - Enhanced Tests', () => {
await orchestrator.shutdown();
// Verify all components were shut down
- assertEquals(mocks.terminalManager.shutdown.calls.length, 1);
- assertEquals(mocks.memoryManager.shutdown.calls.length, 1);
- assertEquals(mocks.coordinationManager.shutdown.calls.length, 1);
- assertEquals(mocks.mcpServer.stop.calls.length, 1);
+ expect(mocks.terminalManager.shutdown.calls.length).toBe(1);
+ expect(mocks.memoryManager.shutdown.calls.length).toBe(1);
+ expect(mocks.coordinationManager.shutdown.calls.length).toBe(1);
+ expect(mocks.mcpServer.stop.calls.length).toBe(1);
// Check shutdown event was emitted
const events = mocks.eventBus.getEvents();
const shutdownEvent = events.find(e => e.event === 'orchestrator.shutdown');
- assertExists(shutdownEvent);
+ expect(shutdownEvent).toBeDefined();
});
it('should handle shutdown with active tasks', async () => {
@@ -581,7 +581,7 @@ describe('Orchestrator - Enhanced Tests', () => {
await Promise.allSettled([taskPromise, shutdownPromise]);
// Verify shutdown completed
- assertEquals(mocks.terminalManager.shutdown.calls.length, 1);
+ expect(mocks.terminalManager.shutdown.calls.length).toBe(1);
});
it('should timeout shutdown if components hang', async () => {
diff --git a/tests/unit/core/event-bus.test.ts b/tests/unit/core/event-bus.test.ts
index 3599dec314..f8b2594a0f 100644
--- a/tests/unit/core/event-bus.test.ts
+++ b/tests/unit/core/event-bus.test.ts
@@ -34,7 +34,7 @@ describe('EventBus', () => {
it('should be a singleton', () => {
const instance1 = EventBus.getInstance();
const instance2 = EventBus.getInstance();
- assertEquals(instance1, instance2);
+ expect(instance1).toBe(instance2);
});
it('should emit and receive events', () => {
@@ -59,7 +59,7 @@ describe('EventBus', () => {
eventBus.emit(SystemEvents.AGENT_SPAWNED as any, eventData);
assertSpyCalls(handler, 1);
- assertEquals(handler.calls[0].args[0], eventData);
+ expect(handler).toHaveBeenCalledWith(eventData);
});
it('should handle multiple listeners', () => {
@@ -105,7 +105,7 @@ describe('EventBus', () => {
}, 100);
const result = await promise as any;
- assertEquals(result.timestamp instanceof Date, true);
+ expect(result.timestamp instanceof Date).toBe(true);
});
it('should timeout when waiting for event', async () => {
@@ -129,7 +129,7 @@ describe('EventBus', () => {
eventBus.emit(SystemEvents.TASK_COMPLETED as any, { taskId: 'task-2', result: 'success' });
assertSpyCalls(handler, 1);
- assertEquals(handler.calls[0].args[0].taskId, 'task-1');
+ expect(handler).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'task-1' }));
});
it('should remove event listeners', () => {
@@ -171,10 +171,10 @@ describe('EventBus', () => {
const taskCreatedStat = stats.find(s => s.event === SystemEvents.TASK_CREATED);
const taskCompletedStat = stats.find(s => s.event === SystemEvents.TASK_COMPLETED);
- assertExists(taskCreatedStat);
- assertExists(taskCompletedStat);
- assertEquals(taskCreatedStat!.count, 2);
- assertEquals(taskCompletedStat!.count, 1);
+ expect(taskCreatedStat).toBeDefined();
+ expect(taskCompletedStat).toBeDefined();
+ expect(taskCreatedStat!.count).toBe(2);
+ expect(taskCompletedStat!.count).toBe(1);
});
it('should reset event statistics', () => {
@@ -182,10 +182,10 @@ describe('EventBus', () => {
debugBus.emit(SystemEvents.SYSTEM_ERROR as any, { error: new Error('test'), component: 'test' });
let stats = debugBus.getEventStats();
- assertEquals(stats.length > 0, true);
+ expect(stats.length > 0).toBe(true);
debugBus.resetStats();
stats = debugBus.getEventStats();
- assertEquals(stats.length, 0);
+ expect(stats.length).toBe(0);
});
});
\ No newline at end of file
diff --git a/tests/unit/core/logger.test.ts b/tests/unit/core/logger.test.ts
index 3e49549fba..9fa299a48c 100644
--- a/tests/unit/core/logger.test.ts
+++ b/tests/unit/core/logger.test.ts
@@ -55,7 +55,7 @@ describe('Logger', () => {
const logger1 = Logger.getInstance(config);
const logger2 = Logger.getInstance();
- assertEquals(logger1, logger2);
+ expect(logger1).toBe(logger2);
});
it('should throw if no config provided on first getInstance', () => {
@@ -68,8 +68,8 @@ describe('Logger', () => {
error = e as Error;
}
- assertExists(error);
- assertEquals(error!.message, 'Logger configuration required for initialization');
+ expect(error).toBeDefined();
+ expect(error!.message).toBe('Logger configuration required for initialization');
});
it('should configure logging level', () => {
@@ -91,8 +91,8 @@ describe('Logger', () => {
const output = consoleCapture.getOutput();
const errors = consoleCapture.getErrors();
- assertEquals(output.length, 0);
- assertEquals(errors.length, 1);
+ expect(output.length).toBe(0);
+ expect(errors.length).toBe(1);
});
});
@@ -110,21 +110,21 @@ describe('Logger', () => {
logger.debug('debug message', { data: 'test' });
const output = consoleCapture.getOutput();
- assertExists(output.find(o => o.includes('DEBUG') && o.includes('debug message')));
+ expect(output.find(o => o.includes('DEBUG').toBeDefined() && o.includes('debug message')));
});
it('should log info messages', () => {
logger.info('info message', { data: 'test' });
const output = consoleCapture.getOutput();
- assertExists(output.find(o => o.includes('INFO') && o.includes('info message')));
+ expect(output.find(o => o.includes('INFO').toBeDefined() && o.includes('info message')));
});
it('should log warn messages', () => {
logger.warn('warn message', { data: 'test' });
const output = consoleCapture.getOutput();
- assertExists(output.find(o => o.includes('WARN') && o.includes('warn message')));
+ expect(output.find(o => o.includes('WARN').toBeDefined() && o.includes('warn message')));
});
it('should log error messages', () => {
@@ -132,7 +132,7 @@ describe('Logger', () => {
logger.error('error message', error);
const errors = consoleCapture.getErrors();
- assertExists(errors.find(e => e.includes('ERROR') && e.includes('error message')));
+ expect(errors.find(e => e.includes('ERROR').toBeDefined() && e.includes('error message')));
});
it('should respect log level hierarchy', () => {
@@ -160,10 +160,10 @@ describe('Logger', () => {
const errors = consoleCapture.getErrors();
const allLogs = [...output, ...errors];
- assertEquals(allLogs.filter(l => l.includes('debug')).length, 0);
- assertEquals(allLogs.filter(l => l.includes('info')).length, 0);
- assertEquals(allLogs.filter(l => l.includes('warn')).length, 1);
- assertEquals(allLogs.filter(l => l.includes('error')).length, 1);
+ expect(allLogs.filter(l => l.includes('debug')).length).toBe(0);
+ expect(allLogs.filter(l => l.includes('info')).length).toBe(0);
+ expect(allLogs.filter(l => l.includes('warn')).length).toBe(1);
+ expect(allLogs.filter(l => l.includes('error')).length).toBe(1);
});
});
@@ -181,10 +181,10 @@ describe('Logger', () => {
const output = consoleCapture.getOutput();
const log = JSON.parse(output[0]);
- assertEquals(log.level, 'INFO');
- assertEquals(log.message, 'test message');
- assertEquals(log.data, { key: 'value' });
- assertExists(log.timestamp);
+ expect(log.level).toBe('INFO');
+ expect(log.message).toBe('test message');
+ expect(log.data).toBe({ key: 'value' });
+ expect(log.timestamp).toBeDefined();
});
it('should format logs as text', () => {
@@ -198,10 +198,10 @@ describe('Logger', () => {
logger.info('test message', { key: 'value' });
const output = consoleCapture.getOutput();
- assertExists(output[0].match(/\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\]/));
- assertExists(output[0].includes('INFO'));
- assertExists(output[0].includes('test message'));
- assertExists(output[0].includes('{"key":"value"}'));
+ expect(output[0].match(/\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\]/).toBeDefined());
+ expect(output[0].includes('INFO').toBeDefined());
+ expect(output[0].includes('test message').toBeDefined());
+ expect(output[0].includes('{"key":"value"}').toBeDefined());
});
it('should format errors properly in text mode', () => {
@@ -218,8 +218,8 @@ describe('Logger', () => {
logger.error('error occurred', error);
const errors = consoleCapture.getErrors();
- assertExists(errors[0].includes('Error: test error'));
- assertExists(errors[0].includes('Stack:'));
+ expect(errors[0].includes('Error: test error').toBeDefined());
+ expect(errors[0].includes('Stack:').toBeDefined());
});
it('should format errors properly in JSON mode', () => {
@@ -237,10 +237,10 @@ describe('Logger', () => {
const errors = consoleCapture.getErrors();
const log = JSON.parse(errors[0]);
- assertExists(log.error);
- assertEquals(log.error.name, 'Error');
- assertEquals(log.error.message, 'test error');
- assertExists(log.error.stack);
+ expect(log.error).toBeDefined();
+ expect(log.error.name).toBe('Error');
+ expect(log.error.message).toBe('test error');
+ expect(log.error.stack).toBeDefined();
});
});
@@ -256,7 +256,7 @@ describe('Logger', () => {
logger.info('console log');
const output = consoleCapture.getOutput();
- assertEquals(output.length, 1);
+ expect(output.length).toBe(1);
});
it('should log to file only', async () => {
@@ -274,11 +274,11 @@ describe('Logger', () => {
await new Promise(resolve => setTimeout(resolve, 100));
const content = await Deno.readTextFile(tempLogFile);
- assertExists(content.includes('file log'));
+ expect(content.includes('file log').toBeDefined());
// Should not log to console
const output = consoleCapture.getOutput();
- assertEquals(output.length, 0);
+ expect(output.length).toBe(0);
});
it('should log to both console and file', async () => {
@@ -297,12 +297,12 @@ describe('Logger', () => {
// Check console
const output = consoleCapture.getOutput();
- assertEquals(output.length, 1);
- assertExists(output[0].includes('both log'));
+ expect(output.length).toBe(1);
+ expect(output[0].includes('both log').toBeDefined());
// Check file
const content = await Deno.readTextFile(tempLogFile);
- assertExists(content.includes('both log'));
+ expect(content.includes('both log').toBeDefined());
});
it('should throw if file destination without filePath', () => {
@@ -319,8 +319,8 @@ describe('Logger', () => {
error = e as Error;
}
- assertExists(error);
- assertEquals(error!.message, 'File path required for file logging');
+ expect(error).toBeDefined();
+ expect(error!.message).toBe('File path required for file logging');
});
});
@@ -356,7 +356,7 @@ describe('Logger', () => {
}
// Should have rotated file
- assertEquals(files.length > 1, true);
+ expect(files.length > 1).toBe(true);
});
});
@@ -382,9 +382,9 @@ describe('Logger', () => {
logger.debug('should now appear');
const output = consoleCapture.getOutput();
- assertEquals(output.filter(o => o.includes('should appear')).length, 1);
- assertEquals(output.filter(o => o.includes('should not appear')).length, 0);
- assertEquals(output.filter(o => o.includes('should now appear')).length, 1);
+ expect(output.filter(o => o.includes('should appear')).length).toBe(1);
+ expect(output.filter(o => o.includes('should not appear')).length).toBe(0);
+ expect(output.filter(o => o.includes('should now appear')).length).toBe(1);
});
it('should close file handle when changing destination', async () => {
@@ -403,7 +403,7 @@ describe('Logger', () => {
// Now spy on the file handle
const fileHandle = logger['fileHandle'];
- assertExists(fileHandle);
+ expect(fileHandle).toBeDefined();
const fileHandleSpy = spy(fileHandle, 'close');
await logger.configure({
@@ -432,7 +432,7 @@ describe('Logger', () => {
const output = consoleCapture.getOutput();
const log = JSON.parse(output[0]);
- assertEquals(log.context.component, 'test-component');
+ expect(log.context.component).toBe('test-component');
});
it('should merge child context with parent context', () => {
@@ -451,8 +451,8 @@ describe('Logger', () => {
const output = consoleCapture.getOutput();
const log = JSON.parse(output[0]);
- assertEquals(log.context.service, 'api');
- assertEquals(log.context.component, 'auth');
+ expect(log.context.service).toBe('api');
+ expect(log.context.component).toBe('auth');
});
});
@@ -479,7 +479,7 @@ describe('Logger', () => {
// Should log error to console
assertSpyCalls(errorSpy, 1);
- assertEquals(errorSpy.calls[0].args[0], 'Failed to write to log file:');
+ expect(errorSpy.calls[0].args[0]).toBe('Failed to write to log file:');
} finally {
console.error = originalError;
}
@@ -498,7 +498,7 @@ describe('Logger', () => {
const errors = consoleCapture.getErrors();
const log = JSON.parse(errors[0]);
- assertEquals(log.error, { custom: 'error object' });
+ expect(log.error).toBe({ custom: 'error object' });
});
});
@@ -522,10 +522,10 @@ describe('Logger', () => {
const duration = Date.now() - start;
// Should complete quickly (< 1 second for 1000 logs)
- assertEquals(duration < 1000, true);
+ expect(duration < 1000).toBe(true);
const output = consoleCapture.getOutput();
- assertEquals(output.length, count);
+ expect(output.length).toBe(count);
});
});
});
\ No newline at end of file
diff --git a/tests/unit/core/orchestrator.test.ts b/tests/unit/core/orchestrator.test.ts
index 7cdda4c278..262129bfb9 100644
--- a/tests/unit/core/orchestrator.test.ts
+++ b/tests/unit/core/orchestrator.test.ts
@@ -65,7 +65,7 @@ describe('Orchestrator', () => {
assertSpyCalls(mocks.coordinationManager.initialize, 1);
assertSpyCalls(mocks.mcpServer.start, 1);
- assertEquals(mocks.logger.hasLog('info', 'Orchestrator initialized successfully'), true);
+ expect(mocks.logger.hasLog('info').toBe('Orchestrator initialized successfully'), true);
});
it('should throw if already initialized', async () => {
@@ -95,8 +95,8 @@ describe('Orchestrator', () => {
const events = (mocks.eventBus as MockEventBus).getEvents();
const readyEvent = events.find(e => e.event === SystemEvents.SYSTEM_READY);
- assertExists(readyEvent);
- assertExists(readyEvent!.data.timestamp);
+ expect(readyEvent).toBeDefined();
+ expect(readyEvent!.data.timestamp).toBeDefined();
});
it('should start background tasks', async () => {
@@ -153,7 +153,7 @@ describe('Orchestrator', () => {
// Fast forward time - should not trigger more health checks
await time.tickAsync(config.orchestrator.healthCheckInterval * 2);
- assertEquals(mocks.terminalManager.getHealthStatus.calls.length, initialHealthChecks);
+ expect(mocks.terminalManager.getHealthStatus.calls.length).toBe(initialHealthChecks);
});
it('should emit shutdown event', async () => {
@@ -162,8 +162,8 @@ describe('Orchestrator', () => {
const events = (mocks.eventBus as MockEventBus).getEvents();
const shutdownEvent = events.find(e => e.event === SystemEvents.SYSTEM_SHUTDOWN);
- assertExists(shutdownEvent);
- assertEquals(shutdownEvent!.data.reason, 'Graceful shutdown');
+ expect(shutdownEvent).toBeDefined();
+ expect(shutdownEvent!.data.reason).toBe('Graceful shutdown');
});
});
@@ -176,7 +176,7 @@ describe('Orchestrator', () => {
const profile = TestDataBuilder.agentProfile();
const sessionId = await orchestrator.spawnAgent(profile);
- assertExists(sessionId);
+ expect(sessionId).toBeDefined();
assertSpyCalls(mocks.terminalManager.spawnTerminal, 1);
assertSpyCalls(mocks.memoryManager.createBank, 1);
});
@@ -213,9 +213,9 @@ describe('Orchestrator', () => {
const events = (mocks.eventBus as MockEventBus).getEvents();
const spawnEvent = events.find(e => e.event === SystemEvents.AGENT_SPAWNED);
- assertExists(spawnEvent);
- assertEquals(spawnEvent!.data.agentId, profile.id);
- assertEquals(spawnEvent!.data.sessionId, sessionId);
+ expect(spawnEvent).toBeDefined();
+ expect(spawnEvent!.data.agentId).toBe(profile.id);
+ expect(spawnEvent!.data.sessionId).toBe(sessionId);
});
it('should terminate an agent', async () => {
@@ -251,8 +251,8 @@ describe('Orchestrator', () => {
const events = (mocks.eventBus as MockEventBus).getEvents();
const terminateEvent = events.find(e => e.event === SystemEvents.AGENT_TERMINATED);
- assertExists(terminateEvent);
- assertEquals(terminateEvent!.data.agentId, profile.id);
+ expect(terminateEvent).toBeDefined();
+ expect(terminateEvent!.data.agentId).toBe(profile.id);
});
it('should throw when terminating non-existent agent', async () => {
@@ -277,8 +277,8 @@ describe('Orchestrator', () => {
await orchestrator.assignTask(task);
assertSpyCalls(mocks.coordinationManager.assignTask, 1);
- assertEquals(mocks.coordinationManager.assignTask.calls[0].args[0], task);
- assertEquals(mocks.coordinationManager.assignTask.calls[0].args[1], profile.id);
+ expect(mocks.coordinationManager.assignTask.calls[0].args[0]).toBe(task);
+ expect(mocks.coordinationManager.assignTask.calls[0].args[1]).toBe(profile.id);
});
it('should queue task when no agent assigned', async () => {
@@ -287,8 +287,8 @@ describe('Orchestrator', () => {
const events = (mocks.eventBus as MockEventBus).getEvents();
const createEvent = events.find(e => e.event === SystemEvents.TASK_CREATED);
- assertExists(createEvent);
- assertEquals(createEvent!.data.task, task);
+ expect(createEvent).toBeDefined();
+ expect(createEvent!.data.task).toBe(task);
});
it('should validate task', async () => {
@@ -351,7 +351,7 @@ describe('Orchestrator', () => {
await new Promise(resolve => setTimeout(resolve, 10));
const metrics = await orchestrator.getMetrics();
- assertEquals(metrics.completedTasks, 1);
+ expect(metrics.completedTasks).toBe(1);
});
it('should handle task failure with retry', async () => {
@@ -367,7 +367,7 @@ describe('Orchestrator', () => {
await new Promise(resolve => setTimeout(resolve, 10));
const metrics = await orchestrator.getMetrics();
- assertEquals(metrics.failedTasks, 1);
+ expect(metrics.failedTasks).toBe(1);
});
it('should select best agent for task', async () => {
@@ -405,7 +405,7 @@ describe('Orchestrator', () => {
// Should assign to agent2
assertSpyCalls(mocks.coordinationManager.assignTask, 1);
- assertEquals(mocks.coordinationManager.assignTask.calls[0].args[1], agent2.id);
+ expect(mocks.coordinationManager.assignTask.calls[0].args[1]).toBe(agent2.id);
});
});
@@ -417,12 +417,12 @@ describe('Orchestrator', () => {
it('should return healthy status when all components healthy', async () => {
const health = await orchestrator.getHealthStatus();
- assertEquals(health.status, 'healthy');
- assertExists(health.components.terminal);
- assertExists(health.components.memory);
- assertExists(health.components.coordination);
- assertExists(health.components.mcp);
- assertExists(health.components.orchestrator);
+ expect(health.status).toBe('healthy');
+ expect(health.components.terminal).toBeDefined();
+ expect(health.components.memory).toBeDefined();
+ expect(health.components.coordination).toBeDefined();
+ expect(health.components.mcp).toBeDefined();
+ expect(health.components.orchestrator).toBeDefined();
});
it('should return unhealthy status when component fails', async () => {
@@ -433,8 +433,8 @@ describe('Orchestrator', () => {
const health = await orchestrator.getHealthStatus();
- assertEquals(health.status, 'unhealthy');
- assertEquals(health.components.terminal.status, 'unhealthy');
+ expect(health.status).toBe('unhealthy');
+ expect(health.components.terminal.status).toBe('unhealthy');
});
it('should return degraded status with circuit breaker open', async () => {
@@ -454,8 +454,8 @@ describe('Orchestrator', () => {
// Circuit breaker should be open now
const health = await orchestrator.getHealthStatus();
- assertEquals(health.status, 'degraded');
- assertEquals(health.components.orchestrator.error, 'Health check circuit breaker open');
+ expect(health.status).toBe('degraded');
+ expect(health.components.orchestrator.error).toBe('Health check circuit breaker open');
});
it('should include metrics in orchestrator health', async () => {
@@ -464,10 +464,10 @@ describe('Orchestrator', () => {
const health = await orchestrator.getHealthStatus();
- assertExists(health.components.orchestrator.metrics);
- assertEquals(health.components.orchestrator.metrics!.activeAgents, 1);
- assertExists(health.components.orchestrator.metrics!.uptime);
- assertExists(health.components.orchestrator.metrics!.memoryUsage);
+ expect(health.components.orchestrator.metrics).toBeDefined();
+ expect(health.components.orchestrator.metrics!.activeAgents).toBe(1);
+ expect(health.components.orchestrator.metrics!.uptime).toBeDefined();
+ expect(health.components.orchestrator.metrics!.memoryUsage).toBeDefined();
});
});
@@ -479,17 +479,17 @@ describe('Orchestrator', () => {
it('should return comprehensive metrics', async () => {
const metrics = await orchestrator.getMetrics();
- assertExists(metrics.uptime);
- assertEquals(metrics.totalAgents, 0);
- assertEquals(metrics.activeAgents, 0);
- assertEquals(metrics.totalTasks, 0);
- assertEquals(metrics.completedTasks, 0);
- assertEquals(metrics.failedTasks, 0);
- assertEquals(metrics.queuedTasks, 0);
- assertEquals(metrics.avgTaskDuration, 0);
- assertExists(metrics.memoryUsage);
- assertExists(metrics.cpuUsage);
- assertExists(metrics.timestamp);
+ expect(metrics.uptime).toBeDefined();
+ expect(metrics.totalAgents).toBe(0);
+ expect(metrics.activeAgents).toBe(0);
+ expect(metrics.totalTasks).toBe(0);
+ expect(metrics.completedTasks).toBe(0);
+ expect(metrics.failedTasks).toBe(0);
+ expect(metrics.queuedTasks).toBe(0);
+ expect(metrics.avgTaskDuration).toBe(0);
+ expect(metrics.memoryUsage).toBeDefined();
+ expect(metrics.cpuUsage).toBeDefined();
+ expect(metrics.timestamp).toBeDefined();
});
it('should track agent metrics', async () => {
@@ -497,8 +497,8 @@ describe('Orchestrator', () => {
await orchestrator.spawnAgent(TestDataBuilder.agentProfile({ id: 'agent-2' }));
const metrics = await orchestrator.getMetrics();
- assertEquals(metrics.totalAgents, 2);
- assertEquals(metrics.activeAgents, 2);
+ expect(metrics.totalAgents).toBe(2);
+ expect(metrics.activeAgents).toBe(2);
});
it('should track task metrics', async () => {
@@ -521,9 +521,9 @@ describe('Orchestrator', () => {
await new Promise(resolve => setTimeout(resolve, 10));
const metrics = await orchestrator.getMetrics();
- assertEquals(metrics.totalTasks, 1);
- assertEquals(metrics.completedTasks, 1);
- assertEquals(metrics.avgTaskDuration, 1000);
+ expect(metrics.totalTasks).toBe(1);
+ expect(metrics.completedTasks).toBe(1);
+ expect(metrics.avgTaskDuration).toBe(1000);
});
});
@@ -548,7 +548,7 @@ describe('Orchestrator', () => {
// Should not throw
await orchestrator.performMaintenance();
- assertEquals(mocks.logger.hasLog('error', 'Error during maintenance'), true);
+ expect(mocks.logger.hasLog('error').toBe('Error during maintenance'), true);
});
it('should clean up terminated sessions', async () => {
@@ -621,7 +621,7 @@ describe('Orchestrator', () => {
component: 'test-component',
});
- assertEquals(mocks.logger.hasLog('error', 'System error'), true);
+ expect(mocks.logger.hasLog('error').toBe('System error'), true);
});
});
@@ -648,7 +648,7 @@ describe('Orchestrator', () => {
// Should assign highest priority task
assertSpyCalls(mocks.coordinationManager.assignTask, 1);
- assertEquals(mocks.coordinationManager.assignTask.calls[0].args[0].id, 'high');
+ expect(mocks.coordinationManager.assignTask.calls[0].args[0].id).toBe('high');
});
it('should handle task assignment failures', async () => {
@@ -670,7 +670,7 @@ describe('Orchestrator', () => {
// Task should remain in queue
const metrics = await orchestrator.getMetrics();
- assertEquals(metrics.queuedTasks, 1);
+ expect(metrics.queuedTasks).toBe(1);
});
});
});
\ No newline at end of file
diff --git a/tests/unit/example.test.ts b/tests/unit/example.test.ts
index 3a5bb0df2d..8b2980fa7a 100644
--- a/tests/unit/example.test.ts
+++ b/tests/unit/example.test.ts
@@ -1,6 +1,4 @@
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertThrows } from "https://deno.land/[email protected]/assert/mod.ts";
-import { spy, stub } from "https://deno.land/[email protected]/testing/mock.ts";
+import { describe, it, beforeEach, afterEach, expect, jest } from "../test.utils.ts";
// Example calculator class to test
class Calculator {
@@ -45,83 +43,79 @@ describe("Calculator", () => {
describe("add", () => {
it("should add two positive numbers", () => {
const result = calculator.add(2, 3);
- assertEquals(result, 5);
+ expect(result).toBe(5);
});
it("should handle negative numbers", () => {
const result = calculator.add(-5, 3);
- assertEquals(result, -2);
+ expect(result).toBe(-2);
});
it("should handle zero", () => {
const result = calculator.add(0, 0);
- assertEquals(result, 0);
+ expect(result).toBe(0);
});
});
describe("subtract", () => {
it("should subtract two numbers", () => {
const result = calculator.subtract(10, 4);
- assertEquals(result, 6);
+ expect(result).toBe(6);
});
it("should handle negative results", () => {
const result = calculator.subtract(3, 5);
- assertEquals(result, -2);
+ expect(result).toBe(-2);
});
});
describe("multiply", () => {
it("should multiply two numbers", () => {
const result = calculator.multiply(4, 5);
- assertEquals(result, 20);
+ expect(result).toBe(20);
});
it("should handle multiplication by zero", () => {
const result = calculator.multiply(10, 0);
- assertEquals(result, 0);
+ expect(result).toBe(0);
});
});
describe("divide", () => {
it("should divide two numbers", () => {
const result = calculator.divide(10, 2);
- assertEquals(result, 5);
+ expect(result).toBe(5);
});
it("should handle decimal results", () => {
const result = calculator.divide(7, 2);
- assertEquals(result, 3.5);
+ expect(result).toBe(3.5);
});
it("should throw error when dividing by zero", () => {
- assertThrows(
- () => calculator.divide(10, 0),
- Error,
- "Division by zero"
- );
+ expect(() => calculator.divide(10, 0)).toThrow("Division by zero");
});
});
describe("asyncOperation", () => {
it("should double the value asynchronously", async () => {
const result = await calculator.asyncOperation(5);
- assertEquals(result, 10);
+ expect(result).toBe(10);
});
it("should handle zero", async () => {
const result = await calculator.asyncOperation(0);
- assertEquals(result, 0);
+ expect(result).toBe(0);
});
});
describe("instance", () => {
it("should create a calculator instance", () => {
- assertExists(calculator);
- assertEquals(typeof calculator.add, "function");
- assertEquals(typeof calculator.subtract, "function");
- assertEquals(typeof calculator.multiply, "function");
- assertEquals(typeof calculator.divide, "function");
+ expect(calculator).toBeDefined();
+ expect(typeof calculator.add).toBe("function");
+ expect(typeof calculator.subtract).toBe("function");
+ expect(typeof calculator.multiply).toBe("function");
+ expect(typeof calculator.divide).toBe("function");
});
});
});
@@ -130,25 +124,27 @@ describe("Calculator", () => {
describe("Calculator with mocks", () => {
it("should spy on method calls", () => {
const calculator = new Calculator();
- const addSpy = spy(calculator, "add");
+ const addSpy = jest.spyOn(calculator, "add");
calculator.add(2, 3);
calculator.add(4, 5);
- assertEquals(addSpy.calls.length, 2);
- assertEquals(addSpy.calls[0].args, [2, 3]);
- assertEquals(addSpy.calls[1].args, [4, 5]);
+ expect(addSpy).toHaveBeenCalledTimes(2);
+ expect(addSpy).toHaveBeenNthCalledWith(1, 2, 3);
+ expect(addSpy).toHaveBeenNthCalledWith(2, 4, 5);
+
+ addSpy.mockRestore();
});
it("should stub a method", () => {
const calculator = new Calculator();
- const multiplyStub = stub(calculator, "multiply", () => 100);
+ const multiplyStub = jest.spyOn(calculator, "multiply").mockImplementation(() => 100);
const result = calculator.multiply(2, 3);
- assertEquals(result, 100); // Stubbed value
+ expect(result).toBe(100); // Stubbed value
- multiplyStub.restore();
+ multiplyStub.mockRestore();
const realResult = calculator.multiply(2, 3);
- assertEquals(realResult, 6); // Real value after restore
+ expect(realResult).toBe(6); // Real value after restore
});
});
\ No newline at end of file
diff --git a/tests/unit/incremental-updates.test.ts b/tests/unit/incremental-updates.test.ts
index 24da383bb2..0a5fbf72f4 100644
--- a/tests/unit/incremental-updates.test.ts
+++ b/tests/unit/incremental-updates.test.ts
@@ -2,9 +2,9 @@
* Comprehensive unit tests for Incremental Updates across the system
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assert } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { assertEquals, assertExists, assert } from "../test.utils.ts";
+// FakeTime equivalent available in test.utils.ts
import { MemoryManager } from '../../src/memory/manager.ts';
import { MemoryBackendFactory } from '../../src/memory/backend.ts';
@@ -46,19 +46,19 @@ describe('Incremental Updates Test Suite', () => {
// Store initial entry
await memoryManager.store('test-key', 'initial value', { namespace: 'test' });
const initial = await memoryManager.retrieve('test-key', 'test');
- assertEquals(initial?.version, 1);
+ expect(initial?.version).toBe(1);
// First update
await memoryManager.update(initial!.id, { content: 'updated value 1' });
const updated1 = await memoryManager.retrieve('test-key', 'test');
- assertEquals(updated1?.version, 2);
- assertEquals(updated1?.content, 'updated value 1');
+ expect(updated1?.version).toBe(2);
+ expect(updated1?.content).toBe('updated value 1');
// Second update
await memoryManager.update(updated1!.id, { content: 'updated value 2' });
const updated2 = await memoryManager.retrieve('test-key', 'test');
- assertEquals(updated2?.version, 3);
- assertEquals(updated2?.content, 'updated value 2');
+ expect(updated2?.version).toBe(3);
+ expect(updated2?.content).toBe('updated value 2');
});
it('should handle partial updates correctly', async () => {
@@ -72,8 +72,8 @@ describe('Incremental Updates Test Suite', () => {
});
const updated = await memoryManager.retrieve('test-key', 'test');
- assertEquals(updated?.content, { a: 1, b: 5, c: 3 });
- assertEquals(updated?.metadata?.updated, true);
+ expect(updated?.content).toBe({ a: 1, b: 5, c: 3 });
+ expect(updated?.metadata?.updated).toBe(true);
});
it('should preserve timestamps correctly during updates', async () => {
@@ -87,8 +87,8 @@ describe('Incremental Updates Test Suite', () => {
await memoryManager.update(initial!.id, { content: 'updated' });
const updated = await memoryManager.retrieve('test-key', 'test');
- assertEquals(updated?.createdAt, createdAt);
- assert(updated!.updatedAt > createdAt);
+ expect(updated?.createdAt).toBe(createdAt);
+ expect(updated!.updatedAt > createdAt).toBeTruthy();
});
});
@@ -105,10 +105,10 @@ describe('Incremental Updates Test Suite', () => {
await swarmMemory.update('test-key', 'version 3');
const entry = await swarmMemory.get('test-key');
- assertEquals(entry.version, 3);
- assertEquals(entry.previousVersions.length, 2);
- assertEquals(entry.previousVersions[0].value, 'version 1');
- assertEquals(entry.previousVersions[1].value, 'version 2');
+ expect(entry.version).toBe(3);
+ expect(entry.previousVersions.length).toBe(2);
+ expect(entry.previousVersions[0].value).toBe('version 1');
+ expect(entry.previousVersions[1].value).toBe('version 2');
});
it('should limit version history to 10 entries', async () => {
@@ -120,10 +120,10 @@ describe('Incremental Updates Test Suite', () => {
}
const entry = await swarmMemory.get('test-key');
- assertEquals(entry.version, 13);
- assertEquals(entry.previousVersions.length, 10);
- assertEquals(entry.previousVersions[0].value, 'version 2');
- assertEquals(entry.previousVersions[9].value, 'version 11');
+ expect(entry.version).toBe(13);
+ expect(entry.previousVersions.length).toBe(10);
+ expect(entry.previousVersions[0].value).toBe('version 2');
+ expect(entry.previousVersions[9].value).toBe('version 11');
});
it('should handle concurrent updates with proper versioning', async () => {
@@ -138,8 +138,8 @@ describe('Incremental Updates Test Suite', () => {
await Promise.all(updates);
const final = await swarmMemory.get('counter');
- assertEquals(final.value, 10);
- assertEquals(final.version, 11); // Initial + 10 updates
+ expect(final.value).toBe(10);
+ expect(final.version).toBe(11); // Initial + 10 updates
});
});
@@ -166,21 +166,21 @@ describe('Incremental Updates Test Suite', () => {
});
const updated = configManager.getConfig();
- assertEquals(updated.temperature, 0.9);
- assertEquals(updated.tools.webSearch, false);
- assertEquals(updated.tools.memory, true); // Preserved
- assertEquals(updated.model, 'claude-3-sonnet'); // Preserved
+ expect(updated.temperature).toBe(0.9);
+ expect(updated.tools.webSearch).toBe(false);
+ expect(updated.tools.memory).toBe(true); // Preserved
+ expect(updated.model).toBe('claude-3-sonnet'); // Preserved
});
it('should track configuration differences', () => {
configManager.update({ temperature: 0.5 });
const diff = configManager.getDiff();
- assertEquals(diff, { temperature: 0.5 });
+ expect(diff).toBe({ temperature: 0.5 });
configManager.update({ maxTokens: 8192 });
const diff2 = configManager.getDiff();
- assertEquals(diff2, { temperature: 0.5, maxTokens: 8192 });
+ expect(diff2).toBe({ temperature: 0.5, maxTokens: 8192 });
});
});
@@ -215,10 +215,10 @@ describe('Incremental Updates Test Suite', () => {
cache.set('key2', 'value2');
cache.set('key3', 'value3'); // Should evict key1
- assertEquals(cache.has('key1'), false);
- assertEquals(cache.has('key2'), true);
- assertEquals(cache.has('key3'), true);
- assertEquals(cache.stats().size, 2);
+ expect(cache.has('key1')).toBe(false);
+ expect(cache.has('key2')).toBe(true);
+ expect(cache.has('key3')).toBe(true);
+ expect(cache.stats().size).toBe(2);
});
});
@@ -272,9 +272,9 @@ describe('Incremental Updates Test Suite', () => {
const result = deepMerge(original, update);
- assertEquals(original.nested.b, 2);
- assertEquals(result.nested.b, 3);
- assertEquals(result.nested.c, 4);
+ expect(original.nested.b).toBe(2);
+ expect(result.nested.b).toBe(3);
+ expect(result.nested.c).toBe(4);
});
});
@@ -296,12 +296,12 @@ describe('Incremental Updates Test Suite', () => {
threads: 2
});
- assertEquals(allocation1, true);
+ expect(allocation1).toBe(true);
const usage1 = resourceManager.getUsage();
- assertEquals(usage1.memory, 100 * 1024 * 1024);
- assertEquals(usage1.cpu, 1);
- assertEquals(usage1.threads, 2);
+ expect(usage1.memory).toBe(100 * 1024 * 1024);
+ expect(usage1.cpu).toBe(1);
+ expect(usage1.threads).toBe(2);
const allocation2 = await resourceManager.allocate('task2', {
memory: 200 * 1024 * 1024, // 200MB
@@ -309,12 +309,12 @@ describe('Incremental Updates Test Suite', () => {
threads: 3
});
- assertEquals(allocation2, true);
+ expect(allocation2).toBe(true);
const usage2 = resourceManager.getUsage();
- assertEquals(usage2.memory, 300 * 1024 * 1024);
- assertEquals(usage2.cpu, 2);
- assertEquals(usage2.threads, 5);
+ expect(usage2.memory).toBe(300 * 1024 * 1024);
+ expect(usage2.cpu).toBe(2);
+ expect(usage2.threads).toBe(5);
});
it('should handle resource deallocation correctly', async () => {
@@ -325,14 +325,14 @@ describe('Incremental Updates Test Suite', () => {
});
const usageBefore = resourceManager.getUsage();
- assertEquals(usageBefore.memory, 500 * 1024 * 1024);
+ expect(usageBefore.memory).toBe(500 * 1024 * 1024);
resourceManager.deallocate('task1');
const usageAfter = resourceManager.getUsage();
- assertEquals(usageAfter.memory, 0);
- assertEquals(usageAfter.cpu, 0);
- assertEquals(usageAfter.threads, 0);
+ expect(usageAfter.memory).toBe(0);
+ expect(usageAfter.cpu).toBe(0);
+ expect(usageAfter.threads).toBe(0);
});
});
@@ -362,8 +362,8 @@ describe('Incremental Updates Test Suite', () => {
// Verify all updates
for (let i = 0; i < 10; i++) {
const updated = await memoryManager.retrieve(`key-${i}`, 'batch');
- assertEquals(updated?.content, i + 10);
- assertEquals(updated?.version, 2);
+ expect(updated?.content).toBe(i + 10);
+ expect(updated?.version).toBe(2);
}
});
});
@@ -398,8 +398,8 @@ describe('Incremental Updates Test Suite', () => {
counter.increment();
const stats = counter.getStats();
- assertEquals(stats.value, 2);
- assertEquals(stats.updates, 4);
+ expect(stats.value).toBe(2);
+ expect(stats.updates).toBe(4);
});
});
@@ -422,9 +422,9 @@ describe('Incremental Updates Test Suite', () => {
// Wait for event propagation
await AsyncTestUtils.waitFor(() => updateEvents.length > 0, 100);
- assertEquals(updateEvents.length, 1);
- assertEquals(updateEvents[0].id, entry!.id);
- assertEquals(updateEvents[0].updates.content, 'updated');
+ expect(updateEvents.length).toBe(1);
+ expect(updateEvents[0].id).toBe(entry!.id);
+ expect(updateEvents[0].updates.content).toBe('updated');
});
});
});
\ No newline at end of file
diff --git a/tests/unit/mcp/mcp-interface.test.ts b/tests/unit/mcp/mcp-interface.test.ts
index 686825095a..67165eb79e 100644
--- a/tests/unit/mcp/mcp-interface.test.ts
+++ b/tests/unit/mcp/mcp-interface.test.ts
@@ -3,10 +3,10 @@
* Tests stdio and HTTP transports, protocol compliance, and error handling
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertRejects, assertThrows } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
-import { spy, stub } from "https://deno.land/[email protected]/testing/mock.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { expect } from "@jest/globals";
+// FakeTime equivalent available in test.utils.ts
+import { spy, stub } from "../test.utils.ts";
import { MCPServer } from '../../../src/mcp/server.ts';
import { MCPClient } from '../../../src/mcp/client.ts';
@@ -84,12 +84,12 @@ describe('MCP Interface - Comprehensive Tests', () => {
for (const message of validMessages) {
// Test message validation
const isValid = validateMCPMessage(message);
- assertEquals(isValid, true);
+ expect(isValid).toBe(true);
// Test serialization/deserialization
const serialized = JSON.stringify(message);
const deserialized = JSON.parse(serialized);
- assertEquals(deserialized, message);
+ expect(deserialized).toBe(message);
}
});
@@ -104,7 +104,7 @@ describe('MCP Interface - Comprehensive Tests', () => {
for (const message of invalidMessages) {
const isValid = validateMCPMessage(message);
- assertEquals(isValid, false);
+ expect(isValid).toBe(false);
}
});
@@ -154,10 +154,10 @@ describe('MCP Interface - Comprehensive Tests', () => {
for (const message of mcpMessages) {
const isValid = validateMCPMessage(message);
- assertEquals(isValid, true);
+ expect(isValid).toBe(true);
const messageType = getMCPMessageType(message);
- assertExists(messageType);
+ expect(messageType).toBeDefined();
}
});
@@ -176,9 +176,9 @@ describe('MCP Interface - Comprehensive Tests', () => {
const negotiatedCapabilities = negotiateCapabilities(serverCapabilities, clientCapabilities);
- assertExists(negotiatedCapabilities);
- assertEquals(typeof negotiatedCapabilities.server, 'object');
- assertEquals(typeof negotiatedCapabilities.client, 'object');
+ expect(negotiatedCapabilities).toBeDefined();
+ expect(typeof negotiatedCapabilities.server).toBe('object');
+ expect(typeof negotiatedCapabilities.client).toBe('object');
});
});
@@ -196,15 +196,15 @@ describe('MCP Interface - Comprehensive Tests', () => {
});
it('should create stdio transport successfully', () => {
- assertExists(stdioTransport);
+ expect(stdioTransport).toBeDefined();
});
it('should handle stdio start and stop', async () => {
// Since we can't actually test stdin/stdout in tests, we'll just verify the methods exist
- assertEquals(typeof stdioTransport.start, 'function');
- assertEquals(typeof stdioTransport.stop, 'function');
- assertEquals(typeof stdioTransport.connect, 'function');
- assertEquals(typeof stdioTransport.disconnect, 'function');
+ expect(typeof stdioTransport.start).toBe('function');
+ expect(typeof stdioTransport.stop).toBe('function');
+ expect(typeof stdioTransport.connect).toBe('function');
+ expect(typeof stdioTransport.disconnect).toBe('function');
});
});
@@ -253,14 +253,14 @@ describe('MCP Interface - Comprehensive Tests', () => {
});
it('should create HTTP transport successfully', () => {
- assertExists(httpTransport);
+ expect(httpTransport).toBeDefined();
});
it('should handle HTTP start and stop', async () => {
- assertEquals(typeof httpTransport.start, 'function');
- assertEquals(typeof httpTransport.stop, 'function');
- assertEquals(typeof httpTransport.connect, 'function');
- assertEquals(typeof httpTransport.disconnect, 'function');
+ expect(typeof httpTransport.start).toBe('function');
+ expect(typeof httpTransport.stop).toBe('function');
+ expect(typeof httpTransport.connect).toBe('function');
+ expect(typeof httpTransport.disconnect).toBe('function');
});
});
@@ -295,7 +295,7 @@ describe('MCP Interface - Comprehensive Tests', () => {
});
it('should create server correctly', () => {
- assertExists(mcpServer);
+ expect(mcpServer).toBeDefined();
});
it('should register and list tools correctly', () => {
@@ -329,7 +329,7 @@ describe('MCP Interface - Comprehensive Tests', () => {
// We can't test the actual listing without starting the server and having a proper transport
// But we can verify the registration doesn't throw
- assertEquals(true, true); // Registration successful
+ expect(true).toBe(true); // Registration successful
});
});
@@ -368,18 +368,18 @@ describe('MCP Interface - Comprehensive Tests', () => {
it('should connect and disconnect correctly', async () => {
await mcpClient.connect();
- assertEquals(mcpClient.isConnected(), true);
+ expect(mcpClient.isConnected()).toBe(true);
await mcpClient.disconnect();
- assertEquals(mcpClient.isConnected(), false);
+ expect(mcpClient.isConnected()).toBe(false);
});
it('should send requests correctly', async () => {
await mcpClient.connect();
const result = await mcpClient.request('test_method', { param: 'value' });
- assertExists(result);
- assertEquals(result, { success: true });
+ expect(result).toBeDefined();
+ expect(result).toBe({ success: true });
});
});
@@ -414,13 +414,13 @@ describe('MCP Interface - Comprehensive Tests', () => {
});
it('should create session manager correctly', () => {
- assertExists(sessionManager);
+ expect(sessionManager).toBeDefined();
});
it('should handle session operations', () => {
// Session manager doesn't have start/stop methods but we can test basic functionality
- assertEquals(typeof sessionManager.createSession, 'function');
- assertEquals(typeof sessionManager.getSession, 'function');
+ expect(typeof sessionManager.createSession).toBe('function');
+ expect(typeof sessionManager.getSession).toBe('function');
});
});
@@ -446,7 +446,7 @@ describe('MCP Interface - Comprehensive Tests', () => {
});
it('should create load balancer correctly', () => {
- assertExists(loadBalancer);
+ expect(loadBalancer).toBeDefined();
});
});
@@ -471,7 +471,7 @@ describe('MCP Interface - Comprehensive Tests', () => {
});
it('should create auth manager correctly', () => {
- assertExists(authManager);
+ expect(authManager).toBeDefined();
});
});
diff --git a/tests/unit/mcp/server.test.ts b/tests/unit/mcp/server.test.ts
index fb463a7b0d..b77a664b0f 100644
--- a/tests/unit/mcp/server.test.ts
+++ b/tests/unit/mcp/server.test.ts
@@ -2,8 +2,8 @@
* Unit tests for MCP Server
*/
-import { describe, it, beforeEach, afterEach } from 'https://deno.land/[email protected]/testing/bdd.ts';
-import { assertEquals, assertExists } from 'https://deno.land/[email protected]/assert/mod.ts';
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { assertEquals, assertExists } from "../test.utils.ts";
import { MCPServer } from '../../../src/mcp/server.ts';
import { MCPConfig, MCPTool } from '../../../src/utils/types.ts';
@@ -54,19 +54,19 @@ describe('MCPServer', () => {
describe('Lifecycle Management', () => {
it('should initialize correctly', () => {
- assertExists(server);
+ expect(server).toBeDefined();
});
it('should have start and stop methods', () => {
// Test that the methods exist without actually starting/stopping
- assertEquals(typeof server.start, 'function');
- assertEquals(typeof server.stop, 'function');
+ expect(typeof server.start).toBe('function');
+ expect(typeof server.stop).toBe('function');
});
it('should handle basic operations without starting', () => {
// Test basic server operations that don't require starting
- assertEquals(typeof server.registerTool, 'function');
- assertEquals(typeof server.getHealthStatus, 'function');
+ expect(typeof server.registerTool).toBe('function');
+ expect(typeof server.getHealthStatus).toBe('function');
});
it('should handle stop when not running', async () => {
@@ -109,7 +109,7 @@ describe('MCPServer', () => {
server.registerTool(testTool);
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('already registered'), true);
+ expect((error as Error).message.includes('already registered')).toBe(true);
}
});
});
@@ -117,23 +117,23 @@ describe('MCPServer', () => {
describe('Health and Metrics', () => {
it('should provide health status without starting', async () => {
const healthStatus = await server.getHealthStatus();
- assertExists(healthStatus);
- assertExists(healthStatus.healthy);
+ expect(healthStatus).toBeDefined();
+ expect(healthStatus.healthy).toBeDefined();
// Healthy should be false when not started
- assertEquals(healthStatus.healthy, false);
+ expect(healthStatus.healthy).toBe(false);
});
it('should provide metrics without starting', () => {
const metrics = server.getMetrics();
- assertExists(metrics);
- assertEquals(metrics.totalRequests >= 0, true);
- assertEquals(metrics.successfulRequests >= 0, true);
- assertEquals(metrics.failedRequests >= 0, true);
+ expect(metrics).toBeDefined();
+ expect(metrics.totalRequests >= 0).toBe(true);
+ expect(metrics.successfulRequests >= 0).toBe(true);
+ expect(metrics.failedRequests >= 0).toBe(true);
});
it('should track sessions without starting', () => {
const sessions = server.getSessions();
- assertEquals(Array.isArray(sessions), true);
+ expect(Array.isArray(sessions)).toBe(true);
});
});
@@ -141,13 +141,13 @@ describe('MCPServer', () => {
it('should get session by ID without starting', () => {
// Since no sessions are created in these tests, should return undefined
const session = server.getSession('non-existent');
- assertEquals(session, undefined);
+ expect(session).toBe(undefined);
});
it('should terminate sessions without starting', () => {
// Should not throw even if session doesn't exist
server.terminateSession('non-existent');
- assertEquals(true, true); // No errors thrown
+ expect(true).toBe(true); // No errors thrown
});
});
@@ -160,7 +160,7 @@ describe('MCPServer', () => {
};
const invalidServer = new MCPServer(invalidConfig, eventBus, logger);
- assertExists(invalidServer); // Should still create the server instance
+ expect(invalidServer).toBeDefined(); // Should still create the server instance
});
it('should handle tool registration errors', () => {
@@ -175,7 +175,7 @@ describe('MCPServer', () => {
server.registerTool(invalidTool);
throw new Error('Should have thrown an error');
} catch (error) {
- assertExists(error);
+ expect(error).toBeDefined();
}
});
});
diff --git a/tests/unit/mcp/tools.test.ts b/tests/unit/mcp/tools.test.ts
index 970741a7a7..e16ffede6a 100644
--- a/tests/unit/mcp/tools.test.ts
+++ b/tests/unit/mcp/tools.test.ts
@@ -2,8 +2,8 @@
* Unit tests for Tool Registry
*/
-import { describe, it, beforeEach } from 'https://deno.land/[email protected]/testing/bdd.ts';
-import { assertEquals, assertExists } from 'https://deno.land/[email protected]/assert/mod.ts';
+import { describe, it, beforeEach } from "../test.utils.ts";
+import { assertEquals, assertExists } from "../test.utils.ts";
import { ToolRegistry } from '../../../src/mcp/tools.ts';
import { MCPTool } from '../../../src/utils/types.ts';
@@ -44,9 +44,9 @@ describe('ToolRegistry', () => {
registry.register(tool);
const retrievedTool = registry.getTool('test/tool');
- assertExists(retrievedTool);
- assertEquals(retrievedTool?.name, 'test/tool');
- assertEquals(retrievedTool?.description, 'A test tool');
+ expect(retrievedTool).toBeDefined();
+ expect(retrievedTool?.name).toBe('test/tool');
+ expect(retrievedTool?.description).toBe('A test tool');
});
it('should prevent duplicate tool registration', () => {
@@ -63,7 +63,7 @@ describe('ToolRegistry', () => {
registry.register(tool);
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('already registered'), true);
+ expect((error as Error).message.includes('already registered')).toBe(true);
}
});
@@ -79,7 +79,7 @@ describe('ToolRegistry', () => {
registry.register(invalidTool);
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('format: namespace/name'), true);
+ expect((error as Error).message.includes('format: namespace/name')).toBe(true);
}
});
@@ -116,7 +116,7 @@ describe('ToolRegistry', () => {
registry.register(invalidTool as MCPTool);
throw new Error('Should have thrown an error');
} catch (error) {
- assertExists(error);
+ expect(error).toBeDefined();
}
}
});
@@ -146,28 +146,28 @@ describe('ToolRegistry', () => {
it('should retrieve a tool by name', () => {
const tool = registry.getTool('test/tool1');
- assertExists(tool);
- assertEquals(tool?.name, 'test/tool1');
- assertEquals(tool?.description, 'First test tool');
+ expect(tool).toBeDefined();
+ expect(tool?.name).toBe('test/tool1');
+ expect(tool?.description).toBe('First test tool');
});
it('should return undefined for non-existent tool', () => {
const tool = registry.getTool('test/nonexistent');
- assertEquals(tool, undefined);
+ expect(tool).toBe(undefined);
});
it('should list all tools', () => {
const tools = registry.listTools();
- assertExists(tools);
- assertEquals(tools.length, 2);
+ expect(tools).toBeDefined();
+ expect(tools.length).toBe(2);
const toolNames = tools.map(t => t.name);
- assertEquals(toolNames.includes('test/tool1'), true);
- assertEquals(toolNames.includes('test/tool2'), true);
+ expect(toolNames.includes('test/tool1')).toBe(true);
+ expect(toolNames.includes('test/tool2')).toBe(true);
});
it('should get tool count', () => {
- assertEquals(registry.getToolCount(), 2);
+ expect(registry.getToolCount()).toBe(2);
});
});
@@ -205,7 +205,7 @@ describe('ToolRegistry', () => {
it('should execute a tool successfully', async () => {
const result = await registry.executeTool('test/echo', { message: 'Hello, World!' });
- assertEquals(result, { echo: 'Hello, World!' });
+ expect(result).toBe({ echo: 'Hello, World!' });
});
it('should handle tool execution errors', async () => {
@@ -213,7 +213,7 @@ describe('ToolRegistry', () => {
await registry.executeTool('test/error', {});
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message, 'Test error');
+ expect((error as Error).message).toBe('Test error');
}
});
@@ -222,7 +222,7 @@ describe('ToolRegistry', () => {
await registry.executeTool('test/nonexistent', {});
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('Tool not found'), true);
+ expect((error as Error).message.includes('Tool not found')).toBe(true);
}
});
@@ -231,7 +231,7 @@ describe('ToolRegistry', () => {
await registry.executeTool('test/echo', {}); // Missing required 'message'
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('Missing required property'), true);
+ expect((error as Error).message.includes('Missing required property')).toBe(true);
}
});
@@ -240,7 +240,7 @@ describe('ToolRegistry', () => {
await registry.executeTool('test/echo', { message: 123 }); // Should be string
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('Invalid type'), true);
+ expect((error as Error).message.includes('Invalid type')).toBe(true);
}
});
});
@@ -258,11 +258,11 @@ describe('ToolRegistry', () => {
});
it('should unregister a tool', () => {
- assertExists(registry.getTool('test/removable'));
+ expect(registry.getTool('test/removable').toBeDefined());
registry.unregister('test/removable');
- assertEquals(registry.getTool('test/removable'), undefined);
+ expect(registry.getTool('test/removable')).toBe(undefined);
});
it('should handle unregistering non-existent tool', () => {
@@ -270,7 +270,7 @@ describe('ToolRegistry', () => {
registry.unregister('test/nonexistent');
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('Tool not found'), true);
+ expect((error as Error).message.includes('Tool not found')).toBe(true);
}
});
});
@@ -302,7 +302,7 @@ describe('ToolRegistry', () => {
name: 'John',
age: 30,
});
- assertEquals(result.name, 'John');
+ expect(result.name).toBe('John');
});
it('should validate number types', async () => {
@@ -313,7 +313,7 @@ describe('ToolRegistry', () => {
});
throw new Error('Should have thrown an error');
} catch (error) {
- assertEquals((error as Error).message.includes('Invalid type'), true);
+ expect((error as Error).message.includes('Invalid type')).toBe(true);
}
});
@@ -323,7 +323,7 @@ describe('ToolRegistry', () => {
age: 30,
active: true,
});
- assertEquals(result.active, true);
+ expect(result.active).toBe(true);
});
it('should validate array types', async () => {
@@ -332,7 +332,7 @@ describe('ToolRegistry', () => {
age: 30,
tags: ['developer', 'typescript'],
});
- assertEquals(result.tags, ['developer', 'typescript']);
+ expect(result.tags).toBe(['developer', 'typescript']);
});
it('should validate object types', async () => {
@@ -341,7 +341,7 @@ describe('ToolRegistry', () => {
age: 30,
metadata: { department: 'engineering' },
});
- assertEquals(result.metadata, { department: 'engineering' });
+ expect(result.metadata).toBe({ department: 'engineering' });
});
it('should handle null input for non-object schema', async () => {
@@ -355,7 +355,7 @@ describe('ToolRegistry', () => {
registry.register(tool);
const result = await registry.executeTool('test/null', null);
- assertEquals(result, { received: 'null' });
+ expect(result).toBe({ received: 'null' });
});
});
});
\ No newline at end of file
diff --git a/tests/unit/memory/memory-backends.test.ts b/tests/unit/memory/memory-backends.test.ts
index d62b9b137a..94378eb10b 100644
--- a/tests/unit/memory/memory-backends.test.ts
+++ b/tests/unit/memory/memory-backends.test.ts
@@ -2,9 +2,9 @@
* Comprehensive unit tests for Memory Backends (SQLite and Markdown)
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertRejects, assertThrows } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { expect } from "@jest/globals";
+// FakeTime equivalent available in test.utils.ts
import { SQLiteMemoryBackend } from '../../../src/memory/backends/sqlite.ts';
import { MarkdownMemoryBackend } from '../../../src/memory/backends/markdown.ts';
@@ -68,11 +68,11 @@ describe('Memory Backends - Comprehensive Tests', () => {
await backend.store(namespace, entry.key, entry.value, entry.tags, entry.metadata);
const retrieved = await backend.retrieve(namespace, entry.key);
- assertEquals(retrieved.value, entry.value);
- assertEquals(retrieved.tags, entry.tags);
- assertEquals(retrieved.metadata, entry.metadata);
- assertExists(retrieved.createdAt);
- assertExists(retrieved.updatedAt);
+ expect(retrieved.value).toBe(entry.value);
+ expect(retrieved.tags).toBe(entry.tags);
+ expect(retrieved.metadata).toBe(entry.metadata);
+ expect(retrieved.createdAt).toBeDefined();
+ expect(retrieved.updatedAt).toBeDefined();
});
it('should handle different data types', async () => {
@@ -94,7 +94,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
// Retrieve and verify all test data
for (const { key, value } of testData) {
const retrieved = await backend.retrieve(namespace, key);
- assertEquals(retrieved.value, value);
+ expect(retrieved.value).toBe(value);
}
});
@@ -110,9 +110,9 @@ describe('Memory Backends - Comprehensive Tests', () => {
await backend.store(namespace, key, { version: 2 });
const updated = await backend.retrieve(namespace, key);
- assertEquals(updated.value, { version: 2 });
- assertEquals(updated.createdAt, initial.createdAt); // Should not change
- assertEquals(updated.updatedAt > initial.updatedAt, true); // Should be newer
+ expect(updated.value).toBe({ version: 2 });
+ expect(updated.createdAt).toBe(initial.createdAt); // Should not change
+ expect(updated.updatedAt > initial.updatedAt).toBe(true); // Should be newer
});
it('should delete entries', async () => {
@@ -122,7 +122,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
await backend.store(namespace, key, { data: 'to be deleted' });
const deleted = await backend.delete(namespace, key);
- assertEquals(deleted, true);
+ expect(deleted).toBe(true);
await assertRejects(
() => backend.retrieve(namespace, key),
@@ -139,7 +139,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
);
const deleted = await backend.delete('nonexistent', 'key');
- assertEquals(deleted, false);
+ expect(deleted).toBe(false);
});
});
@@ -160,11 +160,11 @@ describe('Memory Backends - Comprehensive Tests', () => {
it('should list entries by namespace', async () => {
const entries = await backend.list('test');
- assertEquals(entries.length >= 1, true);
+ expect(entries.length >= 1).toBe(true);
// All entries should be from 'test' namespace
entries.forEach(entry => {
- assertEquals(entry.namespace, 'test');
+ expect(entry.namespace).toBe('test');
});
});
@@ -179,14 +179,14 @@ describe('Memory Backends - Comprehensive Tests', () => {
tags: ['important'],
});
- assertEquals(importantEntries.length, 2);
+ expect(importantEntries.length).toBe(2);
const urgentEntries = await backend.search({
namespace: 'search',
tags: ['urgent'],
});
- assertEquals(urgentEntries.length, 2);
+ expect(urgentEntries.length).toBe(2);
const bothTags = await backend.search({
namespace: 'search',
@@ -194,7 +194,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
tagMode: 'all',
});
- assertEquals(bothTags.length, 1);
+ expect(bothTags.length).toBe(1);
});
it('should search with pagination', async () => {
@@ -210,14 +210,14 @@ describe('Memory Backends - Comprehensive Tests', () => {
offset: 10,
});
- assertEquals(page1.length, 10);
- assertEquals(page2.length >= 1, true);
+ expect(page1.length).toBe(10);
+ expect(page2.length >= 1).toBe(true);
// No overlap between pages
const page1Keys = new Set(page1.map(e => e.key));
const page2Keys = new Set(page2.map(e => e.key));
const intersection = new Set([...page1Keys].filter(k => page2Keys.has(k)));
- assertEquals(intersection.size, 0);
+ expect(intersection.size).toBe(0);
});
it('should search with date ranges', async () => {
@@ -230,14 +230,14 @@ describe('Memory Backends - Comprehensive Tests', () => {
});
// All entries should be recent (created in this test)
- assertEquals(recentEntries.length >= 1, true);
+ expect(recentEntries.length >= 1).toBe(true);
const futureEntries = await backend.search({
namespace: 'test',
createdAfter: new Date(now.getTime() + 60 * 60 * 1000),
});
- assertEquals(futureEntries.length, 0);
+ expect(futureEntries.length).toBe(0);
});
it('should search with complex queries', async () => {
@@ -263,7 +263,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
// Note: actual content search would depend on backend implementation
});
- assertEquals(results.length, 2);
+ expect(results.length).toBe(2);
});
});
@@ -305,7 +305,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
// Verify all operations completed successfully
const allEntries = await backend.list('concurrent');
- assertEquals(allEntries.length, 50);
+ expect(allEntries.length).toBe(50);
});
it('should maintain performance with large datasets', async () => {
@@ -348,7 +348,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
}
});
- assertEquals(leaked, false);
+ expect(leaked).toBe(false);
});
});
@@ -387,7 +387,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
// Some edge cases might be normalized (e.g., undefined -> null)
// Just verify we can store and retrieve them
- assertExists(retrieved);
+ expect(retrieved).toBeDefined();
} catch (error) {
// Some edge cases may legitimately fail
console.log(`Edge case ${category}-${name} failed: ${error.message}`);
@@ -428,7 +428,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
try {
await backend.store('large-test', 'big-value', largeValue);
const retrieved = await backend.retrieve('large-test', 'big-value');
- assertEquals(retrieved.value.data.length, largeValue.data.length);
+ expect(retrieved.value.data.length).toBe(largeValue.data.length);
} catch (error) {
// May fail on systems with limited disk space
console.log(`Large value test failed: ${error.message}`);
@@ -520,9 +520,9 @@ describe('Memory Backends - Comprehensive Tests', () => {
await backend.store(namespace, entry.key, entry.value, entry.tags);
const retrieved = await backend.retrieve(namespace, entry.key);
- assertEquals(retrieved.value, entry.value);
- assertEquals(retrieved.tags, entry.tags);
- assertExists(retrieved.createdAt);
+ expect(retrieved.value).toBe(entry.value);
+ expect(retrieved.tags).toBe(entry.tags);
+ expect(retrieved.createdAt).toBeDefined();
});
it('should handle different content types', async () => {
@@ -557,7 +557,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
for (const { key, value } of testContent) {
const retrieved = await backend.retrieve(namespace, key);
- assertEquals(retrieved.value, value);
+ expect(retrieved.value).toBe(value);
}
});
@@ -569,7 +569,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
// Verify file was created in correct directory
const filePath = `${tempDir}/markdown-memory/project/docs/readme.md`;
const fileExists = await Deno.stat(filePath).then(() => true).catch(() => false);
- assertEquals(fileExists, true);
+ expect(fileExists).toBe(true);
});
it('should handle file naming and escaping', async () => {
@@ -589,7 +589,7 @@ describe('Memory Backends - Comprehensive Tests', () => {
for (const key of specialKeys) {
const retrieved = await backend.retrieve('special', key);
- assertEquals(retrieved.value.content, `Content for ${key}`);
+ expect(retrieved.value.content).toBe(`Content for ${key}`);
}
});
});
@@ -634,7 +634,7 @@ function hello() {
});
const retrieved = await backend.retrieve('markdown', 'formatted-doc');
- assertEquals(retrieved.value.content, markdownContent);
+ expect(retrieved.value.content).toBe(markdownContent);
});
it('should handle frontmatter metadata', async () => {
@@ -649,7 +649,7 @@ function hello() {
await backend.store('frontmatter', 'meta-doc', contentWithFrontmatter);
const retrieved = await backend.retrieve('frontmatter', 'meta-doc');
- assertEquals(retrieved.value, contentWithFrontmatter);
+ expect(retrieved.value).toBe(contentWithFrontmatter);
});
});
@@ -697,11 +697,11 @@ function hello() {
query: 'programming',
});
- assertEquals(results.length, 2);
+ expect(results.length).toBe(2);
const titles = results.map(r => r.value.title);
- assertEquals(titles.includes('JavaScript Guide'), true);
- assertEquals(titles.includes('Python Tutorial'), true);
+ expect(titles.includes('JavaScript Guide')).toBe(true);
+ expect(titles.includes('Python Tutorial')).toBe(true);
});
it('should search by tags', async () => {
@@ -710,15 +710,15 @@ function hello() {
tags: ['programming'],
});
- assertEquals(programmingDocs.length, 2);
+ expect(programmingDocs.length).toBe(2);
const tutorialDocs = await backend.search({
namespace: 'search-test',
tags: ['tutorial'],
});
- assertEquals(tutorialDocs.length, 1);
- assertEquals(tutorialDocs[0].value.title, 'Python Tutorial');
+ expect(tutorialDocs.length).toBe(1);
+ expect(tutorialDocs[0].value.title).toBe('Python Tutorial');
});
it('should search with complex queries', async () => {
@@ -728,7 +728,7 @@ function hello() {
query: 'JavaScript OR Python',
});
- assertEquals(languageResults.length >= 2, true);
+ expect(languageResults.length >= 2).toBe(true);
// Search for programming AND tutorial
const tutorialResults = await backend.search({
@@ -736,8 +736,8 @@ function hello() {
query: 'programming AND tutorial',
});
- assertEquals(tutorialResults.length, 1);
- assertEquals(tutorialResults[0].value.title, 'Python Tutorial');
+ expect(tutorialResults.length).toBe(1);
+ expect(tutorialResults[0].value.title).toBe('Python Tutorial');
});
});
@@ -769,15 +769,15 @@ function hello() {
// Verify file exists
const filePath = `${tempDir}/markdown-memory/${namespace}/${key}.md`;
const existsBefore = await Deno.stat(filePath).then(() => true).catch(() => false);
- assertEquals(existsBefore, true);
+ expect(existsBefore).toBe(true);
// Delete the entry
const deleted = await backend.delete(namespace, key);
- assertEquals(deleted, true);
+ expect(deleted).toBe(true);
// Verify file is removed
const existsAfter = await Deno.stat(filePath).then(() => true).catch(() => false);
- assertEquals(existsAfter, false);
+ expect(existsAfter).toBe(false);
});
it('should handle directory cleanup', async () => {
@@ -821,7 +821,7 @@ function hello() {
// If it succeeds, the backend handled it gracefully
} catch (error) {
// Expected to fail with non-serializable content
- assertExists(error);
+ expect(error).toBeDefined();
}
});
@@ -841,11 +841,11 @@ function hello() {
// At least one should succeed
const successful = results.filter(r => r.status === 'fulfilled');
- assertEquals(successful.length >= 1, true);
+ expect(successful.length >= 1).toBe(true);
// Verify we can read the final state
const final = await backend.retrieve(namespace, key);
- assertExists(final);
+ expect(final).toBeDefined();
});
});
});
@@ -901,8 +901,8 @@ function hello() {
]);
// Values should be equivalent
- assertEquals(sqliteResult.value, markdownResult.value);
- assertEquals(sqliteResult.tags, markdownResult.tags);
+ expect(sqliteResult.value).toBe(markdownResult.value);
+ expect(sqliteResult.tags).toBe(markdownResult.tags);
});
it('should handle performance comparison', async () => {
@@ -962,7 +962,7 @@ function hello() {
// Verify data integrity after migration
const markdownEntries = await markdownBackend.list('test');
- assertEquals(markdownEntries.length, sqliteEntries.length);
+ expect(markdownEntries.length).toBe(sqliteEntries.length);
// Spot check a few entries
for (let i = 0; i < Math.min(5, sqliteEntries.length); i++) {
@@ -972,8 +972,8 @@ function hello() {
sqliteEntry.key
);
- assertEquals(markdownEntry.value, sqliteEntry.value);
- assertEquals(markdownEntry.tags, sqliteEntry.tags);
+ expect(markdownEntry.value).toBe(sqliteEntry.value);
+ expect(markdownEntry.tags).toBe(sqliteEntry.tags);
}
});
});
diff --git a/tests/unit/simple-example.test.ts b/tests/unit/simple-example.test.ts
index 6b9f5088c9..43d20e7963 100644
--- a/tests/unit/simple-example.test.ts
+++ b/tests/unit/simple-example.test.ts
@@ -1,5 +1,4 @@
-import { describe, it, beforeEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertGreater } from "https://deno.land/[email protected]/assert/mod.ts";
+import { describe, it, beforeEach, expect } from "@jest/globals";
// Simple utility functions to test
function greet(name: string): string {
@@ -21,39 +20,39 @@ describe("Simple Test Suite", () => {
describe("greet function", () => {
it("should return a greeting message", () => {
const result = greet("World");
- assertEquals(result, "Hello, World!");
+ expect(result).toBe("Hello, World!");
});
it("should handle empty string", () => {
const result = greet("");
- assertEquals(result, "Hello, !");
+ expect(result).toBe("Hello, !");
});
it("should handle special characters", () => {
const result = greet("Claude-Flow πŸš€");
- assertEquals(result, "Hello, Claude-Flow πŸš€!");
+ expect(result).toBe("Hello, Claude-Flow πŸš€!");
});
});
describe("sum function", () => {
it("should sum an array of numbers", () => {
const result = sum([1, 2, 3, 4, 5]);
- assertEquals(result, 15);
+ expect(result).toBe(15);
});
it("should return 0 for empty array", () => {
const result = sum([]);
- assertEquals(result, 0);
+ expect(result).toBe(0);
});
it("should handle negative numbers", () => {
const result = sum([-5, 10, -3, 8]);
- assertEquals(result, 10);
+ expect(result).toBe(10);
});
it("should handle decimal numbers", () => {
const result = sum([1.5, 2.5, 3.0]);
- assertEquals(result, 7.0);
+ expect(result).toBe(7.0);
});
});
@@ -61,19 +60,19 @@ describe("Simple Test Suite", () => {
it("should format date correctly", () => {
const date = new Date(2024, 0, 15); // January 15, 2024
const result = formatDate(date);
- assertEquals(result, "2024-01-15");
+ expect(result).toBe("2024-01-15");
});
it("should pad single digit months and days", () => {
const date = new Date(2024, 2, 5); // March 5, 2024
const result = formatDate(date);
- assertEquals(result, "2024-03-05");
+ expect(result).toBe("2024-03-05");
});
it("should handle end of year", () => {
const date = new Date(2023, 11, 31); // December 31, 2023
const result = formatDate(date);
- assertEquals(result, "2023-12-31");
+ expect(result).toBe("2023-12-31");
});
});
@@ -81,17 +80,17 @@ describe("Simple Test Suite", () => {
it("should demonstrate various assertions", () => {
// Check existence
const obj = { name: "test", value: 42 };
- assertExists(obj);
- assertExists(obj.name);
+ expect(obj).toBeDefined();
+ expect(obj.name).toBeDefined();
// Check equality
- assertEquals(2 + 2, 4);
- assertEquals("hello".toUpperCase(), "HELLO");
- assertEquals([1, 2, 3].length, 3);
+ expect(2 + 2).toBe(4);
+ expect("hello".toUpperCase()).toBe("HELLO");
+ expect([1, 2, 3].length).toBe(3);
// Check comparison
- assertGreater(10, 5);
- assertGreater(new Date().getFullYear(), 2020);
+ expect(10).toBeGreaterThan(5);
+ expect(new Date().getFullYear()).toBeGreaterThan(2020);
});
});
});
\ No newline at end of file
diff --git a/tests/unit/terminal/terminal-manager.test.ts b/tests/unit/terminal/terminal-manager.test.ts
index a7df29518b..980a8043a2 100644
--- a/tests/unit/terminal/terminal-manager.test.ts
+++ b/tests/unit/terminal/terminal-manager.test.ts
@@ -2,10 +2,10 @@
* Comprehensive unit tests for Terminal Manager
*/
-import { describe, it, beforeEach, afterEach } from "https://deno.land/[email protected]/testing/bdd.ts";
-import { assertEquals, assertExists, assertRejects, assertThrows } from "https://deno.land/[email protected]/assert/mod.ts";
-import { FakeTime } from "https://deno.land/[email protected]/testing/time.ts";
-import { spy, stub } from "https://deno.land/[email protected]/testing/mock.ts";
+import { describe, it, beforeEach, afterEach } from "../test.utils.ts";
+import { expect } from "@jest/globals";
+// FakeTime equivalent available in test.utils.ts
+import { spy, stub } from "../test.utils.ts";
import { TerminalManager } from '../../../src/terminal/manager.ts';
import { TerminalPool } from '../../../src/terminal/pool.ts';
@@ -61,8 +61,8 @@ describe('Terminal Manager - Comprehensive Tests', () => {
it('should initialize successfully with valid configuration', async () => {
await terminalManager.initialize();
- assertEquals(mockPool.initialize.calls.length, 1);
- assertEquals(terminalManager.isInitialized(), true);
+ expect(mockPool.initialize.calls.length).toBe(1);
+ expect(terminalManager.isInitialized()).toBe(true);
});
it('should validate configuration parameters', () => {
@@ -100,7 +100,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
'Pool initialization failed'
);
- assertEquals(terminalManager.isInitialized(), false);
+ expect(terminalManager.isInitialized()).toBe(false);
});
it('should prevent double initialization', async () => {
@@ -122,7 +122,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
});
await nativeManager.initialize();
- assertEquals(nativeManager.isInitialized(), true);
+ expect(nativeManager.isInitialized()).toBe(true);
await nativeManager.shutdown();
});
});
@@ -142,29 +142,29 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const sessionId = await terminalManager.spawnTerminal(profile);
- assertExists(sessionId);
- assertEquals(mockPool.createSession.calls.length, 1);
- assertEquals(mockPool.createSession.calls[0].args[0], profile);
+ expect(sessionId).toBeDefined();
+ expect(mockPool.createSession.calls.length).toBe(1);
+ expect(mockPool.createSession.calls[0].args[0]).toBe(profile);
});
it('should handle session creation with default profile', async () => {
const sessionId = await terminalManager.spawnTerminal();
- assertExists(sessionId);
- assertEquals(mockPool.createSession.calls.length, 1);
+ expect(sessionId).toBeDefined();
+ expect(mockPool.createSession.calls.length).toBe(1);
// Should use default profile
const passedProfile = mockPool.createSession.calls[0].args[0];
- assertEquals(typeof passedProfile.id, 'string');
- assertEquals(typeof passedProfile.name, 'string');
+ expect(typeof passedProfile.id).toBe('string');
+ expect(typeof passedProfile.name).toBe('string');
});
it('should terminate sessions correctly', async () => {
const sessionId = await terminalManager.spawnTerminal();
await terminalManager.terminateTerminal(sessionId);
- assertEquals(mockPool.destroySession.calls.length, 1);
- assertEquals(mockPool.destroySession.calls[0].args[0], sessionId);
+ expect(mockPool.destroySession.calls.length).toBe(1);
+ expect(mockPool.destroySession.calls[0].args[0]).toBe(sessionId);
});
it('should handle termination of non-existent session', async () => {
@@ -211,12 +211,12 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const sessionIds = await Promise.all(promises);
- assertEquals(sessionIds.length, 5);
- assertEquals(mockPool.createSession.calls.length, 5);
+ expect(sessionIds.length).toBe(5);
+ expect(mockPool.createSession.calls.length).toBe(5);
// All session IDs should be unique
const uniqueIds = new Set(sessionIds);
- assertEquals(uniqueIds.size, 5);
+ expect(uniqueIds.size).toBe(5);
});
it('should handle session timeout cleanup', async () => {
@@ -231,7 +231,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
await terminalManager.performMaintenance();
// Should clean up expired sessions
- assertEquals(mockPool.performMaintenance.calls.length, 1);
+ expect(mockPool.performMaintenance.calls.length).toBe(1);
});
});
@@ -252,10 +252,10 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const result = await terminalManager.sendCommand(sessionId, command);
- assertExists(result);
- assertEquals(mockPool.executeCommand.calls.length, 1);
- assertEquals(mockPool.executeCommand.calls[0].args[0], sessionId);
- assertEquals(mockPool.executeCommand.calls[0].args[1], command);
+ expect(result).toBeDefined();
+ expect(mockPool.executeCommand.calls.length).toBe(1);
+ expect(mockPool.executeCommand.calls[0].args[0]).toBe(sessionId);
+ expect(mockPool.executeCommand.calls[0].args[1]).toBe(command);
});
it('should handle string commands', async () => {
@@ -263,8 +263,8 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const result = await terminalManager.sendCommand(sessionId, command);
- assertExists(result);
- assertEquals(mockPool.executeCommand.calls.length, 1);
+ expect(result).toBeDefined();
+ expect(mockPool.executeCommand.calls.length).toBe(1);
});
it('should handle command timeout', async () => {
@@ -289,8 +289,8 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const results = await Promise.all(promises);
- assertEquals(results.length, 10);
- assertEquals(mockPool.executeCommand.calls.length, 10);
+ expect(results.length).toBe(10);
+ expect(mockPool.executeCommand.calls.length).toBe(10);
});
it('should handle command execution on multiple sessions', async () => {
@@ -306,8 +306,8 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const results = await Promise.all(promises);
- assertEquals(results.length, 3);
- assertEquals(mockPool.executeCommand.calls.length, 3);
+ expect(results.length).toBe(3);
+ expect(mockPool.executeCommand.calls.length).toBe(3);
});
it('should handle command execution errors', async () => {
@@ -356,7 +356,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
);
TestAssertions.assertInRange(stats.mean, 0, 100); // Should be fast
- assertEquals(mockPool.createSession.calls.length, 100);
+ expect(mockPool.createSession.calls.length).toBe(100);
console.log(`Session creation performance: ${stats.mean.toFixed(2)}ms average`);
});
@@ -370,7 +370,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
);
TestAssertions.assertInRange(stats.mean, 0, 50); // Should be fast
- assertEquals(mockPool.executeCommand.calls.length, 50);
+ expect(mockPool.executeCommand.calls.length).toBe(50);
console.log(`Command execution performance: ${stats.mean.toFixed(2)}ms average`);
});
@@ -395,7 +395,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
);
});
- assertEquals(leaked, false);
+ expect(leaked).toBe(false);
});
it('should maintain performance under resource pressure', async () => {
@@ -445,10 +445,10 @@ describe('Terminal Manager - Comprehensive Tests', () => {
it('should report health status correctly', async () => {
const health = await terminalManager.getHealthStatus();
- assertEquals(health.healthy, true);
- assertExists(health.metrics);
- assertEquals(typeof health.metrics.activeSessions, 'number');
- assertEquals(typeof health.metrics.availableSlots, 'number');
+ expect(health.healthy).toBe(true);
+ expect(health.metrics).toBeDefined();
+ expect(typeof health.metrics.activeSessions).toBe('number');
+ expect(typeof health.metrics.availableSlots).toBe('number');
});
it('should detect unhealthy pool status', async () => {
@@ -458,14 +458,14 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const health = await terminalManager.getHealthStatus();
- assertEquals(health.healthy, false);
- assertExists(health.error);
+ expect(health.healthy).toBe(false);
+ expect(health.error).toBeDefined();
});
it('should perform maintenance operations', async () => {
await terminalManager.performMaintenance();
- assertEquals(mockPool.performMaintenance.calls.length, 1);
+ expect(mockPool.performMaintenance.calls.length).toBe(1);
});
it('should handle maintenance errors gracefully', async () => {
@@ -476,7 +476,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
// Should not throw, but log error
await terminalManager.performMaintenance();
- assertEquals(mockPool.performMaintenance.calls.length, 1);
+ expect(mockPool.performMaintenance.calls.length).toBe(1);
});
it('should track session metrics accurately', async () => {
@@ -496,7 +496,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const health = await terminalManager.getHealthStatus();
- assertExists(health.metrics);
+ expect(health.metrics).toBeDefined();
TestAssertions.assertInRange(health.metrics.activeSessions, 0, 10);
TestAssertions.assertInRange(health.metrics.totalCommands, 3, 100);
});
@@ -543,7 +543,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
for (const profile of validProfiles) {
try {
const sessionId = await terminalManager.spawnTerminal(profile);
- assertExists(sessionId);
+ expect(sessionId).toBeDefined();
} catch (error) {
// Some edge cases may be rejected, which is acceptable
}
@@ -571,8 +571,8 @@ describe('Terminal Manager - Comprehensive Tests', () => {
const successes = results.filter(r => typeof r === 'string');
const failures = results.filter(r => r instanceof Error);
- assertEquals(successes.length >= 1, true);
- assertEquals(failures.length >= 1, true);
+ expect(successes.length >= 1).toBe(true);
+ expect(failures.length >= 1).toBe(true);
});
it('should handle resource exhaustion scenarios', async () => {
@@ -606,10 +606,10 @@ describe('Terminal Manager - Comprehensive Tests', () => {
try {
const result = await terminalManager.sendCommand(sessionId, 'test-command');
// If retry logic is implemented, this should eventually succeed
- assertExists(result);
+ expect(result).toBeDefined();
} catch (error) {
// If no retry logic, should fail on first attempt
- assertEquals(error.message, 'Adapter temporarily unavailable');
+ expect(error.message).toBe('Adapter temporarily unavailable');
}
});
});
@@ -626,8 +626,8 @@ describe('Terminal Manager - Comprehensive Tests', () => {
await terminalManager.shutdown();
- assertEquals(mockPool.shutdown.calls.length, 1);
- assertEquals(terminalManager.isInitialized(), false);
+ expect(mockPool.shutdown.calls.length).toBe(1);
+ expect(terminalManager.isInitialized()).toBe(false);
});
it('should handle shutdown with active sessions', async () => {
@@ -644,7 +644,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
// Both should complete (command may be cancelled)
await Promise.allSettled([commandPromise, shutdownPromise]);
- assertEquals(terminalManager.isInitialized(), false);
+ expect(terminalManager.isInitialized()).toBe(false);
});
it('should timeout shutdown if pool hangs', async () => {
@@ -670,7 +670,7 @@ describe('Terminal Manager - Comprehensive Tests', () => {
// Should complete shutdown despite pool error
await terminalManager.shutdown();
- assertEquals(terminalManager.isInitialized(), false);
+ expect(terminalManager.isInitialized()).toBe(false);
});
it('should prevent operations after shutdown', async () => {
diff --git a/tests/unit/utils/helpers.test.ts b/tests/unit/utils/helpers.test.ts
index b1e4f766cb..b833cd4ea7 100644
--- a/tests/unit/utils/helpers.test.ts
+++ b/tests/unit/utils/helpers.test.ts
@@ -49,22 +49,22 @@ describe('Helpers', () => {
const id1 = generateId();
const id2 = generateId();
- assertExists(id1);
- assertExists(id2);
- assertEquals(id1 === id2, false);
- assertEquals(typeof id1, 'string');
- assertEquals(typeof id2, 'string');
+ expect(id1).toBeDefined();
+ expect(id2).toBeDefined();
+ expect(id1 === id2).toBe(false);
+ expect(typeof id1).toBe('string');
+ expect(typeof id2).toBe('string');
});
it('should include prefix when provided', () => {
const id = generateId('test');
- assertEquals(id.startsWith('test_'), true);
+ expect(id.startsWith('test_')).toBe(true);
});
it('should generate IDs of reasonable length', () => {
const id = generateId();
- assertEquals(id.length > 10, true);
- assertEquals(id.length < 50, true);
+ expect(id.length > 10).toBe(true);
+ expect(id.length < 50).toBe(true);
});
});
@@ -85,7 +85,7 @@ describe('Helpers', () => {
await delay(0);
const elapsed = Date.now() - start;
- assertEquals(elapsed < 10, true);
+ expect(elapsed < 10).toBe(true);
});
});
@@ -95,8 +95,8 @@ describe('Helpers', () => {
const result = await retry(fn);
- assertEquals(result, 'success');
- assertEquals(fn.calls.length, 1);
+ expect(result).toBe('success');
+ expect(fn.calls.length).toBe(1);
});
it('should retry on failure and eventually succeed', async () => {
@@ -113,8 +113,8 @@ describe('Helpers', () => {
{ maxAttempts: 3, initialDelay: 10 }
);
- assertEquals(result, 'success');
- assertEquals(attempts, 3);
+ expect(result).toBe('success');
+ expect(attempts).toBe(3);
});
it('should throw after max attempts', async () => {
@@ -132,7 +132,7 @@ describe('Helpers', () => {
'Always fails'
);
- assertEquals(attempts, 2);
+ expect(attempts).toBe(2);
});
it('should call onRetry callback', async () => {
@@ -150,9 +150,9 @@ describe('Helpers', () => {
{ maxAttempts: 2, initialDelay: 10, onRetry }
);
- assertEquals(onRetry.calls.length, 1);
- assertEquals(onRetry.calls[0].args[0], 1); // attempt number
- assertEquals(onRetry.calls[0].args[1].message, 'Retry'); // error
+ expect(onRetry.calls.length).toBe(1);
+ expect(onRetry.calls[0].args[0]).toBe(1); // attempt number
+ expect(onRetry.calls[0].args[1].message).toBe('Retry'); // error
});
it('should use exponential backoff', async () => {
@@ -181,8 +181,8 @@ describe('Helpers', () => {
{ maxAttempts: 3, initialDelay: 1, factor: 2 }
);
- assertEquals(result, 'success');
- assertEquals(attempts, 3);
+ expect(result).toBe('success');
+ expect(attempts).toBe(3);
});
});
@@ -196,12 +196,12 @@ describe('Helpers', () => {
debouncedFn();
// Should not call yet
- assertEquals(fn.calls.length, 0);
+ expect(fn.calls.length).toBe(0);
await delay(15); // Wait for debounce
// Should call once
- assertEquals(fn.calls.length, 1);
+ expect(fn.calls.length).toBe(1);
});
it('should reset timer on subsequent calls', async () => {
@@ -214,12 +214,12 @@ describe('Helpers', () => {
await delay(10);
// Should not call yet (timer was reset)
- assertEquals(fn.calls.length, 0);
+ expect(fn.calls.length).toBe(0);
await delay(25); // Wait for final debounce
// Should call now
- assertEquals(fn.calls.length, 1);
+ expect(fn.calls.length).toBe(1);
});
});
@@ -233,39 +233,39 @@ describe('Helpers', () => {
throttledFn();
// Should call immediately once
- assertEquals(fn.calls.length, 1);
+ expect(fn.calls.length).toBe(1);
await delay(15); // Wait for throttle
// Should call the last queued call
- assertEquals(fn.calls.length, 2);
+ expect(fn.calls.length).toBe(2);
});
});
describe('deepClone', () => {
it('should clone primitives', () => {
- assertEquals(deepClone(5), 5);
- assertEquals(deepClone('test'), 'test');
- assertEquals(deepClone(true), true);
- assertEquals(deepClone(null), null);
+ expect(deepClone(5)).toBe(5);
+ expect(deepClone('test')).toBe('test');
+ expect(deepClone(true)).toBe(true);
+ expect(deepClone(null)).toBe(null);
});
it('should clone dates', () => {
const date = new Date();
const cloned = deepClone(date);
- assertEquals(cloned.getTime(), date.getTime());
- assertEquals(cloned === date, false); // Different objects
+ expect(cloned.getTime()).toBe(date.getTime());
+ expect(cloned === date).toBe(false); // Different objects
});
it('should clone arrays deeply', () => {
const original = [1, [2, 3], { a: 4 }];
const cloned = deepClone(original);
- assertEquals(cloned, original);
- assertEquals(cloned === original, false);
- assertEquals(cloned[1] === original[1], false);
- assertEquals(cloned[2] === original[2], false);
+ expect(cloned).toBe(original);
+ expect(cloned === original).toBe(false);
+ expect(cloned[1] === original[1]).toBe(false);
+ expect(cloned[2] === original[2]).toBe(false);
});
it('should clone objects deeply', () => {
@@ -277,35 +277,35 @@ describe('Helpers', () => {
const cloned = deepClone(original);
- assertEquals(cloned.a, original.a);
- assertEquals(cloned.b.c, original.b.c);
- assertEquals(cloned.b.d, original.b.d);
- assertEquals(cloned.e.getTime(), original.e.getTime());
+ expect(cloned.a).toBe(original.a);
+ expect(cloned.b.c).toBe(original.b.c);
+ expect(cloned.b.d).toBe(original.b.d);
+ expect(cloned.e.getTime()).toBe(original.e.getTime());
// Different references
- assertEquals(cloned === original, false);
- assertEquals(cloned.b === original.b, false);
- assertEquals(cloned.b.d === original.b.d, false);
- assertEquals(cloned.e === original.e, false);
+ expect(cloned === original).toBe(false);
+ expect(cloned.b === original.b).toBe(false);
+ expect(cloned.b.d === original.b.d).toBe(false);
+ expect(cloned.e === original.e).toBe(false);
});
it('should clone Maps', () => {
const original = new Map([['a', 1], ['b', { c: 2 }]]);
const cloned = deepClone(original);
- assertEquals(cloned.get('a'), 1);
- assertEquals((cloned.get('b') as any).c, 2);
- assertEquals(cloned === original, false);
- assertEquals(cloned.get('b') === original.get('b'), false);
+ expect(cloned.get('a')).toBe(1);
+ expect((cloned.get('b') as any).c).toBe(2);
+ expect(cloned === original).toBe(false);
+ expect(cloned.get('b') === original.get('b')).toBe(false);
});
it('should clone Sets', () => {
const original = new Set([1, { a: 2 }, [3, 4]]);
const cloned = deepClone(original);
- assertEquals(cloned.size, original.size);
- assertEquals(cloned === original, false);
- assertEquals(cloned.has(1), true);
+ expect(cloned.size).toBe(original.size);
+ expect(cloned === original).toBe(false);
+ expect(cloned.has(1)).toBe(true);
});
});
@@ -329,7 +329,7 @@ describe('Helpers', () => {
const target = { a: 1 };
const result = deepMerge(target);
- assertEquals(result, { a: 1 });
+ expect(result).toBe({ a: 1 });
});
it('should not mutate target object', () => {
@@ -338,8 +338,8 @@ describe('Helpers', () => {
const result = deepMerge(target, source);
- assertEquals(target.b.d, undefined); // Target not mutated
- assertEquals(result.b.d, 3); // Result has merged value
+ expect(target.b.d).toBe(undefined); // Target not mutated
+ expect(result.b.d).toBe(3); // Result has merged value
});
});
@@ -361,8 +361,8 @@ describe('Helpers', () => {
emitter.on('test', handler);
emitter.emit('test', { message: 'hello' });
- assertEquals(handler.calls.length, 1);
- assertEquals(handler.calls[0].args[0], { message: 'hello' });
+ expect(handler.calls.length).toBe(1);
+ expect(handler.calls[0].args[0]).toBe({ message: 'hello' });
});
it('should handle multiple listeners', () => {
@@ -373,8 +373,8 @@ describe('Helpers', () => {
emitter.on('test', handler2);
emitter.emit('test', { message: 'hello' });
- assertEquals(handler1.calls.length, 1);
- assertEquals(handler2.calls.length, 1);
+ expect(handler1.calls.length).toBe(1);
+ expect(handler2.calls.length).toBe(1);
});
it('should support once listeners', () => {
@@ -384,7 +384,7 @@ describe('Helpers', () => {
emitter.emit('test', { message: 'hello' });
emitter.emit('test', { message: 'world' });
- assertEquals(handler.calls.length, 1);
+ expect(handler.calls.length).toBe(1);
});
it('should remove listeners', () => {
@@ -396,7 +396,7 @@ describe('Helpers', () => {
emitter.off('test', handler);
emitter.emit('test', { message: 'world' });
- assertEquals(handler.calls.length, 1);
+ expect(handler.calls.length).toBe(1);
});
it('should remove all listeners', () => {
@@ -409,38 +409,38 @@ describe('Helpers', () => {
emitter.removeAllListeners('test');
emitter.emit('test', { message: 'hello' });
- assertEquals(handler1.calls.length, 0);
- assertEquals(handler2.calls.length, 0);
+ expect(handler1.calls.length).toBe(0);
+ expect(handler2.calls.length).toBe(0);
});
});
describe('formatBytes', () => {
it('should format bytes correctly', () => {
- assertEquals(formatBytes(0), '0 Bytes');
- assertEquals(formatBytes(1024), '1 KB');
- assertEquals(formatBytes(1048576), '1 MB');
- assertEquals(formatBytes(1073741824), '1 GB');
- assertEquals(formatBytes(1099511627776), '1 TB');
+ expect(formatBytes(0)).toBe('0 Bytes');
+ expect(formatBytes(1024)).toBe('1 KB');
+ expect(formatBytes(1048576)).toBe('1 MB');
+ expect(formatBytes(1073741824)).toBe('1 GB');
+ expect(formatBytes(1099511627776)).toBe('1 TB');
});
it('should format with decimals', () => {
- assertEquals(formatBytes(1500), '1.46 KB');
- assertEquals(formatBytes(1500, 1), '1.5 KB');
- assertEquals(formatBytes(1500, 0), '1 KB');
+ expect(formatBytes(1500)).toBe('1.46 KB');
+ expect(formatBytes(1500).toBe(1), '1.5 KB');
+ expect(formatBytes(1500).toBe(0), '1 KB');
});
it('should handle negative values', () => {
- assertEquals(formatBytes(-1024), '-1 KB');
+ expect(formatBytes(-1024)).toBe('-1 KB');
});
});
describe('parseDuration', () => {
it('should parse different time units', () => {
- assertEquals(parseDuration('100ms'), 100);
- assertEquals(parseDuration('5s'), 5000);
- assertEquals(parseDuration('2m'), 120000);
- assertEquals(parseDuration('1h'), 3600000);
- assertEquals(parseDuration('1d'), 86400000);
+ expect(parseDuration('100ms')).toBe(100);
+ expect(parseDuration('5s')).toBe(5000);
+ expect(parseDuration('2m')).toBe(120000);
+ expect(parseDuration('1h')).toBe(3600000);
+ expect(parseDuration('1d')).toBe(86400000);
});
it('should throw on invalid format', () => {
@@ -466,15 +466,15 @@ describe('Helpers', () => {
describe('ensureArray', () => {
it('should convert single values to arrays', () => {
- assertEquals(ensureArray('test'), ['test']);
- assertEquals(ensureArray(5), [5]);
- assertEquals(ensureArray(null), [null]);
+ expect(ensureArray('test')).toBe(['test']);
+ expect(ensureArray(5)).toBe([5]);
+ expect(ensureArray(null)).toBe([null]);
});
it('should keep arrays as arrays', () => {
- assertEquals(ensureArray(['test']), ['test']);
- assertEquals(ensureArray([1, 2, 3]), [1, 2, 3]);
- assertEquals(ensureArray([]), []);
+ expect(ensureArray(['test'])).toBe(['test']);
+ expect(ensureArray([1).toBe(2, 3]), [1, 2, 3]);
+ expect(ensureArray([])).toBe([]);
});
});
@@ -498,7 +498,7 @@ describe('Helpers', () => {
it('should handle empty arrays', () => {
const grouped = groupBy([], (item: any) => item.type);
- assertEquals(grouped, {});
+ expect(grouped).toBe({});
});
it('should handle number keys', () => {
@@ -510,8 +510,8 @@ describe('Helpers', () => {
const grouped = groupBy(items, item => item.score);
- assertEquals(grouped[100].length, 2);
- assertEquals(grouped[90].length, 1);
+ expect(grouped[100].length).toBe(2);
+ expect(grouped[90].length).toBe(1);
});
});
@@ -523,7 +523,7 @@ describe('Helpers', () => {
deferred.resolve('success');
const result = await deferred.promise;
- assertEquals(result, 'success');
+ expect(result).toBe('success');
});
it('should handle rejection', async () => {
@@ -543,23 +543,23 @@ describe('Helpers', () => {
describe('safeParseJSON', () => {
it('should parse valid JSON', () => {
const result = safeParseJSON('{"key": "value"}');
- assertEquals(result, { key: 'value' });
+ expect(result).toBe({ key: 'value' });
});
it('should return undefined for invalid JSON', () => {
const result = safeParseJSON('invalid json');
- assertEquals(result, undefined);
+ expect(result).toBe(undefined);
});
it('should return fallback for invalid JSON', () => {
const result = safeParseJSON('invalid json', { default: true });
- assertEquals(result, { default: true });
+ expect(result).toBe({ default: true });
});
it('should handle complex objects', () => {
const obj = { a: 1, b: [2, 3], c: { d: 4 } };
const result = safeParseJSON(JSON.stringify(obj));
- assertEquals(result, obj);
+ expect(result).toBe(obj);
});
});
@@ -567,7 +567,7 @@ describe('Helpers', () => {
it('should resolve if promise completes in time', async () => {
const promise = Promise.resolve('success');
const result = await timeout(promise, 1000);
- assertEquals(result, 'success');
+ expect(result).toBe('success');
});
it('should reject if promise times out', async () => {
@@ -604,11 +604,11 @@ describe('Helpers', () => {
});
const result = await breaker.execute(() => Promise.resolve('success'));
- assertEquals(result, 'success');
+ expect(result).toBe('success');
const state = breaker.getState();
- assertEquals(state.state, 'closed');
- assertEquals(state.failureCount, 0);
+ expect(state.state).toBe('closed');
+ expect(state.failureCount).toBe(0);
});
it('should open after threshold failures', async () => {
@@ -626,8 +626,8 @@ describe('Helpers', () => {
}
const state = breaker.getState();
- assertEquals(state.state, 'open');
- assertEquals(state.failureCount, 3);
+ expect(state.state).toBe('open');
+ expect(state.failureCount).toBe(3);
});
it('should reject immediately when open', async () => {
@@ -666,15 +666,15 @@ describe('Helpers', () => {
} catch {}
}
- assertEquals(breaker.getState().state, 'open');
+ expect(breaker.getState().state).toBe('open');
// Wait for reset timeout
await delay(60);
// Should be half-open now
const result = await breaker.execute(() => Promise.resolve('success'));
- assertEquals(result, 'success');
- assertEquals(breaker.getState().state, 'closed');
+ expect(result).toBe('success');
+ expect(breaker.getState().state).toBe('closed');
});
it('should handle timeout errors', async () => {
@@ -703,14 +703,14 @@ describe('Helpers', () => {
await breaker.execute(() => Promise.reject(new Error('fail')));
} catch {}
- assertEquals(breaker.getState().failureCount, 1);
+ expect(breaker.getState().failureCount).toBe(1);
// Success should reset count
await breaker.execute(() => Promise.resolve('success'));
const state = breaker.getState();
- assertEquals(state.failureCount, 0);
- assertEquals(state.state, 'closed');
+ expect(state.failureCount).toBe(0);
+ expect(state.state).toBe('closed');
});
it('should allow manual reset', () => {
@@ -723,9 +723,9 @@ describe('Helpers', () => {
breaker.reset();
const state = breaker.getState();
- assertEquals(state.state, 'closed');
- assertEquals(state.failureCount, 0);
- assertEquals(state.lastFailureTime, 0);
+ expect(state.state).toBe('closed');
+ expect(state.failureCount).toBe(0);
+ expect(state.lastFailureTime).toBe(0);
});
});
});
\ No newline at end of file