# Testing Guide

## Overview

The IAVL-TS test suite supports running tests against two different database backends:
- **MemDB**: In-memory database (default) - Fast, no disk I/O
- **CrossKV**: Persistent database using @cross/kv - Tests real-world storage behavior

This allows us to verify that our implementation works correctly with both database types and catches any implementation-specific issues.

## Running Tests

### Quick Start

```bash
# Run tests with default MemDB (fastest)
pnpm test

# Run tests with MemDB explicitly
pnpm test:memdb

# Run tests with CrossKV
pnpm test:crosskv

# Run tests with both databases sequentially
pnpm test:both
```

### Manual Environment Variable Control

```bash
# Using MemDB
TEST_DB_TYPE=memory pnpm test

# Using CrossKV
TEST_DB_TYPE=crosskv pnpm test

# Default behavior (no env var = MemDB)
pnpm test
```

### Watch Mode and Coverage

```bash
# Watch mode with MemDB
pnpm test:watch

# Watch mode with CrossKV
TEST_DB_TYPE=crosskv pnpm test:watch

# Coverage with specific database
TEST_DB_TYPE=crosskv pnpm test:coverage
```

## Writing Tests

### Using the Test Database Factory

The recommended approach is to use the `createTestDb()` factory function which automatically creates the appropriate database type based on the `TEST_DB_TYPE` environment variable.

#### Basic Pattern

```typescript
import { afterEach, beforeEach, describe, it } from "vitest";
import { createTestDb, type TestDbContext } from "./db/test-db-factory.js";

describe("MyComponent", () => {
  let ctx: TestDbContext;

  beforeEach(async () => {
    ctx = await createTestDb();
  });

  afterEach(async () => {
    await ctx.cleanup();
  });

  it("should perform database operations", async () => {
    const key = new Uint8Array([1, 2, 3]);
    const value = new Uint8Array([4, 5, 6]);

    await ctx.db.set(key, value);
    const result = await ctx.db.get(key);

    expect(result).toEqual(value);
  });
});
```

#### With NodeDB Wrapper

```typescript
import { afterEach, beforeEach, describe, it } from "vitest";
import { createTestDb, type TestDbContext } from "./db/test-db-factory.js";
import { NodeDB } from "./storage/node-db.js";
import { DEFAULT_OPTIONS } from "./types/options.js";

describe("Tree Operations", () => {
  let ctx: TestDbContext;
  let nodeDB: NodeDB;

  beforeEach(async () => {
    ctx = await createTestDb();
    nodeDB = new NodeDB(ctx.db, 1000, DEFAULT_OPTIONS);
    await nodeDB.initialize();
  });

  afterEach(async () => {
    await ctx.cleanup();
  });

  it("should work with trees", async () => {
    // ... test code using nodeDB
  });
});
```

### Handling Iterator Differences

CrossKV iterators require calling `waitReady()` before use, while MemDB iterators are synchronously ready. The factory handles this by exposing utility functions:

```typescript
import { isUsingCrossKv } from "./db/test-db-factory.js";

it("should iterate over keys", async () => {
  // Set up data
  await ctx.db.set(new Uint8Array([1]), new Uint8Array([10]));
  await ctx.db.set(new Uint8Array([2]), new Uint8Array([20]));

  const iter = ctx.db.iterator();

  // Wait for iterator if using CrossKV
  if ("waitReady" in iter) {
    await (iter as any).waitReady();
  }

  // Or conditionally based on database type
  if (isUsingCrossKv()) {
    await (iter as any).waitReady();
  }

  const keys: Uint8Array[] = [];
  for (; iter.valid(); iter.next()) {
    keys.push(iter.key());
  }

  await iter.close();

  expect(keys.length).toBe(2);
});
```

### Database-Specific Test Logic

Sometimes you may need conditional logic based on the database type:

```typescript
import { getTestDbType, isUsingMemDb, isUsingCrossKv } from "./db/test-db-factory.js";

it("should handle database-specific behavior", async () => {
  const dbType = getTestDbType(); // "memory" | "crosskv"

  if (isUsingMemDb()) {
    // MemDB-specific expectations
  }

  if (isUsingCrossKv()) {
    // CrossKV-specific expectations
  }
});
```

## Migration Status

**Current Status**: The test suite has been partially migrated to use the database factory.

- ✅ **46 test files migrated** to use `createTestDb()`
- ✅ **1024 tests pass** with MemDB (TEST_DB_TYPE=memory)
- ⚠️ **Inline database creation pattern**: Many tests create databases inline within test functions rather than in setup hooks. This pattern works fine with MemDB but may have limitations with CrossKV due to cleanup requirements.

### Recommended Pattern for New Tests

For new tests or when refactoring existing ones, use the setup hook pattern:

