# Design Document: Test Coverage Improvement

## Overview

This document describes the design for increasing test coverage of the TypeScript RBAC library to a minimum of 95% across all metrics. The primary focus is on covering untested branches in the `helpers.ts`, `middlewares/*`, and `rbac.ts` files.

The strategy involves:
1. Identifying uncovered branches through the lcov.info report
2. Creating specific unit tests for each uncovered branch
3. Focusing on edge cases, error paths, and configuration scenarios
4. Ensuring all conditional paths are exercised

## Architecture

The test architecture will follow the existing project pattern:

```
test/
├── helpers.spec.ts          (expand existing tests)
├── middlewares.spec.ts      (expand existing tests)
└── rbac.spec.ts            (expand existing tests)
```

### Focus Areas

**helpers.ts (85.33% statements, 78.08% branches)**
- `supportsColor` function: uncovered environment detection branches
- Error handling in color detection
- Environment variable scenarios (FORCE_COLOR, NO_COLOR, CI)

**middlewares/* (89.79% statements, 66.66% branches)**
- Custom options (getRole, getParams, onDenied)
- Error handling in Express and Nest middlewares
- Scenarios where custom callbacks are provided

**rbac.ts (96.15% statements, 81.15% branches)**
- Logger undefined in config
- Pattern cache hits
- Non-existent roles
- Logging disabled

## Components and Interfaces

### Test Utilities

No new components are needed. We will use existing test tools:
- Jest for test execution
- Jest mocks to simulate behaviors
- Jest spies to verify function calls

### Environment Mocking

To test `supportsColor`, we need to mock environment variables and `process.stdout`:

```typescript
// Example environment mock
const originalEnv = process.env;
const originalStdout = process.stdout;

beforeEach(() => {
  process.env = { ...originalEnv };
  // Mock stdout as needed
});

afterEach(() => {
  process.env = originalEnv;
  // Restore stdout
});
```

## Data Models

No new data models are required. Tests will use existing RBAC library types.

## Correctness Properties

*A property is a characteristic or behavior that should hold true across all valid executions of a system—essentially, a formal statement about what the system should do. Properties serve as the bridge between human-readable specifications and machine-verifiable correctness guarantees.*

### Property Reflection

Analyzing properties identified in prework:

**Middleware Properties:**
- 2.2, 2.3, 2.4 can be combined into a single property about "custom options work correctly"
- Each middleware (Express, Nest, Fastify) should have consistent behavior

**RBAC Properties:**
- 3.3 and 3.4 are independent properties and should be kept separate
- 3.5 about cache is a performance/optimization property

After reflection, we'll keep properties separate as each validates a different aspect of behavior.

### Property 1: Middleware Custom Options

*For any* middleware (Express, Nest, Fastify) and any set of custom options (getRole, getParams, onDenied), when options are provided, the middleware should use the custom functions instead of default values.

**Validates: Requirements 2.2, 2.3, 2.4**

### Property 2: RBAC Logging Disabled

*For any* role and operation, when enableLogger is false, no logging functions should be executed.

**Validates: Requirements 3.3**

### Property 3: RBAC Non-existent Role

*For any* non-existent role and any operation, RBAC should return false without throwing errors or exceptions.

**Validates: Requirements 3.4**

### Property 4: RBAC Pattern Cache Reuse

*For any* pattern that has already been evaluated, when the same pattern is checked again, RBAC should reuse the cached result without re-executing the matching logic.

**Validates: Requirements 3.5**

## Error Handling

### Error Testing Strategy

1. **supportsColor Error Handling**
   - Test when `process.env` throws exception
   - Test when `process.stdout` is undefined or null
   - Verify fallback returns false

2. **Middleware Error Handling**
   - Test when `rbac.can()` throws exception
   - Verify Express/Nest middlewares call `next(err)`
   - Verify Fastify middleware doesn't propagate unhandled error

3. **RBAC Error Handling**
   - Test when `when` functions throw exceptions
   - Verify errors are caught and return false
   - Test invalid regex patterns

## Testing Strategy

### Dual Testing Approach

This project will use a dual testing approach:

**Unit Tests**: Will focus on:
- Specific examples of each uncovered branch
- Edge cases identified in coverage report
- Error and exception scenarios
- Specific environment configurations

**Property Tests**: Will focus on:
- Universal behaviors that should work for any valid input
- Validation that custom options work consistently
- Verification that caching works correctly
- Guarantee that logging can be disabled

### Property-Based Testing Configuration

- **Library**: fast-check (already available in the project)
- **Iterations**: Minimum 100 iterations per property test
- **Tagging**: Each property test will be marked with a comment:
  ```typescript
  // Feature: test-coverage-improvement, Property 1: Middleware Custom Options
  ```

### Test Organization

Tests will be organized by source file:

**test/helpers.spec.ts**
- Add tests for uncovered branches in `supportsColor`
- Add tests for error scenarios
- Add tests for different environment configurations

**test/middlewares.spec.ts**
- Add tests for custom options (getRole, getParams, onDenied)
- Add tests for error handling
- Add tests for each middleware type

**test/rbac.spec.ts**
- Add tests for undefined logger
- Add tests for pattern cache
- Add tests for non-existent roles with logging disabled

### Coverage Goals

| Metric | Current | Target |
|--------|---------|--------|
| Statements | 92.51% | ≥ 95% |
| Branches | 79.27% | ≥ 95% |
| Functions | 100% | 100% |
| Lines | 92.99% | ≥ 95% |

### Specific Branches to Cover

**helpers.ts (uncovered lines: 45-82)**
- Lines 45-48: NO_COLOR not defined
- Lines 52-62: process.stdout checks
- Lines 64-73: CI environment checks
- Lines 77-82: Error handling

**middlewares/express.ts (uncovered line: 23)**
- Line 23: Error caught and passed to next()

**middlewares/nest.ts (uncovered line: 24)**
- Line 24: Error caught and passed to next()

**middlewares/fastify.ts (uncovered branches)**
- onDenied callback when provided
- Custom getRole and getParams

**rbac.ts (uncovered branches)**
- Logger undefined (line 50)
- enableLogger false paths
- Pattern cache hits
- Non-existent roles

### Test Execution

```bash
# Run tests with coverage
npm test -- --coverage

# View coverage report
open coverage/lcov-report/index.html
```

### Success Criteria

Tests will be considered successful when:
1. All coverage metrics reach ≥ 95%
2. All tests pass without failures
3. No critical branches remain uncovered
4. Coverage report shows green areas for main files
