Files
live-hub-py/.githooks/pre-push
T
yml b0be3d15cc test: 拆分慢速迁移测试并优化 pre-push
- 迁移测试标记 migration,单独运行约 130 秒
- 非迁移测试约 90 秒,日常开发跑快速集
- pre-push 默认跳过 migration;改迁移/模型/迁移测试时自动全量
- FULL_TESTS=1 可强制全量,不删除任何迁移测试
2026-11-24 19:14:40 +08:00

103 lines
3.2 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
push_lines="$(cat)"
while read -r local_ref local_sha remote_ref remote_sha; do
if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
echo "[pre-push] 分支删除推送,跳过测试"
exit 0
fi
done <<< "$push_lines"
if [ "${SKIP_TESTS:-0}" = "1" ]; then
echo "[pre-push] SKIP_TESTS=1,跳过测试"
exit 0
fi
python_files=()
frontend_changed=0
migration_changed=0
while read -r local_ref local_sha remote_ref remote_sha; do
[ -z "$local_sha" ] && continue
if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
continue
fi
if [ "$remote_sha" = "0000000000000000000000000000000000000000" ]; then
changed_paths="$(git diff-tree --no-commit-id --name-only -r --root "$local_sha")"
else
changed_paths="$(git diff --name-only "$remote_sha..$local_sha")"
fi
while IFS= read -r path; do
[ -z "$path" ] && continue
case "$path" in
*.py)
[ -f "$path" ] && python_files+=("$path")
;;
web/frontend/*)
frontend_changed=1
;;
web/backend/migrations/*|web/backend/models.py|tests/test_migrations.py|tests/test_migration_*.py|tests/test_login_attempt_migration.py)
migration_changed=1
;;
esac
done <<< "$changed_paths"
done <<< "$push_lines"
if [ "${#python_files[@]}" -gt 0 ]; then
echo "[pre-push] 检查 Python 格式..."
uv run --group dev ruff format --check "${python_files[@]}"
echo "[pre-push] Python 格式通过"
fi
if [ "$frontend_changed" -eq 1 ]; then
.githooks/run-frontend-tsc.sh
fi
if [ "${TYPECHECK:-0}" = "1" ]; then
echo "[pre-push] 运行 Pyright 类型检查..."
uv run --group dev pyright
echo "[pre-push] Pyright 通过"
fi
# pytest 跑在真实 MySQL 上;钩子自己确保测试库可用,避免只抛一堆连接错误。
ensure_test_mysql() {
if ! command -v docker >/dev/null 2>&1; then
echo "[pre-push] ❌ 未安装 Docker,无法启动测试 MySQL"
return 1
fi
if ! docker info >/dev/null 2>&1; then
echo "[pre-push] ❌ Docker 未运行,请先启动 Docker"
return 1
fi
if docker compose ps -q mysql 2>/dev/null | grep -q .; then
echo "[pre-push] 测试 MySQL 已在运行"
else
echo "[pre-push] 测试 MySQL 未运行,正在启动..."
docker compose up -d mysql
fi
for _ in $(seq 1 30); do
if docker compose exec -T mysql sh -c \
'mysqladmin ping -h localhost -uroot -p"$MYSQL_ROOT_PASSWORD" --silent' \
>/dev/null 2>&1; then
echo "[pre-push] 测试 MySQL 已就绪"
return 0
fi
sleep 2
done
echo "[pre-push] ❌ 测试 MySQL 启动超时"
return 1
}
ensure_test_mysql
if [ "${FULL_TESTS:-0}" = "1" ] || [ "$migration_changed" -eq 1 ]; then
echo "[pre-push] 运行全量 pytest(含迁移测试)..."
./dev.sh test -q
else
echo "[pre-push] 运行 pytest(跳过慢速迁移测试;FULL_TESTS=1 可跑全量)..."
./dev.sh test -q -m "not migration"
fi
echo "[pre-push] pytest 通过"