Test patterns

From d-o-hub/rust-self-learning-memory · View interactive version

Test patterns is an AI agent skill from the GitHub repository d-o-hub/rust-self-learning-memory. Unified testing patterns for Rust: unit testing quality, episodic memory operations, and async/tokio code. Use when writing tests, reviewing test code, or diagnosing test failures.

How to use this skill

Skill file

Test Patterns for Rust Self-Learning Memory

Unified testing patterns covering unit testing quality, episodic memory domain tests, and async/tokio patterns.

Naming Convention

test_<function>_<scenario>_<expected_behavior> (e.g., test_withdraw_valid_amount_decreases_balance)

AAA Pattern

#[tokio::test]
async fn test_save_episode() -> anyhow::Result<()> {
    let memory = create_test_memory().await;    // Arrange
    memory.save_episode(&episode).await?;       // Act
    assert_eq!(retrieved.task_description, "Test");  // Assert
    Ok(())
}

Core Principles

Anti-Patterns

| Bad | Fix |

|-----|-----|

| Testing std library | Test your code |

| No assertions | Verify outcomes |

| Multiple behaviors | Split tests |

| .unwrap() chains | Use Result<()> with ? |

Episodic Memory Testing

State: Created -> InProgress -> Completed/Failed

#[tokio::test]
async fn test_episode_lifecycle() {
    let id = memory.start_episode("Test", ctx, TaskType::CodeGen).await;
    memory.complete_episode(id.clone(), TaskOutcome::Success, None).await?;
    assert_eq!(memory.get_episode(&id).await?.outcome, TaskOutcome::Success);
}

Async/Tokio Patterns

#[tokio::test]                                       // Basic async
#[tokio::test(start_paused = true)]                  // Time control (no real wait)
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]  // Concurrent

Mock Storage

pub struct MockTursoStorage { episodes: Arc<Mutex<Vec<Episode>>> }
#[async_trait]
impl StorageBackend for MockTursoStorage {
    async fn create_episode(&self, episode: &Episode) -> Result<()> { /* ... */ }
}

Async Pitfalls

| Bad | Good |

|-----|------|

| std::thread::sleep() | tokio::time::sleep().await |

| Blocking runtime | spawn_blocking for sync |

Fixture Guardrails

assertion assumes. A "newer" fixture whose end_time precedes the "older"

fixture's start_time measures the inverse comparison and fails on correct

code — treat a failing assertion on fresh code as a fixture hypothesis first

(LESSON-045).

supertrait); an empty impl is correct when it advertises no optional capability.

function: with only the function gated, the file's use lines, helper structs

and impl blocks become unused-import and dead-code errors, and because

scripts/code-quality.sh:158 runs cargo clippy --workspace --tests on

default features, one ungated import in one test file blocks clippy for

every open PR (LESSON-015). Use the same or broader cfg predicate as the most

restrictive consumer. Do not "fix" this by adding an --all-features clippy

run: this repo deliberately avoids --all-features (see the comments at

.github/workflows/storage-matrix.yml:36,41,45), so the gate stays the

default-features one and the code must satisfy it.

Pre-Commit Checklist

Success Metrics

Deploy without manual testing | Failures pinpoint exact problems | Tests run in milliseconds

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.