```typescript
describe("MyComponent", () => {
  let ctx: TestDbContext;

  beforeEach(async () => {
    ctx = await createTestDb();
  });

  afterEach(async () => {
    await ctx.cleanup();
  });

  it("should work", async () => {
    await ctx.db.set(key, value);
    // ...
  });
});
```

## Migration Guide for Existing Tests

If you have existing tests using MemDB directly, here's how to migrate:

### Before (Direct MemDB)

```typescript
import { MemDB } from "./db/mem-db.js";

describe("MyTest", () => {
  let db: MemDB;

  beforeEach(() => {
    db = new MemDB();
  });

  it("should work", async () => {
    await db.set(key, value);
    // ...
  });
});
```

### After (Test DB Factory)

```typescript
import { createTestDb, type TestDbContext } from "./db/test-db-factory.js";

describe("MyTest", () => {
  let ctx: TestDbContext;

  beforeEach(async () => {
    ctx = await createTestDb();
  });

  afterEach(async () => {
    await ctx.cleanup();
  });

  it("should work", async () => {
    await ctx.db.set(key, value);
    // ...
  });
});
```

**Key changes:**
1. Replace `MemDB` import with `createTestDb` and `TestDbContext`
2. Change `db` to `ctx.db`
3. Make `beforeEach` async and await `createTestDb()`
4. Add `afterEach` hook with `await ctx.cleanup()`

## Database Implementations

### MemDB (Default)

**Pros:**
- ✅ Extremely fast (in-memory operations)
- ✅ No disk I/O
- ✅ Automatic cleanup
- ✅ No external dependencies
- ✅ Ideal for CI/CD pipelines

**Cons:**
- ❌ Doesn't catch file system issues
- ❌ Not representative of production behavior
- ❌ Memory-only testing

**Use when:**
- Running tests locally during development
- Running CI/CD pipelines where speed matters
- Unit testing pure logic without storage concerns

### CrossKV

**Pros:**
- ✅ Tests real persistent storage
- ✅ Catches file system issues
- ✅ Production-like behavior
- ✅ Tests async I/O patterns

**Cons:**
- ❌ Slower than MemDB
- ❌ Creates temporary files
- ❌ Requires cleanup
- ❌ May have platform-specific behavior

**Use when:**
- Validating production readiness
- Testing storage-related features
- Debugging file system issues
- Final validation before release

## Best Practices

1. **Default to MemDB for development**: Use `pnpm test` during development for fast feedback
2. **Use CrossKV before releases**: Run `pnpm test:crosskv` before major releases
3. **CI/CD runs both**: Configure CI to run `pnpm test:both` to catch issues with either backend
4. **Always cleanup**: Use the `afterEach` hook with `ctx.cleanup()` to prevent resource leaks
5. **Avoid hardcoding database types**: Use the factory pattern to allow flexible testing
6. **Handle iterator differences**: Always check for `waitReady()` when using iterators

## Troubleshooting

### Tests hang with CrossKV

**Problem**: Tests hang indefinitely when using CrossKV.

**Solution**: Ensure you're calling `await (iter as any).waitReady()` on iterators before using them.

```typescript
const iter = ctx.db.iterator();
if ("waitReady" in iter) {
  await (iter as any).waitReady();
}
```

### File system errors with CrossKV

**Problem**: `ENOENT` or permission errors when running CrossKV tests.

**Solution**: Ensure `ctx.cleanup()` is called in `afterEach`:

```typescript
afterEach(async () => {
  await ctx.cleanup();
});
```

### Tests pass with MemDB but fail with CrossKV

**Problem**: Implementation assumes synchronous behavior.

**Solution**: Review async/await usage and ensure all database operations are properly awaited.

### Leftover database files

**Problem**: Test database files accumulating in the project root.

**Solution**: The factory automatically names files with timestamps. Ensure `ctx.cleanup()` is being called. You can manually clean with:

```bash
rm -f test-db-*.db
```

## Performance Comparison

Approximate test suite runtime (1000+ tests):

| Database | Runtime | Use Case |
|----------|---------|----------|
| MemDB    | ~30s    | Fast iteration during development |
| CrossKV  | ~2-3min | Validation before releases |

## CI/CD Integration

### GitHub Actions Example

```yaml
name: Tests

on: [push, pull_request]

jobs:
  test-memdb:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: pnpm/action-setup@v2
      - run: pnpm install
      - run: pnpm test:memdb

  test-crosskv:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: pnpm/action-setup@v2
      - run: pnpm install
      - run: pnpm test:crosskv
```

### Running Both in Sequence

For comprehensive validation:

```bash
pnpm test:both
```

This runs the full suite with MemDB first, then with CrossKV. If either fails, the command exits with an error code.

## Summary

The test database factory provides a flexible way to validate our implementation against both in-memory and persistent storage backends. Use MemDB for speed during development and CrossKV for production validation. Always use the factory pattern (`createTestDb()`) in new tests to ensure compatibility with both backends.
