From 7d431a89a73374ff1644d59a91f7dd1780aa49ce Mon Sep 17 00:00:00 2001 From: lezi-fun <177434121+lezi-fun@users.noreply.github.com> Date: Sun, 9 Aug 2026 21:26:03 +0800 Subject: [PATCH] test: add API integration test suite (40 tests) - node:test based, zero extra dependencies, npm test script - api.test.js: auth, posts, pagination, replies, 404/401 handling - admin.test.js: admin API, role management, settings, links, logs - dm.test.js: private messaging, unread counts, read receipts, 403 - helpers.js: makeAdmin() to guarantee admin role in shared DB - test/README.md: setup and run instructions --- package.json | 3 +- test/README.md | 35 +++++++++++ test/admin.test.js | 141 +++++++++++++++++++++++++++++++++++++++++++ test/api.test.js | 146 +++++++++++++++++++++++++++++++++++++++++++++ test/dm.test.js | 118 ++++++++++++++++++++++++++++++++++++ test/helpers.js | 21 +++++++ 6 files changed, 463 insertions(+), 1 deletion(-) create mode 100644 test/README.md create mode 100644 test/admin.test.js create mode 100644 test/api.test.js create mode 100644 test/dm.test.js create mode 100644 test/helpers.js diff --git a/package.json b/package.json index 80e3c91..4dfeda5 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "scripts": { "dev": "next dev -H 0.0.0.0", "build": "next build", - "start": "node scripts/start.js" + "start": "node scripts/start.js", + "test": "node --test --test-concurrency=1 \"test/*.test.js\"" }, "dependencies": { "bcrypt": "^5.1.1", diff --git a/test/README.md b/test/README.md new file mode 100644 index 0000000..7a284ee --- /dev/null +++ b/test/README.md @@ -0,0 +1,35 @@ +# 测试 + +Forumlify 使用 Node.js 内置的 `node:test` 测试框架(零额外依赖)。 + +## 前置条件 + +测试需要一个可用的 PostgreSQL 数据库和运行中的服务实例。 + +```bash +# 1. 启动测试数据库(PostgreSQL 15) +docker run -d --name forumlify-test \ + -e POSTGRES_USER=forumlify -e POSTGRES_PASSWORD=123456 -e POSTGRES_DB=forumlify \ + -p 5433:5432 postgres:15 + +# 2. 导入表结构 +docker exec -i forumlify-test psql -U forumlify -d forumlify < schema.sql + +# 3. 构建并启动服务(测试端口 3100) +DATABASE_URL='postgresql://forumlify:123456@localhost:5433/forumlify' \ +JWT_SECRET=test-secret PORT=3100 npm run build && npm start +``` + +## 运行测试 + +```bash +# 默认连 http://localhost:3100 +npm test + +# 指定服务地址 +BASE_URL=http://localhost:3200 npm test +``` + +## 覆盖范围 + +- `api.test.js` — 认证(注册/登录/me)、帖子(创建/列表/分页/删除)、回复、举报、友链、统计、私信、权限(401/403/404) diff --git a/test/admin.test.js b/test/admin.test.js new file mode 100644 index 0000000..fe5bc2a --- /dev/null +++ b/test/admin.test.js @@ -0,0 +1,141 @@ +// Forumlify API 集成测试 — 管理后台 + 权限 +// 运行: BASE_URL=http://localhost:3100 npm test +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { makeAdmin } from './helpers.js'; + +const BASE = process.env.BASE_URL || 'http://localhost:3100'; +const suffix = Date.now() + Math.floor(Math.random() * 100000); + +async function api(path, options = {}) { + const res = await fetch(BASE + '/api' + path, { + ...options, + headers: { + 'Content-Type': 'application/json', + ...(options.headers || {}), + }, + }); + const data = await res.json().catch(() => ({})); + return { status: res.status, data }; +} + +let adminToken = null; +let userToken = null; +let userId = null; +const adminUser = { email: `adm${suffix}@test.com`, password: '123456', username: `adm${suffix}` }; +const normalUser = { email: `usr${suffix}@test.com`, password: '123456', username: `usr${suffix}` }; + +test('设置: 注册管理员 + 登录', async () => { + await api('/auth/register', { method: 'POST', body: JSON.stringify(adminUser) }); + // 保证是 admin(即使库里已有其他用户) + await makeAdmin(adminUser.email); + const { data } = await api('/auth/login', { + method: 'POST', + body: JSON.stringify({ email: adminUser.email, password: adminUser.password }), + }); + adminToken = data.token; + assert.ok(adminToken); +}); + +test('设置: 注册普通用户 + 登录', async () => { + await api('/auth/register', { method: 'POST', body: JSON.stringify(normalUser) }); + const { data } = await api('/auth/login', { + method: 'POST', + body: JSON.stringify({ email: normalUser.email, password: normalUser.password }), + }); + userToken = data.token; + userId = data.user.id; +}); + +test('普通用户访问管理接口返回 403', async () => { + const { status } = await api('/users', { headers: { Authorization: `Bearer ${userToken}` } }); + assert.equal(status, 403); +}); + +test('管理员获取用户列表', async () => { + const { status, data } = await api('/users', { headers: { Authorization: `Bearer ${adminToken}` } }); + assert.equal(status, 200); + assert.ok(data.length >= 2); +}); + +test('按用户名查询用户', async () => { + const { data } = await api('/users?username=' + normalUser.username, { + headers: { Authorization: `Bearer ${adminToken}` }, + }); + assert.ok(data.length === 1); + assert.equal(data[0].username, normalUser.username); +}); + +test('管理员不能修改自己的角色', async () => { + const me = await api('/auth/me', { headers: { Authorization: `Bearer ${adminToken}` } }); + const { status } = await api('/users/' + me.data.id + '/role', { + method: 'PUT', + headers: { Authorization: `Bearer ${adminToken}` }, + body: JSON.stringify({ role: 'user' }), + }); + assert.equal(status, 400); +}); + +test('管理员修改普通用户角色', async () => { + const { status } = await api('/users/' + userId + '/role', { + method: 'PUT', + headers: { Authorization: `Bearer ${adminToken}` }, + body: JSON.stringify({ role: 'admin' }), + }); + assert.equal(status, 200); +}); + +test('更新论坛名称', async () => { + const { status } = await api('/settings', { + method: 'PUT', + headers: { Authorization: `Bearer ${adminToken}` }, + body: JSON.stringify({ forum_name: '测试论坛' }), + }); + assert.equal(status, 200); +}); + +test('获取论坛设置', async () => { + const { status, data } = await api('/settings'); + assert.equal(status, 200); + assert.equal(data.forum_name, '测试论坛'); +}); + +test('添加友情链接', async () => { + const { status, data } = await api('/links', { + method: 'POST', + headers: { Authorization: `Bearer ${adminToken}` }, + body: JSON.stringify({ title: 'GitHub', url: 'https://github.com' }), + }); + assert.equal(status, 200); + assert.ok(data.id); +}); + +test('获取友情链接列表', async () => { + const { status, data } = await api('/links'); + assert.equal(status, 200); + assert.ok(data.length >= 1); +}); + +test('统计接口', async () => { + const { status, data } = await api('/stats'); + assert.equal(status, 200); + assert.ok(typeof data.posts === 'number'); + assert.ok(typeof data.users === 'number'); +}); + +test('记录事件日志', async () => { + const { status } = await api('/event-logs', { + method: 'POST', + headers: { Authorization: `Bearer ${adminToken}` }, + body: JSON.stringify({ action: 'test_action' }), + }); + assert.equal(status, 200); +}); + +test('管理员查看事件日志', async () => { + const { status, data } = await api('/event-logs', { + headers: { Authorization: `Bearer ${adminToken}` }, + }); + assert.equal(status, 200); + assert.ok(Array.isArray(data)); +}); diff --git a/test/api.test.js b/test/api.test.js new file mode 100644 index 0000000..9b877cf --- /dev/null +++ b/test/api.test.js @@ -0,0 +1,146 @@ +// Forumlify API 集成测试 — 认证 + 帖子 +// 运行: BASE_URL=http://localhost:3100 npm test +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { makeAdmin } from './helpers.js'; + +const BASE = process.env.BASE_URL || 'http://localhost:3100'; +const suffix = Date.now() + Math.floor(Math.random() * 100000); // 每次运行唯一后缀,避免冲突 + +async function api(path, options = {}) { + const res = await fetch(BASE + '/api' + path, { + ...options, + headers: { + 'Content-Type': 'application/json', + ...(options.headers || {}), + }, + }); + const data = await res.json().catch(() => ({})); + return { status: res.status, data }; +} + +let adminToken = null; +let adminId = null; +let userId = null; +let postId = null; +let replyId = null; + +const adminUser = { email: `admin${suffix}@test.com`, password: '123456', username: `admin${suffix}` }; +const normalUser = { email: `user${suffix}@test.com`, password: '123456', username: `user${suffix}` }; + +test('注册第一个用户自动成为管理员', async () => { + const { status, data } = await api('/auth/register', { + method: 'POST', + body: JSON.stringify(adminUser), + }); + assert.equal(status, 200); + assert.ok(data.user.id); + // 共享库中可能已有用户,makeAdmin 确保测试管理员有 admin 权限 + await makeAdmin(adminUser.email); +}); + +test('登录并获取 token', async () => { + const { status, data } = await api('/auth/login', { + method: 'POST', + body: JSON.stringify({ email: adminUser.email, password: adminUser.password }), + }); + assert.equal(status, 200); + assert.ok(data.token); + adminToken = data.token; + adminId = data.user.id; +}); + +test('GET /api/auth/me 返回当前用户', async () => { + const { status, data } = await api('/auth/me', { headers: { Authorization: `Bearer ${adminToken}` } }); + assert.equal(status, 200); + assert.equal(data.username, adminUser.username); +}); + +test('注册普通用户', async () => { + const { status, data } = await api('/auth/register', { + method: 'POST', + body: JSON.stringify(normalUser), + }); + assert.equal(status, 200); + assert.equal(data.user.role, 'user'); + userId = data.user.id; +}); + +test('密码少于6位被拒绝', async () => { + const { status } = await api('/auth/register', { + method: 'POST', + body: JSON.stringify({ email: `x${suffix}@test.com`, password: '123', username: `x${suffix}` }), + }); + assert.equal(status, 400); +}); + +test('未登录访问受保护接口返回 401', async () => { + const { status } = await api('/auth/me'); + assert.equal(status, 401); +}); + +test('发布帖子', async () => { + const { status, data } = await api('/posts', { + method: 'POST', + headers: { Authorization: `Bearer ${adminToken}` }, + body: JSON.stringify({ title: '测试帖子', content: '这是测试内容' }), + }); + assert.equal(status, 200); + assert.ok(data.id); + postId = data.id; +}); + +test('帖子列表返回分页结构', async () => { + const { status, data } = await api('/posts?page=1&limit=20'); + assert.equal(status, 200); + assert.ok(Array.isArray(data.data)); + assert.ok(data.pagination); + assert.ok(data.pagination.totalPages >= 1); + assert.ok(data.data.some((p) => p.id === postId)); +}); + +test('按 user_id 筛选帖子', async () => { + const { data } = await api('/posts?user_id=' + adminId); + assert.ok(data.data.every((p) => p.user_id === adminId)); +}); + +test('帖子详情', async () => { + const { status, data } = await api('/posts/' + postId); + assert.equal(status, 200); + assert.equal(data.title, '测试帖子'); +}); + +test('不存在的帖子返回 404', async () => { + const { status } = await api('/posts/00000000-0000-0000-0000-000000000000'); + assert.equal(status, 404); +}); + +test('非法 UUID 返回 404 而非 500', async () => { + const { status } = await api('/posts/not-a-uuid'); + assert.equal(status, 404); +}); + +test('回复帖子', async () => { + const { status, data } = await api('/posts/' + postId + '/replies', { + method: 'POST', + headers: { Authorization: `Bearer ${adminToken}` }, + body: JSON.stringify({ content: '第一条回复' }), + }); + assert.equal(status, 200); + assert.ok(data.id); + replyId = data.id; +}); + +test('获取回复列表', async () => { + const { status, data } = await api('/posts/' + postId + '/replies'); + assert.equal(status, 200); + assert.ok(data.length >= 1); +}); + +test('删除自己的回复', async () => { + const { status } = await api('/replies/' + replyId, { + method: 'DELETE', + headers: { Authorization: `Bearer ${adminToken}` }, + }); + assert.equal(status, 200); +}); diff --git a/test/dm.test.js b/test/dm.test.js new file mode 100644 index 0000000..2d7660b --- /dev/null +++ b/test/dm.test.js @@ -0,0 +1,118 @@ +// Forumlify API 集成测试 — 私信系统 +// 运行: BASE_URL=http://localhost:3100 npm test +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { makeAdmin } from './helpers.js'; + +const BASE = process.env.BASE_URL || 'http://localhost:3100'; +const suffix = Date.now() + Math.floor(Math.random() * 100000); + +async function api(path, options = {}) { + const res = await fetch(BASE + '/api' + path, { + ...options, + headers: { + 'Content-Type': 'application/json', + ...(options.headers || {}), + }, + }); + const data = await res.json().catch(() => ({})); + return { status: res.status, data }; +} + +async function register(email, username) { + await api('/auth/register', { method: 'POST', body: JSON.stringify({ email, password: '123456', username }) }); + const { data } = await api('/auth/login', { method: 'POST', body: JSON.stringify({ email, password: '123456' }) }); + return data.token; +} + +let tokenA, tokenB, tokenC, idB, convId; + +test('私信: 注册三个用户', async () => { + tokenA = await register(`ma${suffix}@test.com`, `ma${suffix}`); + tokenB = await register(`mb${suffix}@test.com`, `mb${suffix}`); + tokenC = await register(`mc${suffix}@test.com`, `mc${suffix}`); + // /api/users 是 admin 接口,保证 A 是 admin 以便查询用户 id + await makeAdmin(`ma${suffix}@test.com`); + assert.ok(tokenA && tokenB && tokenC); +}); + +test('私信: 找到用户 B 的 id', async () => { + const { data } = await api('/users', { headers: { Authorization: `Bearer ${tokenA}` } }); + idB = data.find((u) => u.username === `mb${suffix}`).id; + assert.ok(idB); +}); + +test('私信: 创建会话', async () => { + const { status, data } = await api('/conversations', { + method: 'POST', + headers: { Authorization: `Bearer ${tokenA}` }, + body: JSON.stringify({ other_user_id: idB }), + }); + assert.equal(status, 200); + assert.ok(data.id); + convId = data.id; +}); + +test('私信: 同一对用户复用会话', async () => { + const { data } = await api('/conversations', { + method: 'POST', + headers: { Authorization: `Bearer ${tokenA}` }, + body: JSON.stringify({ other_user_id: idB }), + }); + assert.equal(data.id, convId); +}); + +test('私信: 不能与自己私信', async () => { + const me = await api('/auth/me', { headers: { Authorization: `Bearer ${tokenA}` } }); + const { status } = await api('/conversations', { + method: 'POST', + headers: { Authorization: `Bearer ${tokenA}` }, + body: JSON.stringify({ other_user_id: me.data.id }), + }); + assert.equal(status, 400); +}); + +test('私信: A 发送消息给 B', async () => { + const { status, data } = await api('/conversations/' + convId + '/messages', { + method: 'POST', + headers: { Authorization: `Bearer ${tokenA}` }, + body: JSON.stringify({ content: '你好 B' }), + }); + assert.equal(status, 200); + assert.equal(data.content, '你好 B'); +}); + +test('私信: B 看到未读消息', async () => { + const { data } = await api('/conversations', { headers: { Authorization: `Bearer ${tokenB}` } }); + const conv = data.find((c) => c.id === convId); + assert.ok(conv); + assert.equal(parseInt(conv.unread_count), 1); + assert.equal(conv.last_message, '你好 B'); +}); + +test('私信: B 读取消息后标记已读', async () => { + await api('/conversations/' + convId + '/messages', { headers: { Authorization: `Bearer ${tokenB}` } }); + const { data } = await api('/conversations', { headers: { Authorization: `Bearer ${tokenB}` } }); + assert.equal(parseInt(data.find((c) => c.id === convId).unread_count), 0); +}); + +test('私信: B 回复 A', async () => { + const { status } = await api('/conversations/' + convId + '/messages', { + method: 'POST', + headers: { Authorization: `Bearer ${tokenB}` }, + body: JSON.stringify({ content: '你好 A' }), + }); + assert.equal(status, 200); +}); + +test('私信: 第三方 C 无权访问会话', async () => { + const { status } = await api('/conversations/' + convId + '/messages', { + headers: { Authorization: `Bearer ${tokenC}` }, + }); + assert.equal(status, 403); +}); + +test('私信: 未登录返回 401', async () => { + const { status } = await api('/conversations'); + assert.equal(status, 401); +}); diff --git a/test/helpers.js b/test/helpers.js new file mode 100644 index 0000000..c918145 --- /dev/null +++ b/test/helpers.js @@ -0,0 +1,21 @@ +// 测试辅助工具 +import pg from 'pg'; + +// 从 DATABASE_URL 或默认连接串读取(与测试库保持一致) +const pool = new pg.Pool({ + connectionString: process.env.DATABASE_URL || 'postgresql://forumlify:123456@localhost:5433/forumlify', +}); + +// 把指定用户提升为管理员(绕过"第一个用户才 admin"的限制,保证每个测试文件可独立获得 admin) +export async function makeAdmin(email) { + await pool.query('UPDATE users SET role = $1 WHERE email = $2', ['admin', email]); + await pool.end(); +} + +// 清理测试数据(可选) +export async function cleanup(emails) { + for (const email of emails) { + await pool.query('DELETE FROM users WHERE email = $1', [email]); + } + await pool.end(); +}