Now I have a comprehensive picture. Here is the complete analysis:
AgentLog Test Infrastructure -- Complete Analysis
1. Test Files Inventory
The project has 3 test files total across 2 packages:
| File | Package | Lines | Purpose |
|---|
/Users/hobo/Projects/AgentLog/packages/backend/test/integration.test.ts | @agentlog/backend | 765 | Full backend API integration tests |
/Users/hobo/Projects/AgentLog/packages/vscode-extension/test/fetchInterception.test.ts | agentlog-vscode | 1246 | Fetch interception logic unit tests |
/Users/hobo/Projects/AgentLog/packages/vscode-extension/test/smoke-fetch.mts | agentlog-vscode | 873 | Manual smoke test for fetch monkey-patching |
There are no *.spec.ts files, no __tests__ directories, and no test files in the @agentlog/shared package.
2. Test Framework / Runner
The project uses the Node.js native test runner (node:test + node:assert/strict) exclusively. There is:
- No Jest -- no
jest.config.*, no @jest imports
- No Vitest -- no
vitest.config.*, no vitest imports
- No Mocha -- no
.mocharc*, no mocha imports
Both formal test files import from:
import { describe, it, before, after, beforeEach, afterEach } from "node:test";
import assert from "node:assert/strict";
Tests are executed via tsx (TypeScript executor) + the native --test flag:
| Script | Command |
|---|
packages/backend pnpm test | node --import tsx --test test/integration.test.ts |
packages/vscode-extension pnpm test:fetch | node --import tsx --test test/fetchInterception.test.ts |
The smoke test (smoke-fetch.mts) is a standalone script (not using node:test), run manually with npx tsx or node --experimental-vm-modules. It uses a custom check() function with colored console output and manual pass/fail counting.
There is no root-level test script in the workspace package.json.
3. Backend Integration Test -- Detailed Breakdown
File: /Users/hobo/Projects/AgentLog/packages/backend/test/integration.test.ts
Architecture
The test uses a factory pattern to spin up an isolated Fastify instance per test suite:
async function buildApp(): Promise<FastifyInstance> {
const app = Fastify({ logger: false });
// registers cors, health endpoint, /api meta endpoint,
// then the three route modules: sessions, commits, export
await app.listen({ port: 0, host: "127.0.0.1" }); // random available port
return app;
}
Key design decisions:
port: 0 -- each suite gets a random available port, avoiding conflicts
logger: false -- suppresses Fastify logs during testing
- Each suite calls
buildApp() in before() and app.close() + closeDatabase() in after()
HTTP Request Helper
A lightweight req<T>() helper wraps globalThis.fetch (Node 18+ built-in) to make typed HTTP requests against the running Fastify instance:
async function req<T>(app, method, path, body?): Promise<{ status: number; body: T }>
It uses a baseUrl(app) helper that reads the dynamically assigned port from app.server.address().
Test Suites (4 total, ~40 test cases)
- Health Check (3 tests) --
GET /health, GET /api, GET /nonexistent (404)
- Session CRUD (14 tests) -- create, validate required fields (400), get by ID, get nonexistent (404), paginated list, keyword filter, workspacePath filter, PATCH tags/note/commit, DELETE, stats, unbound sessions
- Commit Binding (7 tests) -- batch bind, verify session updates, GET commit by hash, short hash prefix matching, nonexistent hash (404), list with pagination, unbind single session, unbind already-unbound (400), bind nonexistent session (404)
- Export (10 tests) -- format listing, JSONL export, Chinese weekly report (markdown), English weekly report, PR description, CSV, workspace filter, date range filter, invalid date (400), invalid format (400), preview with truncation
Shared Test Fixture
A single SAMPLE_SESSION constant provides reusable test data:
const SAMPLE_SESSION = {
provider: "deepseek",
model: "deepseek-r1",
source: "cline",
workspacePath: "/tmp/test-project",
prompt: "帮我重构 getUserById 函数,使其支持缓存",
reasoning: "<think>用户希望在 getUserById 中加入缓存层……</think>",
response: "好的,以下是重构后的 getUserById 函数...",
affectedFiles: ["src/user/service.ts", "src/user/cache.ts"],
durationMs: 3200,
tags: ["重构", "缓存"],
note: "这次 AI 建议使用 Map,性能不错",
};
4. Test Utilities and Fixtures
Backend (integration.test.ts)
buildApp() -- factory that creates and starts a fully configured Fastify instance
baseUrl(app) -- extracts the random port from a running server
req<T>(app, method, path, body?) -- generic typed HTTP request helper using native fetch
SAMPLE_SESSION -- shared session fixture object
VS Code Extension (fetchInterception.test.ts)
makeCompletionResponse(opts) -- builds a mock OpenAI-compatible JSON response string
makeSSEText(deltas) -- builds mock Server-Sent Events (SSE) text from an array of delta objects
makeSSEStream(sseText) -- wraps SSE text in a ReadableStream<Uint8Array>
drainStream(stream) -- fully reads a ReadableStream to string
SAMPLE_REQUEST_BODY -- a mock chat completion request body
- URL constants --
DEEPSEEK_URL, OPENAI_URL, QWEN_URL, KIMI_URL
FetchInterceptor class -- a self-contained re-implementation of the production HttpApiInterceptor's fetch-patching logic (inlined because the real module depends on vscode which is unavailable in Node)
- Inlined helper functions:
parseStreamChunk(), inferSource(), extractPrompt(), extractReasoning()
Smoke Test (smoke-fetch.mts)
MiniFetchInterceptor class -- another minimal fetch interceptor re-implementation
makeJsonResponseBody(), makeSSEData(), createMockStream(), readStreamFully() -- similar mock helpers
check(label, ok, detail?) -- custom assertion function with colored terminal output
delay(ms) -- simple Promise-based sleep
There are no shared test utility modules -- each test file is self-contained and inlines everything it needs. There is no test/helpers/, test/fixtures/, or test/setup.ts file.
5. Database Setup for Tests
The backend integration test uses SQLite in-memory mode for complete isolation:
// Set BEFORE any module imports that touch the DB
process.env.AGENTLOG_DB_PATH = ":memory:";
This works because the database.ts module's resolveDbPath() function checks process.env.AGENTLOG_DB_PATH first:
function resolveDbPath(): string {
if (process.env.AGENTLOG_DB_PATH) {
return process.env.AGENTLOG_DB_PATH; // returns ":memory:" in tests
}
// ...falls back to ~/.agentlog/agentlog.db
}
The database module uses a singleton pattern (_db module-level variable). The getDatabase() function initializes it lazily and closeDatabase() closes it and sets _db = null. Each test suite calls closeDatabase() in its after() hook.
Important caveat: Because the DB is a module-level singleton and process.env.AGENTLOG_DB_PATH is set once at the top of the test file, all suites within a single test run share the same :memory: strategy. However, since closeDatabase() nullifies the singleton, the next suite's buildApp() call triggers a fresh getDatabase() which creates a new in-memory database with fresh schema migrations. This means each suite gets a clean, empty database.
The schema initialization (tables, indexes, migrations) runs automatically inside getDatabase() via runMigrations(), so tests don't need any explicit setup SQL.
No temp file databases are used -- it's purely in-memory via better-sqlite3's :memory: mode.
Summary of Gaps / Observations
- No root-level
test script -- you cannot run all tests from the workspace root with a single command.
- No shared test utilities -- each test file re-implements helpers independently. The VS Code extension tests duplicate production code (pattern constants, parsing functions) inline because the production module depends on the
vscode API.
- No
@agentlog/shared tests -- the shared types/utilities package has no test coverage.
- No CI configuration found (no
.github/workflows, no Makefile, etc. for automated test runs -- though I did not exhaustively search for those).
- Test isolation relies on the singleton DB being closed and re-created between suites, which works but is fragile if suite ordering changes or suites run in parallel.