跳转到主要内容

测试

运行测试

运行完整测试套件:
cargo test
或测试单个 crate:
cargo test -p memorose-core
cargo test -p memorose-server
cargo test -p memorose-gateway
cargo test -p memorose-common
按名称运行特定测试:
cargo test -p memorose-core -- test_ingest_and_retrieve

测试组织

单元测试(Unit Tests)

嵌入在被测代码旁边,使用 #[cfg(test)] 模块。大多数存储和引擎逻辑都有就近的单元测试。 关键测试文件:
  • crates/memorose-core/src/storage/tests.rs — 全面的存储后端测试
  • engine/llm/graph/ 中的模块级 #[cfg(test)]

集成测试(Integration Tests)

位于 crates/memorose-core/tests/integration.rs。这些测试覆盖完整的 ingest → retrieve → mark-processed 流程。

测试模式

异步测试

所有 I/O 密集型测试使用 tokio::test
#[tokio::test]
async fn test_ingest_and_retrieve() {
    // ...
}

临时目录

需要存储的测试使用 tempfile 创建隔离的数据目录:
use tempfile::TempDir;

#[tokio::test]
async fn test_storage() {
    let tmp = TempDir::new().unwrap();
    let config = Config {
        data_dir: tmp.path().to_path_buf(),
        ..Default::default()
    };
    // 存储完全隔离,drop 时自动清理
}

Mock LLM

涉及 LLM 调用的测试使用 mock 模式以避免真实 API 调用:
# config.toml
[development]
use_mock_llm = true
Mock 提供商返回确定性响应,使测试无需 API 密钥即可复现。

HTTP Mock

调用外部服务的测试使用 wiremock 进行请求拦截:
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

#[tokio::test]
async fn test_external_call() {
    let mock_server = MockServer::start().await;
    Mock::given(method("POST"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({...})))
        .mount(&mock_server)
        .await;
    // 将客户端指向 mock_server.uri()
}

编写新测试

约定

  • 将单元测试放在被测文件底部的 #[cfg(test)] 模块中
  • 将集成测试放在 crates/memorose-core/tests/ 目录下
  • 使用描述性测试名称:test_hybrid_search_with_agent_filter,而非 test_search_2
  • 清理所有临时资源——优先使用 TempDir 而非手动目录管理
  • 避免真实 LLM 调用——除非你专门测试 LLM 集成,否则使用 mock 模式

典型集成测试流程

#[tokio::test]
async fn test_basic_flow() {
    // 1. 使用临时存储创建引擎
    let tmp = TempDir::new().unwrap();
    let engine = create_test_engine(tmp.path()).await;

    // 2. 摄入事件
    engine.ingest_event(user_id, stream_id, event).await.unwrap();

    // 3. 检索并验证
    let results = engine.search_hybrid(query, app_id, None).await.unwrap();
    assert!(!results.is_empty());
}

Dashboard 测试

对于 Next.js 仪表盘:
cd dashboard
pnpm test       # 运行测试
pnpm lint       # 代码检查
pnpm type-check # TypeScript 类型检查