# Testing Guide

**When to use:** Running and writing tests for StemeDB.

## Quick Start

```bash
# Run all tests
cargo test --workspace

# Run specific crate
cargo test -p stemedb-core

# Run specific test
cargo test test_assertion_round_trips

# Run with output
cargo test -- --nocapture
```

## Test Types

### Unit Tests (in `src/`)

```rust
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_entity_id_equality() {
        let a = EntityId("tesla".into());
        let b = EntityId("tesla".into());
        assert_eq!(a, b);
    }
}
```

### Integration Tests (in `tests/`)

```rust
// tests/integration.rs
use stemedb_core::*;

#[test]
fn test_full_write_read_cycle() {
    let store = MemoryStore::new();
    let assertion = Assertion::new(/* ... */);
    store.put(&assertion)?;
    let loaded = store.get(&assertion.hash())?;
    assert_eq!(assertion, loaded);
}
```

### Property Tests

Use `proptest` for invariant testing:

```rust
use proptest::prelude::*;

proptest! {
    #[test]
    fn hash_is_deterministic(subject in ".*", predicate in ".*") {
        let a1 = Assertion::new(&subject, &predicate, /* ... */);
        let a2 = Assertion::new(&subject, &predicate, /* ... */);
        assert_eq!(a1.hash(), a2.hash());
    }
}
```

## What to Test

### High Priority (Always Test)

- Crash recovery: write -> crash -> restart -> read
- Data integrity: serialization round-trips
- Hash determinism: same input = same hash
- Error paths: invalid signatures, missing data

### Medium Priority

- Index consistency: write assertion -> index updated
- Lens correctness: resolve returns expected winner

### Skip

- Trivial getters
- Compiler-enforced type safety
- Simple delegations

## Test Fixtures

Create shared fixtures in `tests/common/mod.rs`:

```rust
// tests/common/mod.rs
pub fn test_assertion() -> Assertion {
    Assertion {
        subject: EntityId("test_subject".into()),
        predicate: RelationId("test_predicate".into()),
        // ...
    }
}

pub fn test_agent() -> AgentId {
    AgentId([0u8; 32])
}
```

Use in tests:
```rust
mod common;

#[test]
fn test_something() {
    let assertion = common::test_assertion();
    // ...
}
```

## Coverage

Check coverage with `cargo-llvm-cov`:

```bash
cargo install cargo-llvm-cov
cargo llvm-cov --workspace --html
open target/llvm-cov/html/index.html
```

## Related

- [Setup Guide](./setup.md)
- [Rust Guidelines](../backend/rust-guidelines.md)
- [UAT Reports](./uat-reports.md)
