# Testing Guide for Mailcow MCP Server
This guide explains the testing infrastructure and how to use code coverage effectively.
## π Test Structure
```
tests/
βββ unit/ # Unit tests (fast, isolated)
β βββ auth/ # Auth system tests (4 files, 70% coverage)
β βββ utils/ # Utility tests (8 files, 77% coverage)
βββ integration/ # Integration tests (slower, end-to-end)
βββ server-startup.test.js # Full server startup test
```
## π§ͺ Running Tests
### Basic Commands
```bash
# Run all unit tests
npm test
# or specifically
npm run test:unit
# Run integration tests
npm run test:integration
# Run both unit and integration tests
npm run test:all
# Generate coverage report
npm run test:coverage
# Generate coverage report AND open in browser π
npm run test:coverage:open
# Just open existing coverage report
npm run coverage:open
```
### Test Types
**Unit Tests** (Fast, ~10s):
- β
**Auth module**: 70% coverage, 162 test cases
- β
**Utils module**: 77% coverage, comprehensive validation
- β **API module**: 0% coverage (needs implementation)
- β **Tools module**: 0% coverage (needs implementation)
- β **Config module**: 0% coverage (needs implementation)
**Integration Tests** (Slower, ~3s):
- β
**Server startup**: Tests full MCP server initialization and protocol response
- β **Tool execution**: Not implemented yet
- β **API integration**: Not implemented yet
## π Code Coverage System
### What is the `coverage/` folder?
The `coverage/` folder contains detailed reports about which parts of your code are tested:
```
coverage/
βββ index.html # π Main coverage dashboard (open in browser)
βββ lcov.info # π Machine-readable coverage data
βββ lcov-report/ # π Detailed HTML reports by file
β βββ auth/ # Auth module coverage breakdown
β βββ utils/ # Utils module coverage breakdown
β βββ api/ # API module coverage (0% - needs work!)
β βββ tools/ # Tools module coverage (0% - needs work!)
βββ [other files] # Supporting files (CSS, JS, etc.)
```
### π How to Use Coverage Reports
#### 1. **View Overall Coverage**
```bash
npm run test:coverage
```
**Current Status**: 18.55% overall
- **π’ Auth**: 70.16% (excellent!)
- **π’ Utils**: 77.16% (excellent!)
- **π΄ API**: 0% (critical gap)
- **π΄ Tools**: 0% (critical gap)
- **π΄ Config**: 0% (needs basic tests)
#### 2. **Interactive HTML Reports**
**Quick Access**: `npm run coverage:open` π
Open `coverage/index.html` in your browser for:
- **π Visual coverage dashboard** with sortable tables
- **π― File-by-file breakdown** - click any file to see detailed coverage
- **π Line-by-line analysis** - see exactly which lines are tested (green) vs untested (red)
- **π Branch coverage** - see which code paths are exercised
#### 3. **Understanding Coverage Metrics**
**Statements**: % of executable code lines run during tests
**Branches**: % of if/else, switch, ternary conditions tested
**Functions**: % of functions called during tests
**Lines**: % of code lines executed (excluding comments/whitespace)
### π― Coverage Goals
**Target Coverage Levels**:
- **Critical modules** (auth, API client): >80%
- **Utility modules**: >70%
- **Tool implementations**: >60%
- **Overall project**: >50%
**Current Priority**:
1. **π¨ API Client tests** (currently 0%) - critical for reliability
2. **π¨ Tool registry tests** (currently 0%) - core functionality
3. **β οΈ Config validation tests** (currently 0%) - important for stability
### π Finding What to Test
**Use coverage reports to identify**:
1. **Red lines** in HTML reports = untested code paths
2. **Low function coverage** = functions never called in tests
3. **Low branch coverage** = missing error cases or edge conditions
**Example workflow**:
```bash
# 1. Run coverage
npm run test:coverage
# 2. Open coverage/index.html in browser
# 3. Navigate to src/api/client.ts.html
# 4. Look for red highlighted lines
# 5. Write tests to cover those code paths
# 6. Re-run coverage to verify improvement
```
## π Writing New Tests
### Unit Test Template
```typescript
// tests/unit/api/client.test.ts
import { APIClient } from '../../../src/api/client';
describe('APIClient', () => {
let client: APIClient;
beforeEach(() => {
client = new APIClient({
url: 'https://test.example.com',
key: 'test-api-key-with-32-characters',
accessType: 'read-only'
});
});
it('should initialize with correct config', () => {
expect(client).toBeDefined();
// Add your assertions
});
it('should handle API errors gracefully', async () => {
// Test error scenarios
});
});
```
### Integration Test Template
```javascript
// tests/integration/api-integration.test.js
const { spawn } = require('child_process');
// Set up test environment
process.env.MAILCOW_API_URL = 'https://test.example.com';
process.env.MAILCOW_API_KEY = 'test-key-32-characters-long';
// Test full end-to-end functionality
```
## π― Testing Best Practices
### 1. **Test the Critical Path First**
- API client HTTP operations
- Authentication validation
- Tool execution workflows
- Error handling
### 2. **Mock External Dependencies**
```typescript
// Use existing MockLogger for consistent testing
import { MockLogger } from '../../../src/utils/mocks';
const logger = new MockLogger();
// ... run code that logs
expect(logger.getLogs()).toHaveLength(2);
```
### 3. **Test Both Success and Failure Cases**
```typescript
it('should handle valid API key', async () => {
const result = await auth.validateAPIKey('a'.repeat(32));
expect(result.success).toBe(true);
});
it('should reject invalid API key', async () => {
const result = await auth.validateAPIKey('short');
expect(result.success).toBe(false);
expect(result.error?.code).toBe('INVALID_API_KEY');
});
```
### 4. **Use Coverage to Guide Testing**
- Aim for >80% coverage on critical modules
- Focus on untested branches (error cases)
- Don't chase 100% coverage - focus on important code paths
## π Current Test Status Summary
| Module | Coverage | Priority | Status |
|--------|----------|----------|--------|
| **Auth** | 70% | High | β
Well tested |
| **Utils** | 77% | High | β
Well tested |
| **API Client** | 0% | Critical | π¨ Needs immediate attention |
| **Tools** | 0% | Critical | π¨ Needs immediate attention |
| **Config** | 0% | Medium | β οΈ Needs basic tests |
| **Types** | 71% | Low | β
Adequate |
**Next Steps**:
1. Add API client tests with HTTP mocking
2. Add tool registry and execution tests
3. Add configuration validation tests
4. Add end-to-end integration tests
The testing foundation is excellent - now we need to extend it to cover the core application logic!