Bun 博客实战(10):测试、构建与部署
在练习中成长
不用等读完,先测一下一句话:测试不碰线上库,构建不依赖目标机装 Bun,部署只走 VPS 单文件。
测试:bun:test
import { describe, expect, test } from 'bun:test'
describe('markdown', () => {
test('先转义再生成标签', () => {
expect(renderMarkdown('<script>alert(1)</script>'))
.toContain('<script>')
})
})
测试和源码同构,放在 tests/。不装 Jest/Vitest,bun test 直接跑。
临时数据库
DB 测试必须在 import db 之前设置:
BLOG_DB_FILE=/tmp/blog-test.sqlite bun test
或者测试文件顶部:
process.env.BLOG_DB_FILE = `/tmp/blog-test-${crypto.randomUUID()}.sqlite`
const { initLocalDb } = await import('../src/lib/engine/sqlite.ts')
初始化后 savePost/savePage 直接造数据:
await savePost({
slug: 'test-post',
title: 'Test',
date: '2026-10-26',
tags: ['test'],
summary: 'summary',
series: '',
published: true,
body: '# Hello',
})
不要用 content/archive 当测试夹具:它是导入源,不是稳定契约。
类型检查
bun run typecheck
tsc --noEmit 覆盖 src 和 tests。几个关键开关:
strict;noUncheckedIndexedAccess;noUnusedLocals/Parameters;verbatimModuleSyntax。
类型检查不是测试的替代品:它能抓接口不匹配,抓不到 SQL 写错、路由顺序、HTML 转义。
构建:单文件
bun run build:bin
实际执行:
bun build --compile --minify ./src/index.ts --outfile ./dist/blog-server
产物自带运行时。部署时:
BLOG_ROOT=/home/wangbing/blog ./dist/blog-server
必须保证 BLOG_ROOT 下有:
public/ 静态资源
db/blog.sqlite 数据库
否则单文件程序找不到 CSS、htmx 和 DB。db/schema.sql 不进产物,建表靠内嵌的 SCHEMA_SQL。
VPS 部署
简单流程:
git fetch origin main
git reset --hard origin/main
bun run build:bin
sudo systemctl restart blog
内容更新另走 db:import <slug>/seed-en,不要每次全量导入覆盖 DB。发布后用 curl 检查 200/301/302,并跑一次 sitemap/IndexNow。
回归清单
bun run typecheckbun test- 首页/文章/系列/测验/admin 各打一次 200;
- 旧 URL 301;
- 匿名访问后台 302,非管理员 403;
- sitemap 不包含私有后台;
- 移动端看一次导航/代码块。
边界
- 没有端到端浏览器测试;htmx 片段用轻量集成测试;
- 没有负载/并发测试;
- 没有自动回滚脚本;
- 单文件构建只覆盖 Linux 当前架构,其他平台需在对应平台编译。
验证状态
- ✅ 命令、
BLOG_ROOT、VPS 入口与当前仓库一致; - ✅ 测试使用临时
BLOG_DB_FILE; - ⚠️ 生产部署前仍需人工 smoke test,尤其是静态资源和反代。
评论 0
还没有评论,来抢沙发~