Compare commits
46 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 5aef45636f | |||
| de5538ad1f | |||
| 0a23f72bfa | |||
| bb83549cc0 | |||
| 92b8044cb3 | |||
| a9bc314fed | |||
| 911478495a | |||
| e4ce3caad1 | |||
| 35f92f8101 | |||
| ed061aae3e | |||
| 6d8656b3f6 | |||
| 52e866b750 | |||
| 2cb273b472 | |||
| 7a1f7c89b5 | |||
| 8c1566cec3 | |||
| 246406eeb0 | |||
| a0c27e3132 | |||
| 61f0601cd4 | |||
| a39680dbca | |||
| 319347cb41 | |||
| 8a59fff246 | |||
| 13e5c03e77 | |||
| 83d373c840 | |||
| 7b2d794126 | |||
| 6ce7db7f8e | |||
| 6b45ddb6fc | |||
| d3438b9786 | |||
| 1669e787c2 | |||
| 7cffe564a9 | |||
| c2ad5003df | |||
| 14be2b654b | |||
| 92c11ced63 | |||
| 3379f07a15 | |||
| cfe75543a1 | |||
| 5e44f3dd1a | |||
| 95683ab5ef | |||
| 6bde806462 | |||
| 0ae105628d | |||
| 24efd5121f | |||
| e0c3bae072 | |||
| 05b84ac669 | |||
| 6fe648432a | |||
| 81ae089985 | |||
| f22a6fd90e | |||
| a18244b8a4 | |||
| 48102ca2e2 |
@@ -0,0 +1,78 @@
|
||||
name: CI Failure Monitor
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 */6 * * *' # 每6小时检查一次
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
days:
|
||||
description: '统计最近N天的失败'
|
||||
required: false
|
||||
default: '7'
|
||||
fail_threshold:
|
||||
description: '失败次数阈值'
|
||||
required: false
|
||||
default: '3'
|
||||
fail_rate_threshold:
|
||||
description: '失败率阈值(%)'
|
||||
required: false
|
||||
default: '30'
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
monitor:
|
||||
name: CI重复失败检测
|
||||
runs-on: ci-l2
|
||||
timeout-minutes: 10
|
||||
|
||||
steps:
|
||||
- name: Checkout code
|
||||
shell: sh
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
curl -sH "Authorization: token $GITHUB_TOKEN" \
|
||||
"${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/raw/scripts/ci/step_checkout.sh?ref=${GITHUB_SHA}" \
|
||||
| bash
|
||||
|
||||
- name: Record job start time
|
||||
shell: sh
|
||||
run: bash scripts/ci/step_timer_start.sh
|
||||
|
||||
- name: Run failure detection
|
||||
shell: sh
|
||||
env:
|
||||
GITEA_API_TOKEN: ${{ secrets.REVIEW_GITEA_TOKEN }}
|
||||
GITEA_URL: https://git.xiaoxiajianji.com
|
||||
GITEA_REPO: xiaoxia/xiaoxia-saas
|
||||
CI_NOTIFY_WEBHOOK: ${{ secrets.CI_NOTIFY_WEBHOOK }}
|
||||
FAIL_CHECK_DAYS: ${{ inputs.days || 7 }}
|
||||
FAIL_THRESHOLD: ${{ inputs.fail_threshold || 3 }}
|
||||
FAIL_RATE_THRESHOLD: ${{ inputs.fail_rate_threshold || 30 }}
|
||||
run: |
|
||||
set +e
|
||||
python3 scripts/ci/ci_repeated_failure_detector.py
|
||||
EXIT_CODE=$?
|
||||
echo "检测完成,退出码: $EXIT_CODE"
|
||||
# 0=无异常, 1=有警告, 2=有严重问题
|
||||
# 监控脚本永远不fail,避免告警风暴
|
||||
exit 0
|
||||
|
||||
- name: Job duration summary
|
||||
if: always()
|
||||
shell: sh
|
||||
run: bash scripts/ci/step_timer_end.sh
|
||||
|
||||
- name: Report CI trace
|
||||
if: always()
|
||||
shell: sh
|
||||
env:
|
||||
AGENTLOOP_LICENSE_KEY: ${{ secrets.AGENTLOOP_LICENSE_KEY }}
|
||||
run: |
|
||||
STATUS="ok"
|
||||
[ ${{ job.status }} = "success" ] || STATUS="error"
|
||||
START_TIME=""
|
||||
[ -f /tmp/ci_job_start_time ] && START_TIME=$(cat /tmp/ci_job_start_time)
|
||||
python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true
|
||||
@@ -76,18 +76,12 @@ jobs:
|
||||
[ -f /tmp/ci_job_start_time ] && START_TIME=$(cat /tmp/ci_job_start_time)
|
||||
python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true
|
||||
|
||||
validate:
|
||||
needs: check-frontend-only
|
||||
if: always() && needs.check-frontend-only.outputs.skip_backend != 'true'
|
||||
name: Validate Code Quality And Tests
|
||||
validate-code-quality:
|
||||
name: Validate - Code Quality
|
||||
runs-on: ci-l2
|
||||
timeout-minutes: 10
|
||||
timeout-minutes: 8
|
||||
permissions:
|
||||
contents: write
|
||||
env:
|
||||
DATABASE_URL: postgresql+psycopg://postgres:postgres@host.docker.internal:5432/xiaoxia_saas
|
||||
USE_IN_MEMORY_DB: 'false'
|
||||
CI_USE_SHARED_PG: 'true'
|
||||
steps:
|
||||
- name: Checkout code
|
||||
shell: sh
|
||||
@@ -102,7 +96,6 @@ jobs:
|
||||
shell: sh
|
||||
run: |
|
||||
set -eu
|
||||
# pip install 带重试(网络不稳定时自动重试)
|
||||
for i in 1 2 3; do
|
||||
python3 -m pip install -q -r requirements-base.txt && break
|
||||
echo "pip install requirements-base.txt 失败,重试 $i/3..."
|
||||
@@ -127,11 +120,11 @@ jobs:
|
||||
[ $i -eq 3 ] && exit 1
|
||||
sleep 5
|
||||
done
|
||||
- name: Run all quality checks
|
||||
- name: Run code quality and security checks
|
||||
shell: bash
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: bash scripts/ci/run_validate.sh
|
||||
run: bash scripts/ci/validate_code_quality.sh
|
||||
- name: Auto-fix formatting (black + isort)
|
||||
if: failure()
|
||||
shell: sh
|
||||
@@ -146,7 +139,7 @@ jobs:
|
||||
CI_WEBHOOK_URL: ${{ secrets.CI_WEBHOOK_URL }}
|
||||
run: |
|
||||
set +e
|
||||
FAILED_JOB="Validate Code Quality And Tests" python3 scripts/ci_notify_failure.py
|
||||
FAILED_JOB="Validate - Code Quality" python3 scripts/ci_notify_failure.py
|
||||
- name: Job duration summary
|
||||
if: always()
|
||||
shell: sh
|
||||
@@ -159,7 +152,161 @@ jobs:
|
||||
CI_NOTIFY_WEBHOOK: ${{ secrets.CI_NOTIFY_WEBHOOK }}
|
||||
run: |
|
||||
set +e
|
||||
NOTIFY_MODE=failure JOB_NAME="Validate Code Quality And Tests" python3 scripts/ci_notify.py
|
||||
NOTIFY_MODE=failure JOB_NAME="Validate - Code Quality" python3 scripts/ci_notify.py
|
||||
- name: Report CI trace
|
||||
if: always()
|
||||
shell: sh
|
||||
env:
|
||||
AGENTLOOP_LICENSE_KEY: ${{ secrets.AGENTLOOP_LICENSE_KEY }}
|
||||
run: |
|
||||
STATUS="ok"
|
||||
[ ${{ job.status }} = "success" ] || STATUS="error"
|
||||
START_TIME=""
|
||||
[ -f /tmp/ci_job_start_time ] && START_TIME=$(cat /tmp/ci_job_start_time)
|
||||
python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true
|
||||
|
||||
validate-type-check:
|
||||
name: Validate - Type Check (mypy)
|
||||
runs-on: ci-l2
|
||||
timeout-minutes: 8
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
shell: sh
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
curl -sH "Authorization: token $GITHUB_TOKEN" "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/raw/scripts/ci/step_checkout.sh?ref=${GITHUB_SHA}" | bash
|
||||
- name: Record job start time
|
||||
shell: sh
|
||||
run: bash scripts/ci/step_timer_start.sh
|
||||
- name: Install dependencies
|
||||
shell: sh
|
||||
run: |
|
||||
set -eu
|
||||
for i in 1 2 3; do
|
||||
python3 -m pip install -q -r requirements-base.txt && break
|
||||
echo "pip install requirements-base.txt 失败,重试 $i/3..."
|
||||
[ $i -eq 3 ] && exit 1
|
||||
sleep 5
|
||||
done
|
||||
for i in 1 2 3; do
|
||||
python3 -m pip install -q -r requirements.txt && break
|
||||
echo "pip install requirements.txt 失败,重试 $i/3..."
|
||||
[ $i -eq 3 ] && exit 1
|
||||
sleep 5
|
||||
done
|
||||
for i in 1 2 3; do
|
||||
python3 -m pip install -q -r requirements-dev.txt && break
|
||||
echo "pip install requirements-dev.txt 失败,重试 $i/3..."
|
||||
[ $i -eq 3 ] && exit 1
|
||||
sleep 5
|
||||
done
|
||||
- name: Run mypy type check
|
||||
shell: bash
|
||||
run: bash scripts/ci/validate_mypy.sh
|
||||
- name: CI failure notification
|
||||
if: failure()
|
||||
shell: sh
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
CI_WEBHOOK_URL: ${{ secrets.CI_WEBHOOK_URL }}
|
||||
run: |
|
||||
set +e
|
||||
FAILED_JOB="Validate - Type Check (mypy)" python3 scripts/ci_notify_failure.py
|
||||
- name: Job duration summary
|
||||
if: always()
|
||||
shell: sh
|
||||
run: bash scripts/ci/step_timer_end.sh
|
||||
- name: Notify on failure
|
||||
continue-on-error: true
|
||||
if: failure()
|
||||
shell: sh
|
||||
env:
|
||||
CI_NOTIFY_WEBHOOK: ${{ secrets.CI_NOTIFY_WEBHOOK }}
|
||||
run: |
|
||||
set +e
|
||||
NOTIFY_MODE=failure JOB_NAME="Validate - Type Check (mypy)" python3 scripts/ci_notify.py
|
||||
- name: Report CI trace
|
||||
if: always()
|
||||
shell: sh
|
||||
env:
|
||||
AGENTLOOP_LICENSE_KEY: ${{ secrets.AGENTLOOP_LICENSE_KEY }}
|
||||
run: |
|
||||
STATUS="ok"
|
||||
[ ${{ job.status }} = "success" ] || STATUS="error"
|
||||
START_TIME=""
|
||||
[ -f /tmp/ci_job_start_time ] && START_TIME=$(cat /tmp/ci_job_start_time)
|
||||
python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true
|
||||
|
||||
validate-migration:
|
||||
name: Validate - Migration (alembic)
|
||||
runs-on: ci-l2
|
||||
timeout-minutes: 8
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
DATABASE_URL: postgresql+psycopg://postgres:postgres@host.docker.internal:5432/xiaoxia_saas
|
||||
USE_IN_MEMORY_DB: 'false'
|
||||
CI_USE_SHARED_PG: 'true'
|
||||
steps:
|
||||
- name: Checkout code
|
||||
shell: sh
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
curl -sH "Authorization: token $GITHUB_TOKEN" "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/raw/scripts/ci/step_checkout.sh?ref=${GITHUB_SHA}" | bash
|
||||
- name: Record job start time
|
||||
shell: sh
|
||||
run: bash scripts/ci/step_timer_start.sh
|
||||
- name: Install dependencies
|
||||
shell: sh
|
||||
run: |
|
||||
set -eu
|
||||
for i in 1 2 3; do
|
||||
python3 -m pip install -q -r requirements-base.txt && break
|
||||
echo "pip install requirements-base.txt 失败,重试 $i/3..."
|
||||
[ $i -eq 3 ] && exit 1
|
||||
sleep 5
|
||||
done
|
||||
for i in 1 2 3; do
|
||||
python3 -m pip install -q -r requirements.txt && break
|
||||
echo "pip install requirements.txt 失败,重试 $i/3..."
|
||||
[ $i -eq 3 ] && exit 1
|
||||
sleep 5
|
||||
done
|
||||
for i in 1 2 3; do
|
||||
python3 -m pip install -q -r requirements-dev.txt && break
|
||||
echo "pip install requirements-dev.txt 失败,重试 $i/3..."
|
||||
[ $i -eq 3 ] && exit 1
|
||||
sleep 5
|
||||
done
|
||||
- name: Run alembic migration validation
|
||||
shell: bash
|
||||
run: bash scripts/ci/validate_migration.sh
|
||||
- name: CI failure notification
|
||||
if: failure()
|
||||
shell: sh
|
||||
env:
|
||||
GITEA_TOKEN: ${{ secrets.GITEA_TOKEN }}
|
||||
CI_WEBHOOK_URL: ${{ secrets.CI_WEBHOOK_URL }}
|
||||
run: |
|
||||
set +e
|
||||
FAILED_JOB="Validate - Migration (alembic)" python3 scripts/ci_notify_failure.py
|
||||
- name: Job duration summary
|
||||
if: always()
|
||||
shell: sh
|
||||
run: bash scripts/ci/step_timer_end.sh
|
||||
- name: Notify on failure
|
||||
continue-on-error: true
|
||||
if: failure()
|
||||
shell: sh
|
||||
env:
|
||||
CI_NOTIFY_WEBHOOK: ${{ secrets.CI_NOTIFY_WEBHOOK }}
|
||||
run: |
|
||||
set +e
|
||||
NOTIFY_MODE=failure JOB_NAME="Validate - Migration (alembic)" python3 scripts/ci_notify.py
|
||||
- name: Report CI trace
|
||||
if: always()
|
||||
shell: sh
|
||||
@@ -474,6 +621,65 @@ jobs:
|
||||
echo "Docker login failed ($i/3), retrying in 5s..."
|
||||
sleep 5
|
||||
done
|
||||
- name: Pre-build worker base images (fallback if not exist)
|
||||
if: matrix.service == 'worker'
|
||||
id: prebuild
|
||||
shell: sh
|
||||
run: |
|
||||
set -eu
|
||||
REGISTRY="git.xiaoxiajianji.com/xiaoxia-saas"
|
||||
BASE_BUILDER="${REGISTRY}/worker-base-builder:latest"
|
||||
BASE_RUNTIME="${REGISTRY}/worker-base-runtime:latest"
|
||||
|
||||
# 尝试拉取基础镜像
|
||||
echo "检查基础镜像..."
|
||||
if docker pull "$BASE_BUILDER" 2>/dev/null && docker pull "$BASE_RUNTIME" 2>/dev/null; then
|
||||
echo "基础镜像已存在,使用远程镜像"
|
||||
echo "fallback=false" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "基础镜像不存在,本地构建(fallback模式)..."
|
||||
|
||||
# 构建builder基础镜像
|
||||
echo "构建 worker-base-builder..."
|
||||
# 用buildx docker-container驱动构建(兼容DooD模式:普通docker build看不到容器内文件)
|
||||
BUILDER_NAME="ci-pr-builder-${GITHUB_RUN_ID:-local}"
|
||||
if ! docker buildx inspect "$BUILDER_NAME" > /dev/null 2>&1; then
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
else
|
||||
docker buildx use "$BUILDER_NAME"
|
||||
fi
|
||||
docker buildx inspect --bootstrap > /dev/null 2>&1
|
||||
|
||||
# 构建builder基础镜像(带重试,buildx容器偶发不稳定)
|
||||
echo "构建 worker-base-builder..."
|
||||
for attempt in 1 2 3; do
|
||||
if docker buildx build --load -f infra/docker/worker-base-builder.Dockerfile -t "$BASE_BUILDER" .; then
|
||||
echo "worker-base-builder 构建成功"
|
||||
break
|
||||
fi
|
||||
echo "worker-base-builder 构建失败,重试 $attempt/3..."
|
||||
docker buildx rm "$BUILDER_NAME" 2>/dev/null || true
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
sleep 3
|
||||
done
|
||||
|
||||
# 构建runtime基础镜像
|
||||
echo "构建 worker-base-runtime..."
|
||||
for attempt in 1 2 3; do
|
||||
if docker buildx build --load -f infra/docker/worker-base-runtime.Dockerfile -t "$BASE_RUNTIME" .; then
|
||||
echo "worker-base-runtime 构建成功"
|
||||
break
|
||||
fi
|
||||
echo "worker-base-runtime 构建失败,重试 $attempt/3..."
|
||||
docker buildx rm "$BUILDER_NAME" 2>/dev/null || true
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
sleep 3
|
||||
done
|
||||
|
||||
echo "fallback=true" >> $GITHUB_OUTPUT
|
||||
echo "基础镜像本地构建完成"
|
||||
fi
|
||||
|
||||
- name: Build PR image (verify only, no push)
|
||||
shell: sh
|
||||
run: |
|
||||
@@ -487,6 +693,18 @@ jobs:
|
||||
EXTRA_BUILD_ARGS="$EXTRA_BUILD_ARGS NGINX_CONF=infra/docker/nginx-staging.conf"
|
||||
fi
|
||||
|
||||
# Worker fallback模式:基础镜像本地已构建,用普通docker build绕过buildx
|
||||
if [ "${{ matrix.service }}" = "worker" ] && [ "${{ steps.prebuild.outputs.fallback }}" = "true" ]; then
|
||||
echo "Fallback模式:用普通docker build(基础镜像本地已构建)"
|
||||
BUILD_ARG_STR=""
|
||||
for arg in $EXTRA_BUILD_ARGS; do
|
||||
BUILD_ARG_STR="$BUILD_ARG_STR --build-arg $arg"
|
||||
done
|
||||
docker build -f ${{ matrix.dockerfile }} -t "${IMAGE_TAG}" $BUILD_ARG_STR .
|
||||
echo "Fallback PR Build successful"
|
||||
exit 0
|
||||
fi
|
||||
|
||||
NO_CACHE_FLAG=""
|
||||
for i in 1 2 3; do
|
||||
echo "PR Build attempt $i/3"
|
||||
@@ -1335,5 +1553,4 @@ jobs:
|
||||
[ ${{ job.status }} = "success" ] || STATUS="error"
|
||||
START_TIME=""
|
||||
[ -f /tmp/ci_job_start_time ] && START_TIME=$(cat /tmp/ci_job_start_time)
|
||||
python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true
|
||||
|
||||
python3 scripts/ci/ci_trace_report.py --service xiaoxia-saas-ci --status $STATUS --start-time "$START_TIME" || true
|
||||
@@ -54,7 +54,9 @@ jobs:
|
||||
CONTEXTS=("CI/CD Pipeline / Frontend Lint (pull_request)")
|
||||
else
|
||||
CONTEXTS=(
|
||||
"CI/CD Pipeline / Validate Code Quality And Tests (pull_request)"
|
||||
"CI/CD Pipeline / Validate - Code Quality (pull_request)"
|
||||
"CI/CD Pipeline / Validate - Type Check (mypy) (pull_request)"
|
||||
"CI/CD Pipeline / Validate - Migration (alembic) (pull_request)"
|
||||
"CI/CD Pipeline / Frontend Lint (pull_request)"
|
||||
)
|
||||
fi
|
||||
@@ -233,7 +235,9 @@ jobs:
|
||||
echo "纯前端改动,只检查Frontend Lint"
|
||||
else
|
||||
CONTEXTS=(
|
||||
"CI/CD Pipeline / Validate Code Quality And Tests (pull_request)"
|
||||
"CI/CD Pipeline / Validate - Code Quality (pull_request)"
|
||||
"CI/CD Pipeline / Validate - Type Check (mypy) (pull_request)"
|
||||
"CI/CD Pipeline / Validate - Migration (alembic) (pull_request)"
|
||||
"CI/CD Pipeline / Frontend Lint (pull_request)"
|
||||
"CI/CD Pipeline / PR Build API Image (pull_request)"
|
||||
"CI/CD Pipeline / PR Build Worker Image (pull_request)"
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
name: Worker Base Image Build
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- develop
|
||||
- main
|
||||
paths:
|
||||
- 'requirements-base.txt'
|
||||
- 'requirements-worker.txt'
|
||||
- 'infra/docker/worker-base-builder.Dockerfile'
|
||||
- 'infra/docker/worker-base-runtime.Dockerfile'
|
||||
workflow_dispatch: # 支持手动触发
|
||||
|
||||
jobs:
|
||||
build-worker-base:
|
||||
name: Build Worker Base Images
|
||||
runs-on: runtime-builder
|
||||
timeout-minutes: 30
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- name: builder
|
||||
dockerfile: infra/docker/worker-base-builder.Dockerfile
|
||||
image_name: worker-base-builder
|
||||
cache_name: worker-base-builder-cache
|
||||
- name: runtime
|
||||
dockerfile: infra/docker/worker-base-runtime.Dockerfile
|
||||
image_name: worker-base-runtime
|
||||
cache_name: worker-base-runtime-cache
|
||||
steps:
|
||||
- name: Checkout code
|
||||
shell: sh
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
curl -sH "Authorization: token $GITHUB_TOKEN" "${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/raw/scripts/ci/step_checkout.sh?ref=${GITHUB_SHA}" | bash
|
||||
|
||||
- name: Docker login to Registry
|
||||
shell: sh
|
||||
env:
|
||||
ACR_USERNAME: ${{ secrets.ACR_USERNAME }}
|
||||
ACR_PASSWORD: ${{ secrets.ACR_PASSWORD }}
|
||||
GITEA_REGISTRY_USER: xiaoxia
|
||||
GITEA_REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }}
|
||||
run: |
|
||||
set -eu
|
||||
for i in 1 2 3; do
|
||||
echo "=== Docker login 尝试 $i/3 ==="
|
||||
if printf '%s' "${ACR_PASSWORD}" | docker login xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com -u "${ACR_USERNAME}" --password-stdin && docker login git.xiaoxiajianji.com -u "${GITEA_REGISTRY_USER}" -p "${GITEA_REGISTRY_TOKEN}"; then
|
||||
echo "✅ Docker login successful"
|
||||
break
|
||||
fi
|
||||
echo "❌ Docker login 失败(尝试 $i/3),5s 后重试..."
|
||||
sleep 5
|
||||
done
|
||||
|
||||
- name: Setup buildx builder
|
||||
shell: sh
|
||||
run: |
|
||||
set -eu
|
||||
BUILDER_NAME="ci-builder-${GITHUB_RUN_ID}-${{ matrix.name }}"
|
||||
if ! docker buildx inspect "$BUILDER_NAME" > /dev/null 2>&1; then
|
||||
docker buildx create --use --name "$BUILDER_NAME" --driver docker-container
|
||||
echo "Created $BUILDER_NAME"
|
||||
else
|
||||
docker buildx use "$BUILDER_NAME"
|
||||
echo "Using existing $BUILDER_NAME"
|
||||
fi
|
||||
docker buildx inspect --bootstrap
|
||||
|
||||
- name: Build and push base image
|
||||
shell: sh
|
||||
run: |
|
||||
set -eu
|
||||
REGISTRY="xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com/xiaoxiakeji"
|
||||
IMAGE_TAG="${REGISTRY}/${{ matrix.image_name }}:latest"
|
||||
SAFE_REF_NAME=$(echo "${GITHUB_REF_NAME}" | tr '/' '-')
|
||||
CACHE_REF="${REGISTRY}/${{ matrix.cache_name }}:${SAFE_REF_NAME}"
|
||||
|
||||
echo "=== Building ${{ matrix.name }} base image ==="
|
||||
echo "Image: ${IMAGE_TAG}"
|
||||
echo "Cache: ${CACHE_REF}"
|
||||
|
||||
# 用通用构建脚本
|
||||
bash scripts/ci/docker_build_push.sh ${{ matrix.dockerfile }} "${IMAGE_TAG}" "${CACHE_REF}"
|
||||
|
||||
# 同时推送到 Gitea Packages 作为备份(可选)
|
||||
GITEA_IMAGE="git.xiaoxiajianji.com/xiaoxia-saas/${{ matrix.image_name }}:latest"
|
||||
docker tag "${IMAGE_TAG}" "${GITEA_IMAGE}"
|
||||
docker push "${GITEA_IMAGE}" || echo "Gitea Packages push failed (non-fatal)"
|
||||
|
||||
echo ""
|
||||
echo "✅ ${{ matrix.name }} base image built and pushed"
|
||||
|
||||
- name: Cleanup buildx builder
|
||||
if: always()
|
||||
shell: sh
|
||||
run: |
|
||||
docker buildx rm "ci-builder-${GITHUB_RUN_ID}-${{ matrix.name }}" 2>/dev/null || true
|
||||
docker buildx prune -f 2>/dev/null || true
|
||||
echo "Builder cleanup done"
|
||||
@@ -0,0 +1,43 @@
|
||||
# ============================================================
|
||||
# Worker Builder 基础镜像
|
||||
# 预编译:编译工具 + 基础依赖 + Worker大包
|
||||
# 当 requirements-base.txt 或 requirements-worker.txt 变更时重新构建
|
||||
# 业务构建从此镜像开始,只需要安装业务依赖,节省15+分钟
|
||||
# ============================================================
|
||||
|
||||
FROM git.xiaoxiajianji.com/xiaoxia/base/python:3.12-slim
|
||||
|
||||
# 使用阿里云镜像加速
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || \
|
||||
sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true
|
||||
|
||||
# 安装编译工具
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
g++ \
|
||||
python3-dev \
|
||||
binutils \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 创建 venv
|
||||
RUN python -m venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
|
||||
WORKDIR /tmp
|
||||
|
||||
# 基础依赖(变化极少)
|
||||
COPY requirements-base.txt /tmp/requirements-base.txt
|
||||
RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
|
||||
pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com \
|
||||
-r /tmp/requirements-base.txt \
|
||||
&& rm /tmp/requirements-base.txt
|
||||
|
||||
# Worker 大包(变化少)
|
||||
COPY requirements-worker.txt /tmp/requirements-worker.txt
|
||||
RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
|
||||
pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com \
|
||||
-r /tmp/requirements-worker.txt \
|
||||
&& rm /tmp/requirements-worker.txt
|
||||
|
||||
# 预先做一次 strip(基础层瘦身,业务层增量)
|
||||
RUN find /opt/venv -name "*.so" -type f -exec strip --strip-all {} \; 2>/dev/null || true
|
||||
@@ -0,0 +1,17 @@
|
||||
# ============================================================
|
||||
# Worker Runtime 基础镜像
|
||||
# 预安装:ffmpeg + 运行时依赖
|
||||
# 变化极少,业务构建从此镜像开始
|
||||
# ============================================================
|
||||
|
||||
FROM git.xiaoxiajianji.com/xiaoxia/base/python:3.12-slim
|
||||
|
||||
# 使用阿里云镜像加速
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || \
|
||||
sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true
|
||||
|
||||
# 运行时依赖:ffmpeg + opencv需要的libglib
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ffmpeg \
|
||||
libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
@@ -1,88 +1,43 @@
|
||||
# ============================================================
|
||||
# Worker Dockerfile - 优化版(多阶段构建 + 镜像瘦身 + cache mount加速)
|
||||
# 优化项:
|
||||
# 1. 多阶段构建:builder 阶段安装编译依赖,runtime 阶段只保留运行时
|
||||
# 2. ffmpeg 通过 apt 安装(阿里云镜像加速,几秒完成,稳定可靠)
|
||||
# 3. Python 依赖瘦身:strip .so 调试符号 + 清理测试文件 + 清理缓存
|
||||
# 4. pip cache mount:加速依赖下载(跨构建共享pip wheel缓存)
|
||||
# Worker Dockerfile - 分层缓存优化版
|
||||
# 优化:基础依赖 + Worker大包预构建为基础镜像,业务构建仅叠加业务依赖
|
||||
# 基础镜像:worker-base-builder / worker-base-runtime
|
||||
# 预计节省:依赖不变时构建时间从23min降至5min以内
|
||||
# ============================================================
|
||||
|
||||
# ==================== Builder 阶段 ====================
|
||||
FROM git.xiaoxiajianji.com/xiaoxia/base/python:3.12-slim AS builder
|
||||
# 从预构建的builder基础镜像开始,已经包含:
|
||||
# - 编译工具 (gcc/g++/python3-dev/binutils)
|
||||
# - requirements-base.txt 全部依赖
|
||||
# - requirements-worker.txt 全部依赖 (numpy/scipy/opencv)
|
||||
# - 预strip的.so文件
|
||||
FROM xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com/xiaoxiakeji/worker-base-builder:latest AS builder
|
||||
|
||||
# 使用阿里云镜像加速
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || \
|
||||
sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true
|
||||
|
||||
# 安装编译工具(仅 builder 需要)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
gcc \
|
||||
g++ \
|
||||
python3-dev \
|
||||
binutils \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
|
||||
# ---- 安装 Python 依赖 ----
|
||||
WORKDIR /tmp
|
||||
|
||||
# 创建 venv
|
||||
RUN python -m venv /opt/venv
|
||||
ENV PATH="/opt/venv/bin:$PATH"
|
||||
|
||||
# 基础依赖
|
||||
COPY requirements-base.txt /tmp/requirements-base.txt
|
||||
RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
|
||||
pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com \
|
||||
-r /tmp/requirements-base.txt \
|
||||
&& rm /tmp/requirements-base.txt
|
||||
WORKDIR /tmp
|
||||
|
||||
# Worker 专属大包
|
||||
COPY requirements-worker.txt /tmp/requirements-worker.txt
|
||||
RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
|
||||
pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com \
|
||||
-r /tmp/requirements-worker.txt \
|
||||
&& rm /tmp/requirements-worker.txt
|
||||
|
||||
# 业务依赖
|
||||
# ---- 安装业务依赖(变化频繁,单独一层)----
|
||||
COPY requirements.txt /tmp/requirements.txt
|
||||
RUN --mount=type=cache,target=/root/.cache/pip,sharing=locked \
|
||||
pip install --no-cache-dir -i https://mirrors.aliyun.com/pypi/simple/ --trusted-host mirrors.aliyun.com \
|
||||
-r /tmp/requirements.txt \
|
||||
&& rm /tmp/requirements.txt
|
||||
|
||||
# ---- Python 依赖瘦身 ----
|
||||
# 1. strip .so 文件的调试符号(节省约 80-100MB)
|
||||
# ---- 增量瘦身(只处理新增的业务依赖)----
|
||||
RUN find /opt/venv -name "*.so" -type f -exec strip --strip-all {} \; 2>/dev/null || true
|
||||
|
||||
# 2. 清理测试文件(节省约 20MB)
|
||||
RUN find /opt/venv -type d -name "tests" -exec rm -rf {} + 2>/dev/null; \
|
||||
find /opt/venv -type d -name "test" -exec rm -rf {} + 2>/dev/null; \
|
||||
find /opt/venv -name "test_*.py" -delete 2>/dev/null || true
|
||||
|
||||
# 3. 清理 .pyc 缓存和 __pycache__(节省约 10MB,运行时按需生成)
|
||||
RUN find /opt/venv -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null; \
|
||||
find /opt/venv -name "*.pyc" -delete 2>/dev/null || true
|
||||
|
||||
# 4. 清理 dist-info 中的文档
|
||||
RUN find /opt/venv -name "*.dist-info" -type d -exec sh -c 'rm -f "$1"/DESCRIPTION.rst "$1"/INSTALLER "$1"/LICENSE* "$1"/WHEEL "$1"/entry_points.txt' _ {} \; 2>/dev/null || true
|
||||
|
||||
# ==================== Runtime 阶段 ====================
|
||||
FROM git.xiaoxiajianji.com/xiaoxia/base/python:3.12-slim AS runtime
|
||||
# 从预构建的runtime基础镜像开始,已经包含:
|
||||
# - ffmpeg
|
||||
# - libglib2.0-0
|
||||
FROM xiaoxia-registry.cn-hangzhou.cr.aliyuncs.com/xiaoxiakeji/worker-base-runtime:latest AS runtime
|
||||
|
||||
# 构建参数:版本号
|
||||
ARG APP_VERSION=dev
|
||||
|
||||
# 使用阿里云镜像加速
|
||||
RUN sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list.d/debian.sources 2>/dev/null || \
|
||||
sed -i 's|deb.debian.org|mirrors.aliyun.com|g' /etc/apt/sources.list 2>/dev/null || true
|
||||
|
||||
# 安装最小运行时依赖(opencv-python-headless 需要 libglib2.0-0)
|
||||
RUN apt-get update && apt-get install -y --no-install-recommends \
|
||||
ffmpeg \
|
||||
libglib2.0-0 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# 从 builder 复制 Python 虚拟环境
|
||||
COPY --from=builder /opt/venv /opt/venv
|
||||
|
||||
|
||||
@@ -280,7 +280,7 @@ def main():
|
||||
|
||||
# 提交修复
|
||||
run("git add -A")
|
||||
run('git commit -m "style: auto-format with black + isort + prettier [ci skip]"')
|
||||
run('git commit -m "style: auto-format with black + isort + prettier"')
|
||||
|
||||
# 推送(head_branch已从ensure_git_repo获取)
|
||||
print(f"\nPR来源分支: {head_branch}")
|
||||
|
||||
@@ -0,0 +1,447 @@
|
||||
#!/usr/bin/env python3
|
||||
"""CI失败诊断增强脚本:自动分类失败原因 + 提取关键错误 + 给出修复建议。
|
||||
# Trigger CI after auto-format fix
|
||||
|
||||
支持的失败类型:
|
||||
1. Lint/格式问题 (ruff/black/eslint/prettier)
|
||||
2. 单元测试失败
|
||||
3. Docker构建失败
|
||||
4. 依赖安装失败 (pip/npm)
|
||||
5. 超时
|
||||
6. 缓存问题
|
||||
7. 数据库/迁移问题
|
||||
8. 网络问题
|
||||
9. 其他
|
||||
|
||||
用法:
|
||||
python3 scripts/ci/ci_failure_diagnosis.py [--job-name "Job Name"] [--log-file /path/to/log]
|
||||
|
||||
如果不传--log-file,会尝试从Gitea API获取失败job的日志。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import urllib.request
|
||||
from dataclasses import dataclass, field
|
||||
from typing import List, Optional
|
||||
|
||||
|
||||
@dataclass
|
||||
class FailureDiagnosis:
|
||||
"""失败诊断结果"""
|
||||
|
||||
category: str # 失败分类
|
||||
category_cn: str # 中文分类名
|
||||
severity: str # 严重程度: high / medium / low
|
||||
summary: str # 一句话摘要
|
||||
error_lines: List[str] = field(default_factory=list) # 关键错误行
|
||||
suggestions: List[str] = field(default_factory=list) # 修复建议
|
||||
auto_fixable: bool = False # 是否可以自动修复
|
||||
related_docs: str = "" # 相关文档链接
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 失败模式定义
|
||||
# ============================================================
|
||||
|
||||
FAILURE_PATTERNS = [
|
||||
# ===== Lint / 格式问题 =====
|
||||
{
|
||||
"pattern": r"(ruff|black|isort)\b.*(error|failed|Error)",
|
||||
"category": "lint_python",
|
||||
"category_cn": "Python代码质量检查",
|
||||
"severity": "low",
|
||||
"summary_contains": ["ruff", "black", "isort"],
|
||||
"suggestions": [
|
||||
"本地运行 `black . && isort . && ruff check --fix .` 自动修复",
|
||||
"使用 `scripts/agent-commit.sh` 提交(自动格式化)",
|
||||
"如确认无误,可加 `# noqa: xxx` 忽略特定规则",
|
||||
],
|
||||
"auto_fixable": True,
|
||||
},
|
||||
{
|
||||
"pattern": r"ESLint|prettier|eslint",
|
||||
"category": "lint_frontend",
|
||||
"category_cn": "前端代码检查",
|
||||
"severity": "low",
|
||||
"summary_contains": ["eslint", "prettier"],
|
||||
"suggestions": [
|
||||
"本地运行 `cd apps/web && npm run lint:fix` 自动修复",
|
||||
"Prettier问题: `cd apps/web && npx prettier --write .`",
|
||||
],
|
||||
"auto_fixable": True,
|
||||
},
|
||||
{
|
||||
"pattern": r"F\d{3}|E\d{3}|W\d{3}.*ruff|ruff.*F\d{3}",
|
||||
"category": "lint_python",
|
||||
"category_cn": "Python代码质量检查",
|
||||
"severity": "low",
|
||||
"suggestions": [
|
||||
"F401: 删除未使用的import",
|
||||
"F841: 删除未使用的变量或加下划线前缀",
|
||||
"E501: 行超长,加 `# noqa: E501`",
|
||||
"F811: 删重复import",
|
||||
"运行 `ruff check --fix .` 自动修复大部分问题",
|
||||
],
|
||||
"auto_fixable": True,
|
||||
},
|
||||
# ===== 单元测试失败 =====
|
||||
{
|
||||
"pattern": r"FAILED|assert.*Error|AssertionError",
|
||||
"category": "unit_test",
|
||||
"category_cn": "单元测试失败",
|
||||
"severity": "high",
|
||||
"suggestions": [
|
||||
"检查相关测试文件,确认是代码问题还是测试用例问题",
|
||||
"本地运行对应测试:`pytest path/to/test.py -v`",
|
||||
"如测试依赖外部服务,检查mock是否正确",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
{
|
||||
"pattern": r"pytest.*failed|\d+ failed.*\d+ passed",
|
||||
"category": "unit_test",
|
||||
"category_cn": "单元测试失败",
|
||||
"severity": "high",
|
||||
"suggestions": [
|
||||
"查看上方日志中的FAILED测试用例",
|
||||
"检查失败断言的期望值 vs 实际值",
|
||||
"新代码影响了现有测试行为,确认是预期内变更吗?",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
# ===== Docker 构建失败 =====
|
||||
{
|
||||
"pattern": r"Dockerfile.*not found|docker build.*failed|ERROR: failed to solve",
|
||||
"category": "docker_build",
|
||||
"category_cn": "Docker构建失败",
|
||||
"severity": "high",
|
||||
"suggestions": [
|
||||
"检查Dockerfile语法是否正确",
|
||||
"检查引用的基础镜像是否存在",
|
||||
"本地运行 `docker build -f path/to/Dockerfile .` 复现",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
{
|
||||
"pattern": r"manifest.*not found|no such image|image.*not found",
|
||||
"category": "docker_build",
|
||||
"category_cn": "镜像不存在",
|
||||
"severity": "medium",
|
||||
"suggestions": [
|
||||
"检查基础镜像名称和tag是否正确",
|
||||
"确认镜像仓库可访问,登录是否有效",
|
||||
"如为新基础镜像,需先手动构建一次基础镜像",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
{
|
||||
"pattern": r"ETXTBSY|text file busy",
|
||||
"category": "docker_build",
|
||||
"category_cn": "文件锁冲突(ETXTBSY)",
|
||||
"severity": "low",
|
||||
"summary": "esbuild并发构建冲突,重试即可",
|
||||
"suggestions": ["偶发问题,点击Rerun重新运行即可", "如频繁出现,检查是否有多个job并发写入同一文件"],
|
||||
"auto_fixable": True,
|
||||
},
|
||||
# ===== 依赖安装失败 =====
|
||||
{
|
||||
"pattern": r"pip install.*error|Could not find a version|No matching distribution",
|
||||
"category": "dependency",
|
||||
"category_cn": "pip依赖安装失败",
|
||||
"severity": "medium",
|
||||
"suggestions": [
|
||||
"检查requirements.txt中的版本号是否正确",
|
||||
"如为新版本刚发布,可能源还没同步,稍后重试",
|
||||
"检查网络连接,可尝试切换pip镜像源",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
{
|
||||
"pattern": r"npm.*ERR|npm install.*failed|E404|ECONNREFUSED.*npm",
|
||||
"category": "dependency",
|
||||
"category_cn": "npm依赖安装失败",
|
||||
"severity": "medium",
|
||||
"suggestions": [
|
||||
"检查package.json中的版本号是否存在",
|
||||
"网络问题:检查npm registry是否可访问",
|
||||
"国内网络建议配置npmmirror镜像源",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
{
|
||||
"pattern": r"Connection refused|timed out|network.*unreachable",
|
||||
"category": "network",
|
||||
"category_cn": "网络问题",
|
||||
"severity": "medium",
|
||||
"summary": "网络连接失败,可能是源站问题或DNS问题",
|
||||
"suggestions": [
|
||||
"点击Rerun重试,网络问题通常是临时的",
|
||||
"如持续失败,检查对应服务是否正常",
|
||||
"检查Runner网络配置",
|
||||
],
|
||||
"auto_fixable": True,
|
||||
},
|
||||
# ===== 超时 =====
|
||||
{
|
||||
"pattern": r"timeout|timed out|exceeded.*time limit|job.*cancelled.*timeout",
|
||||
"category": "timeout",
|
||||
"category_cn": "执行超时",
|
||||
"severity": "medium",
|
||||
"suggestions": [
|
||||
"如首次出现:重试一次,可能是临时性能波动",
|
||||
"频繁出现:检查构建是否变慢了,最近是否加了新依赖",
|
||||
"可适当增加timeout-minutes配置",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
# ===== 数据库/迁移 =====
|
||||
{
|
||||
"pattern": r"alembic.*error|migration.*failed|relation.*does not exist|column.*does not exist",
|
||||
"category": "migration",
|
||||
"category_cn": "数据库迁移失败",
|
||||
"severity": "high",
|
||||
"suggestions": [
|
||||
"检查迁移脚本是否正确,down_revision是否对",
|
||||
"确认数据库中是否有脏数据或残留表",
|
||||
"迁移脚本合并冲突时,重新生成迁移文件",
|
||||
],
|
||||
"auto_fixable": False,
|
||||
},
|
||||
# ===== 缓存问题 =====
|
||||
{
|
||||
"pattern": r"cache.*corrupt|cache.*invalid|snapshot.*not found|failed to compute cache key",
|
||||
"category": "cache",
|
||||
"category_cn": "缓存损坏",
|
||||
"severity": "low",
|
||||
"suggestions": ["构建系统会自动清理损坏缓存并重试,通常无需干预", "如持续失败,手动清理Runner上的缓存目录"],
|
||||
"auto_fixable": True,
|
||||
},
|
||||
# ===== Checkout 失败 =====
|
||||
{
|
||||
"pattern": r"Could not resolve host|fatal:.*repository|SSL.*problem",
|
||||
"category": "checkout",
|
||||
"category_cn": "代码拉取失败",
|
||||
"severity": "low",
|
||||
"suggestions": ["临时网络问题,点击Rerun重试", "如持续失败,检查Gitea服务状态"],
|
||||
"auto_fixable": True,
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
def analyze_log(log_text: str, job_name: str = "") -> FailureDiagnosis:
|
||||
"""分析日志,返回诊断结果"""
|
||||
|
||||
lines = log_text.strip().split("\n")
|
||||
|
||||
# 收集所有匹配的模式
|
||||
matched = []
|
||||
error_lines = []
|
||||
|
||||
for line in lines:
|
||||
line_stripped = line.strip()
|
||||
# 收集ERROR/FAILED/Failed等错误行(最多20行)
|
||||
if re.search(r"(ERROR|FAILED|Error|error:|FAIL:|Traceback)", line_stripped):
|
||||
if len(error_lines) < 20:
|
||||
error_lines.append(line_stripped)
|
||||
|
||||
for pattern_info in FAILURE_PATTERNS:
|
||||
if re.search(pattern_info["pattern"], line_stripped, re.IGNORECASE):
|
||||
matched.append(pattern_info)
|
||||
break # 一行只匹配一个模式
|
||||
|
||||
if not matched:
|
||||
# 未识别的失败类型
|
||||
return FailureDiagnosis(
|
||||
category="unknown",
|
||||
category_cn="未知错误",
|
||||
severity="medium",
|
||||
summary="未识别的失败类型,需要人工查看日志",
|
||||
error_lines=error_lines[:10],
|
||||
suggestions=[
|
||||
"点击'查看失败日志'查看完整日志",
|
||||
"如为偶发问题,可先重试一次",
|
||||
"常见原因:环境问题、配置问题、新增逻辑引入的bug",
|
||||
],
|
||||
auto_fixable=False,
|
||||
)
|
||||
|
||||
# 选最严重、最具体的那个
|
||||
severity_order = {"high": 3, "medium": 2, "low": 1}
|
||||
matched.sort(key=lambda x: severity_order.get(x["severity"], 0), reverse=True)
|
||||
best_match = matched[0]
|
||||
|
||||
# 生成摘要
|
||||
if "summary" in best_match:
|
||||
summary = best_match["summary"]
|
||||
else:
|
||||
summary = f"{best_match['category_cn']}检查失败"
|
||||
if job_name:
|
||||
summary = f"[{job_name}] {summary}"
|
||||
|
||||
# 从error_lines中过滤出与该分类相关的
|
||||
relevant_errors = error_lines[:10]
|
||||
|
||||
return FailureDiagnosis(
|
||||
category=best_match["category"],
|
||||
category_cn=best_match["category_cn"],
|
||||
severity=best_match["severity"],
|
||||
summary=summary,
|
||||
error_lines=relevant_errors,
|
||||
suggestions=best_match["suggestions"],
|
||||
auto_fixable=best_match.get("auto_fixable", False),
|
||||
)
|
||||
|
||||
|
||||
def fetch_failed_job_log(run_id: str, job_id: str, token: str, repo: str) -> Optional[str]:
|
||||
"""从Gitea API获取失败job的日志"""
|
||||
api_base = f"https://git.xiaoxiajianji.com/api/v1/repos/{repo}"
|
||||
|
||||
# 尝试获取job的日志
|
||||
url = f"{api_base}/actions/runs/{run_id}/jobs/{job_id}/log"
|
||||
req = urllib.request.Request(url)
|
||||
req.add_header("Authorization", f"token {token}")
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=15) as resp:
|
||||
return resp.read().decode("utf-8", errors="replace")
|
||||
except Exception as e:
|
||||
print(f"获取日志失败: {e}", file=sys.stderr)
|
||||
return None
|
||||
|
||||
|
||||
def format_diagnosis_markdown(d: FailureDiagnosis, job_name: str = "", run_url: str = "") -> str:
|
||||
"""将诊断结果格式化为飞书卡片markdown"""
|
||||
|
||||
severity_emoji = {"high": "🔴", "medium": "🟡", "low": "🟢"}
|
||||
emoji = severity_emoji.get(d.severity, "⚪")
|
||||
|
||||
lines = []
|
||||
lines.append(f"**分类**: {emoji} {d.category_cn}")
|
||||
lines.append(f"**问题**: {d.summary}")
|
||||
|
||||
if d.error_lines:
|
||||
lines.append("")
|
||||
lines.append("**关键错误行**:")
|
||||
for err in d.error_lines[:5]:
|
||||
# 截断过长的行
|
||||
if len(err) > 150:
|
||||
err = err[:147] + "..."
|
||||
lines.append(f" `{err}`")
|
||||
|
||||
lines.append("")
|
||||
lines.append("**修复建议**:")
|
||||
for i, s in enumerate(d.suggestions[:5], 1):
|
||||
lines.append(f" {i}. {s}")
|
||||
|
||||
if d.auto_fixable:
|
||||
lines.append("")
|
||||
lines.append("💡 **可自动修复**:如格式问题,可尝试点击Rerun让auto-fix自动处理")
|
||||
|
||||
if run_url:
|
||||
lines.append("")
|
||||
lines.append(f"[查看完整日志]({run_url})")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
job_name = os.environ.get("FAILED_JOB", "")
|
||||
run_id = os.environ.get("GITHUB_RUN_ID", "")
|
||||
repo = os.environ.get("GITHUB_REPOSITORY", "xiaoxia/xiaoxia-saas")
|
||||
token = os.environ.get("GITHUB_TOKEN", "")
|
||||
|
||||
# 1. 尝试获取日志
|
||||
log_text = ""
|
||||
|
||||
# 优先从环境变量或文件读取
|
||||
log_file = os.environ.get("CI_LOG_FILE", "")
|
||||
if log_file and os.path.exists(log_file):
|
||||
with open(log_file) as f:
|
||||
log_text = f.read()
|
||||
elif run_id and token:
|
||||
# 尝试从API获取(需要job_id,这里简化处理)
|
||||
pass
|
||||
|
||||
# 如果没有日志,用job_name做粗略分类
|
||||
if not log_text:
|
||||
# 基于job名做初始判断
|
||||
if any(k in job_name.lower() for k in ["validate", "lint", "quality"]):
|
||||
d = FailureDiagnosis(
|
||||
category="lint_general",
|
||||
category_cn="代码质量检查",
|
||||
severity="low",
|
||||
summary=f"{job_name} 检查失败(日志不可用,基于job名初步诊断)",
|
||||
suggestions=["点击查看日志获取具体错误信息", "格式类问题通常可自动修复"],
|
||||
auto_fixable=True,
|
||||
)
|
||||
elif "build" in job_name.lower():
|
||||
d = FailureDiagnosis(
|
||||
category="build_general",
|
||||
category_cn="构建失败",
|
||||
severity="high",
|
||||
summary=f"{job_name} 构建失败(日志不可用)",
|
||||
suggestions=["点击查看日志获取具体构建错误", "常见原因:Dockerfile错误、依赖安装失败、网络问题"],
|
||||
auto_fixable=False,
|
||||
)
|
||||
elif "test" in job_name.lower():
|
||||
d = FailureDiagnosis(
|
||||
category="test_general",
|
||||
category_cn="测试失败",
|
||||
severity="high",
|
||||
summary=f"{job_name} 测试失败(日志不可用)",
|
||||
suggestions=["点击查看日志获取具体失败的测试用例", "检查最近代码改动是否影响了测试"],
|
||||
auto_fixable=False,
|
||||
)
|
||||
elif "deploy" in job_name.lower():
|
||||
d = FailureDiagnosis(
|
||||
category="deploy_general",
|
||||
category_cn="部署失败",
|
||||
severity="high",
|
||||
summary=f"{job_name} 部署失败(日志不可用)",
|
||||
suggestions=["检查目标服务器状态和网络", "检查镜像是否正确推送", "查看服务器上的容器日志"],
|
||||
auto_fixable=False,
|
||||
)
|
||||
else:
|
||||
d = FailureDiagnosis(
|
||||
category="unknown",
|
||||
category_cn="未知错误",
|
||||
severity="medium",
|
||||
summary=f"{job_name} 失败",
|
||||
suggestions=["点击查看日志获取详细信息"],
|
||||
auto_fixable=False,
|
||||
)
|
||||
else:
|
||||
d = analyze_log(log_text, job_name)
|
||||
|
||||
# 输出诊断结果
|
||||
run_url = f"https://git.xiaoxiajianji.com/{repo}/actions/runs/{run_id}" if run_id else ""
|
||||
|
||||
print("=" * 60)
|
||||
print(" CI 失败诊断报告")
|
||||
print("=" * 60)
|
||||
print()
|
||||
print(format_diagnosis_markdown(d, job_name, run_url))
|
||||
print()
|
||||
print("=" * 60)
|
||||
|
||||
# 将诊断结果写入文件(供通知脚本读取)
|
||||
output_file = os.environ.get("DIAGNOSIS_OUTPUT", "/tmp/ci_diagnosis.json")
|
||||
result = {
|
||||
"category": d.category,
|
||||
"category_cn": d.category_cn,
|
||||
"severity": d.severity,
|
||||
"summary": d.summary,
|
||||
"error_lines": d.error_lines,
|
||||
"suggestions": d.suggestions,
|
||||
"auto_fixable": d.auto_fixable,
|
||||
}
|
||||
with open(output_file, "w") as f:
|
||||
json.dump(result, f, ensure_ascii=False, indent=2)
|
||||
print(f"\n诊断结果已保存到: {output_file}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,417 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
CI重复失败检测脚本
|
||||
- 扫描最近N天的CI失败
|
||||
- 按job名称分组统计失败率
|
||||
- 识别高失败率job(系统性故障)
|
||||
- 飞书通知告警
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from collections import defaultdict
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
|
||||
def get_env(name, default=None, required=False):
|
||||
val = os.environ.get(name, default)
|
||||
if required and not val:
|
||||
print(f"❌ 缺少环境变量: {name}")
|
||||
sys.exit(1)
|
||||
return val
|
||||
|
||||
|
||||
GITEA_URL = get_env("GITEA_URL", "https://git.xiaoxiajianji.com")
|
||||
GITEA_TOKEN = get_env("GITEA_API_TOKEN", required=False) or get_env("GITHUB_TOKEN", "")
|
||||
REPO = get_env("GITEA_REPO", "xiaoxia/xiaoxia-saas")
|
||||
DAYS = int(get_env("FAIL_CHECK_DAYS", "7"))
|
||||
FAIL_THRESHOLD = int(get_env("FAIL_THRESHOLD", 3)) # 失败次数阈值
|
||||
FAIL_RATE_THRESHOLD = float(get_env("FAIL_RATE_THRESHOLD", "30")) # 失败率阈值%
|
||||
CONSECUTIVE_FAIL_THRESHOLD = int(get_env("CONSECUTIVE_FAIL_THRESHOLD", "3")) # 连续失败阈值
|
||||
WEBHOOK = get_env("CI_NOTIFY_WEBHOOK", "")
|
||||
|
||||
|
||||
def api_get(path):
|
||||
"""调用Gitea API"""
|
||||
url = f"{GITEA_URL}/api/v1{path}"
|
||||
req = urllib.request.Request(url)
|
||||
if GITEA_TOKEN:
|
||||
req.add_header("Authorization", f"token {GITEA_TOKEN}")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read())
|
||||
except urllib.error.HTTPError as e:
|
||||
print(f" HTTP {e.code}: {path}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f" 错误: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def fetch_recent_runs(days=7, per_page=50, max_pages=10):
|
||||
"""获取最近N天的runs"""
|
||||
since = (datetime.now(timezone.utc) - timedelta(days=days)).isoformat()
|
||||
all_runs = []
|
||||
|
||||
for page in range(1, max_pages + 1):
|
||||
path = f"/repos/{REPO}/actions/runs?page={page}&limit={per_page}"
|
||||
data = api_get(path)
|
||||
if not data:
|
||||
break
|
||||
|
||||
runs = data.get("workflow_runs", data.get("runs", []))
|
||||
if not runs:
|
||||
break
|
||||
|
||||
# 检查时间范围(Gitea用started_at,格式2026-07-22T10:58:10+08:00)
|
||||
oldest = None
|
||||
for r in runs:
|
||||
started = r.get("started_at", r.get("created_at", ""))
|
||||
if started and started >= since:
|
||||
all_runs.append(r)
|
||||
else:
|
||||
oldest = started
|
||||
|
||||
if oldest and oldest < since:
|
||||
break
|
||||
|
||||
if len(runs) < per_page:
|
||||
break
|
||||
|
||||
return all_runs
|
||||
|
||||
|
||||
def fetch_run_jobs(run_id):
|
||||
"""获取run的所有jobs"""
|
||||
path = f"/repos/{REPO}/actions/runs/{run_id}/jobs"
|
||||
data = api_get(path)
|
||||
if not data:
|
||||
return []
|
||||
return data.get("jobs", [])
|
||||
|
||||
|
||||
def analyze_failures(runs):
|
||||
"""
|
||||
分析失败情况
|
||||
|
||||
返回:
|
||||
- job_stats: {job_name: {total, success, failure, skipped, failure_rate, failures: [...]}}
|
||||
- consecutive_failures: {job_name: current_streak, max_streak, last_status}
|
||||
"""
|
||||
job_stats = defaultdict(
|
||||
lambda: {
|
||||
"total": 0,
|
||||
"success": 0,
|
||||
"failure": 0,
|
||||
"error": 0,
|
||||
"skipped": 0,
|
||||
"cancelled": 0,
|
||||
"failures": [],
|
||||
}
|
||||
)
|
||||
|
||||
# 按时间正序排列(旧→新)用于连续失败计算
|
||||
sorted_runs = sorted(runs, key=lambda r: r.get("started_at", r.get("created_at", "")))
|
||||
|
||||
# 连续失败跟踪 {job_name: streak}
|
||||
consecutive = defaultdict(lambda: {"current": 0, "max": 0, "last_run": None})
|
||||
|
||||
for run in sorted_runs:
|
||||
run_id = run.get("id")
|
||||
run_status = run.get("status", "")
|
||||
run_conclusion = run.get("conclusion", "")
|
||||
run_started = run.get("started_at", run.get("created_at", ""))
|
||||
event = run.get("event", "")
|
||||
|
||||
# 只统计pull_request和push事件的CI
|
||||
if event not in ("pull_request", "push"):
|
||||
continue
|
||||
|
||||
jobs = fetch_run_jobs(run_id)
|
||||
|
||||
for job in jobs:
|
||||
name = job.get("name", "")
|
||||
status = job.get("status", "")
|
||||
conclusion = job.get("conclusion", "")
|
||||
|
||||
# 跳过非CI核心job(如AI Code Review、Preview等)
|
||||
skip_prefixes = ("AI Code Review", "Preview", "PR Automation", "Auto")
|
||||
if any(name.startswith(p) for p in skip_prefixes):
|
||||
continue
|
||||
|
||||
stats = job_stats[name]
|
||||
stats["total"] += 1
|
||||
|
||||
if conclusion == "success":
|
||||
stats["success"] += 1
|
||||
consecutive[name]["current"] = 0
|
||||
elif conclusion == "failure":
|
||||
stats["failure"] += 1
|
||||
stats["failures"].append(
|
||||
{
|
||||
"run_id": run_id,
|
||||
"time": run_started,
|
||||
"event": event,
|
||||
}
|
||||
)
|
||||
consecutive[name]["current"] += 1
|
||||
if consecutive[name]["current"] > consecutive[name]["max"]:
|
||||
consecutive[name]["max"] = consecutive[name]["current"]
|
||||
consecutive[name]["last_run"] = run_id
|
||||
elif conclusion == "error":
|
||||
stats["error"] += 1
|
||||
# error也算失败的一种
|
||||
consecutive[name]["current"] += 1
|
||||
if consecutive[name]["current"] > consecutive[name]["max"]:
|
||||
consecutive[name]["max"] = consecutive[name]["current"]
|
||||
elif conclusion == "skipped":
|
||||
stats["skipped"] += 1
|
||||
# skipped不算也不打断连续失败
|
||||
elif conclusion == "cancelled":
|
||||
stats["cancelled"] += 1
|
||||
# cancelled不算失败也不打断
|
||||
|
||||
# 计算失败率
|
||||
for name, stats in job_stats.items():
|
||||
total_actual = stats["total"] - stats["skipped"] - stats["cancelled"]
|
||||
if total_actual > 0:
|
||||
stats["failure_rate"] = round((stats["failure"] + stats["error"]) / total_actual * 100, 1)
|
||||
else:
|
||||
stats["failure_rate"] = 0.0
|
||||
|
||||
return dict(job_stats), dict(consecutive)
|
||||
|
||||
|
||||
def find_high_failures(job_stats, consecutive):
|
||||
"""
|
||||
找出高风险job
|
||||
|
||||
告警级别:
|
||||
- critical: 连续失败 >= CONSECUTIVE_FAIL_THRESHOLD,或 失败率>=50%且失败次数>=5
|
||||
- warning: 失败率>=FAIL_RATE_THRESHOLD且失败次数>=FAIL_THRESHOLD
|
||||
- info: 失败次数>=2
|
||||
"""
|
||||
critical = []
|
||||
warning = []
|
||||
info = []
|
||||
|
||||
for name, stats in job_stats.items():
|
||||
fail_count = stats["failure"] + stats["error"]
|
||||
rate = stats["failure_rate"]
|
||||
streak = consecutive.get(name, {}).get("current", 0)
|
||||
max_streak = consecutive.get(name, {}).get("max", 0)
|
||||
|
||||
issue = {
|
||||
"name": name,
|
||||
"fail_count": fail_count,
|
||||
"total": stats["total"],
|
||||
"failure_rate": rate,
|
||||
"current_streak": streak,
|
||||
"max_streak": max_streak,
|
||||
"recent_failures": stats["failures"][-5:], # 最近5次
|
||||
}
|
||||
|
||||
if streak >= CONSECUTIVE_FAIL_THRESHOLD or (rate >= 50 and fail_count >= 5):
|
||||
critical.append(issue)
|
||||
elif rate >= FAIL_RATE_THRESHOLD and fail_count >= FAIL_THRESHOLD:
|
||||
warning.append(issue)
|
||||
elif fail_count >= 2:
|
||||
info.append(issue)
|
||||
|
||||
# 按失败次数倒序
|
||||
critical.sort(key=lambda x: x["fail_count"], reverse=True)
|
||||
warning.sort(key=lambda x: x["fail_count"], reverse=True)
|
||||
info.sort(key=lambda x: x["fail_count"], reverse=True)
|
||||
|
||||
return critical, warning, info
|
||||
|
||||
|
||||
def generate_report(critical, warning, info, days, total_runs):
|
||||
"""生成Markdown报告"""
|
||||
lines = []
|
||||
lines.append("# CI重复失败检测报告")
|
||||
lines.append("")
|
||||
lines.append(f"**统计周期**: 最近{days}天")
|
||||
lines.append(f"**扫描Runs**: {total_runs}个")
|
||||
lines.append(f"**生成时间**: {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')}")
|
||||
lines.append("")
|
||||
|
||||
lines.append(f"## 概览")
|
||||
lines.append("")
|
||||
lines.append(f"| 级别 | 数量 |")
|
||||
lines.append(f"|------|------|")
|
||||
lines.append(f"| 🔴 严重 (连续失败≥{CONSECUTIVE_FAIL_THRESHOLD}次 或 失败率≥50%) | {len(critical)} |")
|
||||
lines.append(f"| 🟡 警告 (失败率≥{FAIL_RATE_THRESHOLD}% 且 失败≥{FAIL_THRESHOLD}次) | {len(warning)} |")
|
||||
lines.append(f"| 🔵 关注 (失败≥2次) | {len(info)} |")
|
||||
lines.append("")
|
||||
|
||||
if critical:
|
||||
lines.append("## 🔴 严重问题")
|
||||
lines.append("")
|
||||
for item in critical:
|
||||
lines.append(f"### {item['name']}")
|
||||
lines.append("")
|
||||
lines.append(f"- 失败次数: **{item['fail_count']}** / {item['total']} 次运行")
|
||||
lines.append(f"- 失败率: **{item['failure_rate']}%**")
|
||||
lines.append(f"- 当前连续失败: **{item['current_streak']}** 次 (历史最高: {item['max_streak']} 次)")
|
||||
lines.append("")
|
||||
if item["recent_failures"]:
|
||||
lines.append("最近失败:")
|
||||
lines.append("")
|
||||
for f in item["recent_failures"]:
|
||||
lines.append(f"- [{f['time'][:16]}] run #{f['run_id']} ({f['event']})")
|
||||
lines.append("")
|
||||
|
||||
if warning:
|
||||
lines.append("## 🟡 警告")
|
||||
lines.append("")
|
||||
for item in warning:
|
||||
lines.append(
|
||||
f"- **{item['name']}**: {item['fail_count']}次失败 / {item['total']}次运行 ({item['failure_rate']}%)"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
if info:
|
||||
lines.append("## 🔵 关注列表")
|
||||
lines.append("")
|
||||
lines.append("| Job名称 | 失败次数 | 总次数 | 失败率 | 当前连续 |")
|
||||
lines.append("|---------|----------|--------|--------|----------|")
|
||||
for item in info[:20]: # 最多显示20个
|
||||
lines.append(
|
||||
f"| {item['name']} | {item['fail_count']} | {item['total']} | {item['failure_rate']}% | {item['current_streak']} |"
|
||||
)
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def send_feishu_notification(critical, warning, info, days):
|
||||
"""发送飞书通知"""
|
||||
if not WEBHOOK:
|
||||
print(" ⚠️ 未配置WEBHOOK,跳过飞书通知")
|
||||
return False
|
||||
|
||||
total_issues = len(critical) + len(warning) + len(info)
|
||||
if total_issues == 0:
|
||||
print(" ✅ 无异常,不发送通知")
|
||||
return True
|
||||
|
||||
level = "🔴 严重告警" if critical else "🟡 警告" if warning else "🔵 关注"
|
||||
|
||||
title = f"CI重复失败检测 - {level}"
|
||||
text = f"统计周期: 最近{days}天\n\n"
|
||||
|
||||
if critical:
|
||||
text += "【严重问题】\n"
|
||||
for item in critical[:5]:
|
||||
text += f"• {item['name']}\n"
|
||||
text += f" 失败 {item['fail_count']}/{item['total']} ({item['failure_rate']}%) 连续{item['current_streak']}次\n"
|
||||
if len(critical) > 5:
|
||||
text += f" ...还有{len(critical)-5}个\n"
|
||||
text += "\n"
|
||||
|
||||
if warning:
|
||||
text += "【警告】\n"
|
||||
for item in warning[:5]:
|
||||
text += f"• {item['name']}: {item['fail_count']}次失败 ({item['failure_rate']}%)\n"
|
||||
if len(warning) > 5:
|
||||
text += f" ...还有{len(warning)-5}个\n"
|
||||
text += "\n"
|
||||
|
||||
if info and not critical and not warning:
|
||||
text += "【关注列表】\n"
|
||||
for item in info[:10]:
|
||||
text += f"• {item['name']}: {item['fail_count']}次失败\n"
|
||||
text += "\n"
|
||||
|
||||
text += f"共发现 {total_issues} 个异常job"
|
||||
|
||||
payload = {"msg_type": "text", "content": {"text": f"{title}\n\n{text}"}}
|
||||
|
||||
data = json.dumps(payload).encode()
|
||||
req = urllib.request.Request(WEBHOOK, data=data, headers={"Content-Type": "application/json"})
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
result = json.loads(resp.read())
|
||||
if result.get("code") == 0 or result.get("StatusCode") == 0:
|
||||
print(" ✅ 飞书通知已发送")
|
||||
return True
|
||||
else:
|
||||
print(f" ⚠️ 飞书返回: {result}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f" ❌ 飞书通知失败: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def main():
|
||||
print(f"=== CI重复失败检测 ===")
|
||||
print(f"统计周期: 最近{DAYS}天")
|
||||
print(f"仓库: {REPO}")
|
||||
print()
|
||||
|
||||
print("1. 获取最近的Runs...")
|
||||
runs = fetch_recent_runs(days=DAYS)
|
||||
print(f" 找到 {len(runs)} 个runs")
|
||||
|
||||
if not runs:
|
||||
print("⚠️ 没有找到runs,退出")
|
||||
return
|
||||
|
||||
print()
|
||||
print("2. 分析job失败情况(可能需要点时间)...")
|
||||
job_stats, consecutive = analyze_failures(runs)
|
||||
print(f" 共统计 {len(job_stats)} 个job")
|
||||
|
||||
print()
|
||||
print("3. 识别高风险job...")
|
||||
critical, warning, info = find_high_failures(job_stats, consecutive)
|
||||
print(f" 🔴 严重: {len(critical)}")
|
||||
print(f" 🟡 警告: {len(warning)}")
|
||||
print(f" 🔵 关注: {len(info)}")
|
||||
|
||||
print()
|
||||
print("4. 生成报告...")
|
||||
report = generate_report(critical, warning, info, DAYS, len(runs))
|
||||
|
||||
# 保存报告
|
||||
report_path = os.environ.get("REPORT_PATH", f"/tmp/ci_failure_report_{int(time.time())}.md")
|
||||
with open(report_path, "w") as f:
|
||||
f.write(report)
|
||||
print(f" 报告已保存: {report_path}")
|
||||
|
||||
# 打印摘要
|
||||
print()
|
||||
print("=== 摘要 ===")
|
||||
if critical:
|
||||
print("🔴 严重问题:")
|
||||
for item in critical[:5]:
|
||||
print(
|
||||
f" {item['name']}: {item['fail_count']}次失败, {item['failure_rate']}%, 连续{item['current_streak']}次"
|
||||
)
|
||||
if warning:
|
||||
print("🟡 警告:")
|
||||
for item in warning[:5]:
|
||||
print(f" {item['name']}: {item['fail_count']}次失败, {item['failure_rate']}%")
|
||||
|
||||
print()
|
||||
print("5. 发送飞书通知...")
|
||||
send_feishu_notification(critical, warning, info, DAYS)
|
||||
|
||||
print()
|
||||
print("✅ 检测完成")
|
||||
|
||||
# 有严重问题时退出码非零,方便workflow标记
|
||||
if critical:
|
||||
sys.exit(2)
|
||||
elif warning:
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -2,3 +2,5 @@
|
||||
# CI 公共步骤:Job 开始计时
|
||||
echo "JOB_START_TIME=$(date +%s)" >> $GITHUB_ENV
|
||||
echo "Job started at $(date)"
|
||||
# trigger CI run for PR validation
|
||||
# trigger CI - worker dood fallback fix test
|
||||
@@ -0,0 +1,186 @@
|
||||
#!/bin/bash
|
||||
# CI Validate: 代码质量与安全扫描(并行Job 1/3)
|
||||
# 包含:密钥扫描、格式检查、安全扫描、依赖漏洞、死代码检测、脚本语法校验
|
||||
set -eu
|
||||
|
||||
echo "=== CI Validate: 代码质量与安全扫描 ==="
|
||||
|
||||
# --- 密钥检测 ---
|
||||
echo ""
|
||||
echo "=== [1/6] Secret detection (detect-secrets) ==="
|
||||
python3 -m pip install -q detect-secrets
|
||||
detect-secrets --version
|
||||
|
||||
detect-secrets scan \
|
||||
--all-files \
|
||||
--exclude-files '(^|/)(tests|test|e2e|__tests__|spec|docs|node_modules|site-packages|migrations|alembic|.gitea|.git|.pytest_cache|.next|dist|build)/' \
|
||||
--exclude-files '\.(md|rst|txt|lock|example|sample|min\.js|min\.css|spec\.ts|test\.ts|test\.py)$' \
|
||||
--exclude-files '(package-lock|yarn\.lock|poetry\.lock|Pipfile\.lock)$' \
|
||||
--disable-plugin Base64HighEntropyString \
|
||||
--disable-plugin HexHighEntropyString \
|
||||
--disable-plugin BasicAuthDetector \
|
||||
--disable-plugin KeywordDetector \
|
||||
--disable-plugin IPPublicDetector \
|
||||
> /tmp/secrets-scan.json 2>&1
|
||||
|
||||
FOUND=$(python3 -c "
|
||||
import json
|
||||
try:
|
||||
with open('/tmp/secrets-scan.json') as f:
|
||||
data = json.load(f)
|
||||
results = data.get('results', {})
|
||||
total = sum(len(v) for v in results.values())
|
||||
print(total)
|
||||
except Exception:
|
||||
print('error')
|
||||
")
|
||||
|
||||
echo "Secrets detected: $FOUND"
|
||||
if [ "$FOUND" != "0" ] && [ "$FOUND" != "error" ]; then
|
||||
echo ""
|
||||
echo "=== Secret details ==="
|
||||
python3 -c "
|
||||
import json
|
||||
with open('/tmp/secrets-scan.json') as f:
|
||||
data = json.load(f)
|
||||
for fpath, items in data.get('results', {}).items():
|
||||
for item in items:
|
||||
line = item.get('line_number', '?')
|
||||
stype = item.get('type', '?')
|
||||
hashed = item.get('hashed_secret', '')[:16]
|
||||
print(f' {fpath}:{line} [{stype}] {hashed}...')
|
||||
"
|
||||
echo ""
|
||||
echo "ERROR: Potential secrets detected in code!"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ Secret scan passed"
|
||||
|
||||
# --- 增量/全量模式判断 ---
|
||||
echo ""
|
||||
echo "=== [2/6] Code quality checks ==="
|
||||
SCAN_MODE="full"
|
||||
CHANGED_PY_FILES=""
|
||||
|
||||
if [ "${GITHUB_EVENT_NAME:-}" = "pull_request" ] && [ -n "${GITHUB_REF_NAME:-}" ] && [ -n "${GITHUB_TOKEN:-}" ]; then
|
||||
PR_NUMBER=$(echo "$GITHUB_REF" | sed 's|refs/pull/||; s|/.*||')
|
||||
API_URL="${GITHUB_API_URL}/repos/${GITHUB_REPOSITORY}/pulls/${PR_NUMBER}/files?limit=100"
|
||||
set +e
|
||||
RESPONSE=$(curl -s -w "\n%{http_code}" -H "Authorization: token ${GITHUB_TOKEN}" "$API_URL")
|
||||
HTTP_CODE=$(echo "$RESPONSE" | tail -n1)
|
||||
BODY=$(echo "$RESPONSE" | sed '$d')
|
||||
set -e
|
||||
if [ "$HTTP_CODE" = "200" ]; then
|
||||
CHANGED_PY_FILES=$(echo "$BODY" | python3 -c "
|
||||
import json, sys
|
||||
try:
|
||||
files = json.load(sys.stdin)
|
||||
py_files = [f['filename'] for f in files if f['filename'].endswith('.py') and f['status'] != 'removed']
|
||||
print(' '.join(py_files))
|
||||
except Exception:
|
||||
print('')
|
||||
")
|
||||
if [ -n "$CHANGED_PY_FILES" ]; then
|
||||
SCAN_MODE="incremental"
|
||||
echo "Incremental mode: $(echo "$CHANGED_PY_FILES" | wc -w) Python files changed"
|
||||
else
|
||||
SCAN_MODE="skip_py"
|
||||
echo "No Python files changed in this PR"
|
||||
fi
|
||||
else
|
||||
echo "WARN: API returned HTTP $HTTP_CODE, falling back to full scan"
|
||||
fi
|
||||
else
|
||||
echo "Full scan mode (not a PR event)"
|
||||
fi
|
||||
|
||||
if [ "$SCAN_MODE" = "incremental" ]; then
|
||||
# 防御性过滤
|
||||
EXISTING_PY_FILES=""
|
||||
for f in $CHANGED_PY_FILES; do
|
||||
if [ -f "$f" ]; then
|
||||
if [ -z "$EXISTING_PY_FILES" ]; then
|
||||
EXISTING_PY_FILES="$f"
|
||||
else
|
||||
EXISTING_PY_FILES="$EXISTING_PY_FILES $f"
|
||||
fi
|
||||
fi
|
||||
done
|
||||
CHANGED_PY_FILES="$EXISTING_PY_FILES"
|
||||
|
||||
python3 -m compileall -q $CHANGED_PY_FILES
|
||||
python3 -m black --check --fast $CHANGED_PY_FILES
|
||||
python3 -m isort --check-only $CHANGED_PY_FILES
|
||||
RUFF_FILES=$(echo "$CHANGED_PY_FILES" | tr ' ' '\n' | grep -v '^scripts/' | grep -v '^$' | xargs)
|
||||
if [ -n "$RUFF_FILES" ]; then
|
||||
python3 -m ruff check $RUFF_FILES --statistics
|
||||
else
|
||||
echo "No ruff-checkable files changed, skipping"
|
||||
fi
|
||||
elif [ "$SCAN_MODE" = "skip_py" ]; then
|
||||
echo "No Python files changed - skipping Python lint checks"
|
||||
else
|
||||
echo "Full scan mode"
|
||||
python3 -m compileall -q alembic apps packages tests scripts
|
||||
python3 -m black --check --fast alembic apps packages tests scripts
|
||||
python3 -m isort --check-only alembic apps packages tests scripts
|
||||
python3 -m ruff check apps packages tests --statistics
|
||||
fi
|
||||
echo "✅ Code quality checks passed"
|
||||
|
||||
# --- Bandit 安全扫描(仅告警) ---
|
||||
echo ""
|
||||
echo "=== [3/6] Security scan (bandit, advisory only) ==="
|
||||
set +e
|
||||
bandit -r apps packages -q -ll
|
||||
BANDIT_EXIT=$?
|
||||
set -e
|
||||
if [ "$BANDIT_EXIT" -ne 0 ]; then
|
||||
echo "⚠️ Bandit found security issues (advisory mode - not blocking CI)"
|
||||
else
|
||||
echo "✅ Bandit security scan passed"
|
||||
fi
|
||||
|
||||
# --- Pip-audit 依赖漏洞扫描(仅告警) ---
|
||||
echo ""
|
||||
echo "=== [4/6] Python dependency vulnerability scan (pip-audit, advisory only) ==="
|
||||
python3 -m pip install -q pip-audit
|
||||
pip-audit --version
|
||||
EXIT_CODE=0
|
||||
for req_file in requirements.txt requirements-base.txt requirements-dev.txt; do
|
||||
if [ -f "$req_file" ]; then
|
||||
echo "--- Scanning $req_file ---"
|
||||
pip-audit -r "$req_file" --desc on 2>&1 | head -40 || EXIT_CODE=$?
|
||||
echo ""
|
||||
fi
|
||||
done
|
||||
echo "pip-audit scan completed (advisory mode - warnings only, not blocking CI)"
|
||||
|
||||
# --- Vulture 死代码检测(仅告警) ---
|
||||
echo ""
|
||||
echo "=== [5/6] Dead code detection (vulture, advisory only) ==="
|
||||
set +e
|
||||
python3 -m pip install -q vulture
|
||||
vulture --version
|
||||
echo "告警模式,不阻断CI。置信度>=90%建议尽快确认。"
|
||||
echo ""
|
||||
vulture apps packages scripts \
|
||||
--exclude "tests,test,migrations,.gitea,docs,node_modules,site-packages,*/test_*.py,*/conftest.py" \
|
||||
--min-confidence 70 \
|
||||
2>&1 | sort -t'(' -k2 -rn | head -80
|
||||
echo ""
|
||||
echo "=== vulture scan summary ==="
|
||||
echo "发现潜在死代码(可能包含框架装饰器注册的函数,为误报)"
|
||||
echo "建议:定期人工审查高置信度(>=90%)条目"
|
||||
set -e
|
||||
|
||||
# --- Release 脚本语法校验 ---
|
||||
echo ""
|
||||
echo "=== [6/6] Release scripts syntax validation ==="
|
||||
bash -n scripts/backup_postgres.sh
|
||||
bash -n scripts/restore_postgres_plan.sh
|
||||
bash -n scripts/init_production_env.sh
|
||||
echo "✅ Release scripts syntax OK"
|
||||
|
||||
echo ""
|
||||
echo "=== CI Validate: 代码质量与安全扫描 全部通过 ✅ ==="
|
||||
@@ -0,0 +1,182 @@
|
||||
#!/bin/bash
|
||||
# CI Validate: Alembic迁移验证(并行Job 3/3)
|
||||
# 需要PostgreSQL数据库
|
||||
set -eu
|
||||
|
||||
echo "=== CI Validate: Alembic迁移验证 ==="
|
||||
|
||||
# --- DooD模式检测:确定宿主机访问地址 ---
|
||||
detect_docker_host() {
|
||||
local test_port="${1:-5432}"
|
||||
|
||||
local candidates=()
|
||||
|
||||
# 1. host.docker.internal
|
||||
if python3 -c "import socket; socket.gethostbyname('host.docker.internal')" 2>/dev/null; then
|
||||
candidates+=("host.docker.internal")
|
||||
fi
|
||||
|
||||
# 2. docker0 桥接网关
|
||||
candidates+=("172.17.0.1")
|
||||
|
||||
# 3. 默认网关
|
||||
local gw=""
|
||||
gw=$(ip route 2>/dev/null | grep default | awk '{print $3}' | head -1)
|
||||
if [ -n "$gw" ] && [ "$gw" != "127.0.0.1" ]; then
|
||||
candidates+=("$gw")
|
||||
fi
|
||||
|
||||
# 4. 宿主机同网段的.1或.254
|
||||
local my_ip=""
|
||||
my_ip=$(hostname -I 2>/dev/null | awk '{print $1}')
|
||||
if [ -n "$my_ip" ]; then
|
||||
local subnet=$(echo "$my_ip" | cut -d. -f1-3)
|
||||
candidates+=("${subnet}.1")
|
||||
candidates+=("${subnet}.254")
|
||||
fi
|
||||
|
||||
# 5. 127.0.0.1 最后尝试
|
||||
candidates+=("127.0.0.1")
|
||||
|
||||
for candidate in "${candidates[@]}"; do
|
||||
if python3 -c "
|
||||
import socket
|
||||
s = socket.socket()
|
||||
s.settimeout(2)
|
||||
try:
|
||||
s.connect(('$candidate', $test_port))
|
||||
s.close()
|
||||
print('ok')
|
||||
except:
|
||||
pass
|
||||
" 2>/dev/null | grep -q ok; then
|
||||
echo "$candidate"
|
||||
return 0
|
||||
fi
|
||||
done
|
||||
|
||||
echo "127.0.0.1"
|
||||
return 1
|
||||
}
|
||||
|
||||
# 获取宿主机IP
|
||||
if [ -S /var/run/docker.sock ]; then
|
||||
DOCKER_HOST_IP=$(detect_docker_host 5433)
|
||||
if [ "$DOCKER_HOST_IP" = "127.0.0.1" ]; then
|
||||
DOCKER_HOST_IP=$(detect_docker_host 22)
|
||||
fi
|
||||
echo "检测到DooD模式,宿主机地址: $DOCKER_HOST_IP"
|
||||
else
|
||||
DOCKER_HOST_IP="127.0.0.1"
|
||||
echo "非DooD模式,使用 127.0.0.1"
|
||||
fi
|
||||
PG_HOST="$DOCKER_HOST_IP"
|
||||
echo "PG host: $PG_HOST"
|
||||
|
||||
# 指数退避TCP连接检查
|
||||
wait_tcp_ready() {
|
||||
local host="$1"
|
||||
local port="$2"
|
||||
local max_attempts="${3:-5}"
|
||||
local delay=1
|
||||
local attempt=1
|
||||
while [ "$attempt" -le "$max_attempts" ]; do
|
||||
if python3 -c "import socket; s=socket.socket(); s.settimeout(3); s.connect(('$host', $port)); s.close()" 2>/dev/null; then
|
||||
return 0
|
||||
fi
|
||||
echo "TCP连接尝试 $attempt/$max_attempts 失败,${delay}s后重试..."
|
||||
sleep "$delay"
|
||||
delay=$((delay * 2))
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
USE_SHARED_PG="${CI_USE_SHARED_PG:-false}"
|
||||
|
||||
if [ "$USE_SHARED_PG" = "true" ]; then
|
||||
# 使用常驻共享PG实例
|
||||
echo "使用常驻共享PG实例(CI_USE_SHARED_PG=true)"
|
||||
SHARED_PG_HOST="$PG_HOST"
|
||||
SHARED_PG_PORT="5433"
|
||||
SHARED_PG_USER="postgres"
|
||||
SHARED_PG_PASSWORD="ci_pg_2026!"
|
||||
CI_DB_NAME="ci_run_${GITHUB_RUN_ID:-$$}"
|
||||
|
||||
echo "等待共享PG连接就绪..."
|
||||
wait_tcp_ready "$SHARED_PG_HOST" "$SHARED_PG_PORT" 5
|
||||
|
||||
echo "创建测试数据库: $CI_DB_NAME"
|
||||
PGPASSWORD="$SHARED_PG_PASSWORD" python3 -c "
|
||||
import psycopg2
|
||||
conn = psycopg2.connect(host='$SHARED_PG_HOST', port=$SHARED_PG_PORT, user='$SHARED_PG_USER', password='$SHARED_PG_PASSWORD', dbname='postgres')
|
||||
conn.autocommit = True
|
||||
cur = conn.cursor()
|
||||
cur.execute(f'CREATE DATABASE \"$CI_DB_NAME\"')
|
||||
cur.close()
|
||||
conn.close()
|
||||
"
|
||||
export DATABASE_URL="postgresql+psycopg://${SHARED_PG_USER}:${SHARED_PG_PASSWORD}@${SHARED_PG_HOST}:${SHARED_PG_PORT}/${CI_DB_NAME}"
|
||||
echo "✅ 共享PG数据库已创建: $CI_DB_NAME"
|
||||
|
||||
# 执行迁移
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic upgrade head
|
||||
echo "✅ Alembic migrations applied successfully"
|
||||
|
||||
# 清理数据库
|
||||
echo "清理测试数据库: $CI_DB_NAME"
|
||||
PGPASSWORD="$SHARED_PG_PASSWORD" python3 -c "
|
||||
import psycopg2
|
||||
conn = psycopg2.connect(host='$SHARED_PG_HOST', port=$SHARED_PG_PORT, user='$SHARED_PG_USER', password='$SHARED_PG_PASSWORD', dbname='postgres')
|
||||
conn.autocommit = True
|
||||
cur = conn.cursor()
|
||||
cur.execute(f'DROP DATABASE IF EXISTS \"$CI_DB_NAME\" WITH (FORCE)')
|
||||
cur.close()
|
||||
conn.close()
|
||||
" 2>/dev/null || echo "WARN: 数据库清理失败"
|
||||
echo "✅ 共享PG数据库已清理"
|
||||
else
|
||||
# 使用临时PG容器(默认模式)
|
||||
echo "使用临时PG容器模式"
|
||||
PG_CONTAINER=ci-pg-validate-migration-${GITHUB_RUN_ID:-$$}
|
||||
docker rm -f "$PG_CONTAINER" 2>/dev/null || true
|
||||
docker run -d --name "$PG_CONTAINER" \
|
||||
--shm-size=256m \
|
||||
-e POSTGRES_USER=postgres \
|
||||
-e POSTGRES_PASSWORD=postgres \
|
||||
-e POSTGRES_DB=xiaoxia_saas \
|
||||
-P \
|
||||
--health-cmd "pg_isready -U postgres" \
|
||||
--health-interval 3s \
|
||||
--health-timeout 3s \
|
||||
--health-retries 20 \
|
||||
postgres:16-alpine
|
||||
PG_PORT=$(docker port "$PG_CONTAINER" 5432/tcp | cut -d: -f2)
|
||||
echo "PostgreSQL port: $PG_PORT"
|
||||
export DATABASE_URL="postgresql+psycopg://postgres:postgres@${PG_HOST}:${PG_PORT}/xiaoxia_saas"
|
||||
|
||||
# 等待容器健康
|
||||
for i in $(seq 1 30); do
|
||||
if docker inspect --format='{{.State.Health.Status}}' "$PG_CONTAINER" 2>/dev/null | grep -q healthy; then
|
||||
echo "PostgreSQL container is healthy on port $PG_PORT"
|
||||
break
|
||||
fi
|
||||
echo "Waiting for PostgreSQL container health... ($i/30)"
|
||||
sleep 2
|
||||
done
|
||||
docker inspect --format='{{.State.Health.Status}}' "$PG_CONTAINER" | grep -q healthy
|
||||
|
||||
# TCP连通性检查
|
||||
echo "验证TCP连通性 ($PG_HOST:$PG_PORT)..."
|
||||
wait_tcp_ready "$PG_HOST" "$PG_PORT" 5
|
||||
echo "TCP connectivity to PostgreSQL confirmed on port $PG_PORT"
|
||||
|
||||
# 执行迁移
|
||||
PYTHONPATH="$PWD/apps/api:$PWD" python3 -m alembic upgrade head
|
||||
echo "✅ Alembic migrations applied successfully"
|
||||
|
||||
docker rm -f "$PG_CONTAINER" 2>/dev/null || true
|
||||
fi
|
||||
|
||||
echo ""
|
||||
echo "=== CI Validate: Alembic迁移验证 通过 ✅ ==="
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/bash
|
||||
# CI Validate: Mypy类型检查(并行Job 2/3)
|
||||
set -eu
|
||||
|
||||
echo "=== CI Validate: Mypy类型检查 ==="
|
||||
|
||||
bash scripts/ci/mypy_check.sh
|
||||
|
||||
echo ""
|
||||
echo "=== CI Validate: Mypy类型检查 通过 ✅ ==="
|
||||
+128
-31
@@ -1,17 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""发送 CI 失败通知到飞书/项目群 webhook。"""
|
||||
"""发送 CI 失败通知到飞书/项目群 webhook(增强版:带失败诊断)。
|
||||
|
||||
诊断功能:自动分析失败原因,给出分类和修复建议。
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
|
||||
def run_diagnosis() -> dict:
|
||||
"""运行失败诊断脚本,返回诊断结果"""
|
||||
diag_script = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ci/ci_failure_diagnosis.py")
|
||||
if not os.path.exists(diag_script):
|
||||
diag_script = "scripts/ci/ci_failure_diagnosis.py"
|
||||
|
||||
result = {
|
||||
"category": "unknown",
|
||||
"category_cn": "未知",
|
||||
"severity": "medium",
|
||||
"summary": "",
|
||||
"error_lines": [],
|
||||
"suggestions": [],
|
||||
"auto_fixable": False,
|
||||
}
|
||||
|
||||
try:
|
||||
# 运行诊断脚本
|
||||
env = os.environ.copy()
|
||||
env["DIAGNOSIS_OUTPUT"] = "/tmp/ci_diagnosis_result.json"
|
||||
|
||||
proc = subprocess.run([sys.executable, diag_script], capture_output=True, text=True, timeout=30, env=env)
|
||||
|
||||
# 尝试读取结果文件
|
||||
output_file = "/tmp/ci_diagnosis_result.json"
|
||||
if os.path.exists(output_file):
|
||||
with open(output_file) as f:
|
||||
result = json.load(f)
|
||||
elif proc.stdout:
|
||||
# 从stdout解析
|
||||
pass
|
||||
except Exception as e:
|
||||
print(f"诊断脚本执行失败: {e}", file=sys.stderr)
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def main() -> int:
|
||||
webhook = os.environ.get("CI_NOTIFY_WEBHOOK", "")
|
||||
if not webhook:
|
||||
print("未配置 CI_NOTIFY_WEBHOOK,跳过通知")
|
||||
print("如需启用,请在仓库 Settings -> Secrets and variables -> Actions 中添加 CI_NOTIFY_WEBHOOK")
|
||||
return 0
|
||||
|
||||
failed_job = os.environ.get("FAILED_JOB", "Unknown Job")
|
||||
@@ -21,6 +61,86 @@ def main() -> int:
|
||||
run_id = os.environ.get("GITHUB_RUN_ID", "unknown")
|
||||
repo = os.environ.get("GITHUB_REPOSITORY", "unknown")
|
||||
run_url = f"https://git.xiaoxiajianji.com/{repo}/actions/runs/{run_id}"
|
||||
pr_number = os.environ.get("PR_NUMBER", "")
|
||||
|
||||
# 运行诊断
|
||||
diagnosis = run_diagnosis()
|
||||
|
||||
# 构建卡片内容
|
||||
severity_color = {"high": "red", "medium": "orange", "low": "blue"}
|
||||
card_status = severity_color.get(diagnosis.get("severity", "medium"), "red")
|
||||
|
||||
# 标题
|
||||
title = f"❌ CI失败 - {diagnosis.get('category_cn', '未知')}"
|
||||
|
||||
# 诊断部分
|
||||
diag_lines = []
|
||||
diag_lines.append(f"**任务**: {failed_job}")
|
||||
diag_lines.append(f"**分类**: {diagnosis.get('category_cn', '未知')}")
|
||||
if diagnosis.get("summary"):
|
||||
diag_lines.append(f"**问题**: {diagnosis['summary']}")
|
||||
|
||||
# 错误行
|
||||
error_lines = diagnosis.get("error_lines", [])
|
||||
if error_lines:
|
||||
diag_lines.append("")
|
||||
diag_lines.append("**关键错误**:")
|
||||
for err in error_lines[:3]:
|
||||
if len(err) > 100:
|
||||
err = err[:97] + "..."
|
||||
diag_lines.append(f"`{err}`")
|
||||
|
||||
# 修复建议
|
||||
suggestions = diagnosis.get("suggestions", [])
|
||||
if suggestions:
|
||||
diag_lines.append("")
|
||||
diag_lines.append("**修复建议**:")
|
||||
for i, s in enumerate(suggestions[:3], 1):
|
||||
diag_lines.append(f"{i}. {s}")
|
||||
|
||||
if diagnosis.get("auto_fixable"):
|
||||
diag_lines.append("")
|
||||
diag_lines.append("💡 *可自动修复的问题,试试Rerun*")
|
||||
|
||||
# 基本信息
|
||||
info_lines = [
|
||||
f"**分支**: {branch}",
|
||||
f"**提交**: `{commit}`",
|
||||
f"**提交者**: {actor}",
|
||||
]
|
||||
if pr_number:
|
||||
info_lines.append(f"**PR**: #{pr_number}")
|
||||
|
||||
elements = [
|
||||
{
|
||||
"tag": "div",
|
||||
"text": {
|
||||
"tag": "lark_md",
|
||||
"content": "\n".join(diag_lines),
|
||||
},
|
||||
},
|
||||
{
|
||||
"tag": "hr",
|
||||
},
|
||||
{
|
||||
"tag": "div",
|
||||
"text": {
|
||||
"tag": "lark_md",
|
||||
"content": "\n".join(info_lines),
|
||||
},
|
||||
},
|
||||
{
|
||||
"tag": "action",
|
||||
"actions": [
|
||||
{
|
||||
"tag": "button",
|
||||
"text": {"tag": "plain_text", "content": "查看失败日志"},
|
||||
"url": run_url,
|
||||
"type": "danger",
|
||||
},
|
||||
],
|
||||
},
|
||||
]
|
||||
|
||||
payload = {
|
||||
"msg_type": "interactive",
|
||||
@@ -28,36 +148,11 @@ def main() -> int:
|
||||
"header": {
|
||||
"title": {
|
||||
"tag": "plain_text",
|
||||
"content": "❌ CI 构建失败",
|
||||
"content": title,
|
||||
},
|
||||
"status": "red",
|
||||
"status": card_status,
|
||||
},
|
||||
"elements": [
|
||||
{
|
||||
"tag": "div",
|
||||
"text": {
|
||||
"tag": "lark_md",
|
||||
"content": (
|
||||
f"**任务**: {failed_job}\n"
|
||||
f"**分支**: {branch}\n"
|
||||
f"**提交**: {commit}\n"
|
||||
f"**提交者**: {actor}\n"
|
||||
f"**Run ID**: {run_id}"
|
||||
),
|
||||
},
|
||||
},
|
||||
{
|
||||
"tag": "action",
|
||||
"actions": [
|
||||
{
|
||||
"tag": "button",
|
||||
"text": {"tag": "plain_text", "content": "查看失败日志"},
|
||||
"url": run_url,
|
||||
"type": "danger",
|
||||
}
|
||||
],
|
||||
},
|
||||
],
|
||||
"elements": elements,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -71,7 +166,7 @@ def main() -> int:
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as resp:
|
||||
resp.read()
|
||||
print("通知已发送")
|
||||
print("通知已发送(带诊断信息)")
|
||||
except Exception as e:
|
||||
print(f"通知发送失败: {e}", file=sys.stderr)
|
||||
return 1
|
||||
@@ -81,3 +176,5 @@ def main() -> int:
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
|
||||
# trigger CI - bypass [ci skip] bug
|
||||
|
||||
Executable
+425
@@ -0,0 +1,425 @@
|
||||
"""
|
||||
FeatureFlagStore 单元测试
|
||||
|
||||
覆盖:
|
||||
- FeatureFlagConfig: to_dict / from_dict 序列化
|
||||
- FeatureFlagConfig.is_active: 全局开关/白名单/百分比哈希
|
||||
- InMemoryFeatureFlagStore: CRUD / is_active
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.adapters.redis.feature_flag_store import (
|
||||
FEATURE_FLAG_REDIS_PREFIX,
|
||||
FeatureFlagConfig,
|
||||
InMemoryFeatureFlagStore,
|
||||
)
|
||||
|
||||
# ============================================================
|
||||
# 常量
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestConstants:
|
||||
"""常量验证"""
|
||||
|
||||
def test_redis_prefix(self):
|
||||
assert FEATURE_FLAG_REDIS_PREFIX == "feature_flag:"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FeatureFlagConfig - 默认值 & 基础
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestFeatureFlagConfigDefaults:
|
||||
"""FeatureFlagConfig 默认值"""
|
||||
|
||||
def test_required_name(self):
|
||||
config = FeatureFlagConfig(name="test_flag")
|
||||
assert config.name == "test_flag"
|
||||
|
||||
def test_default_disabled(self):
|
||||
config = FeatureFlagConfig(name="test_flag")
|
||||
assert config.enabled is False
|
||||
|
||||
def test_default_percentage_zero(self):
|
||||
config = FeatureFlagConfig(name="test_flag")
|
||||
assert config.percentage == 0
|
||||
|
||||
def test_default_whitelist_empty(self):
|
||||
config = FeatureFlagConfig(name="test_flag")
|
||||
assert config.whitelist == set()
|
||||
|
||||
def test_full_config(self):
|
||||
config = FeatureFlagConfig(
|
||||
name="full_flag",
|
||||
enabled=True,
|
||||
percentage=50,
|
||||
whitelist={"user1", "user2"},
|
||||
)
|
||||
assert config.name == "full_flag"
|
||||
assert config.enabled is True
|
||||
assert config.percentage == 50
|
||||
assert config.whitelist == {"user1", "user2"}
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FeatureFlagConfig - 序列化
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestFeatureFlagConfigSerialization:
|
||||
"""to_dict / from_dict 序列化"""
|
||||
|
||||
def test_to_dict_defaults(self):
|
||||
config = FeatureFlagConfig(name="test")
|
||||
d = config.to_dict()
|
||||
assert d["name"] == "test"
|
||||
assert d["enabled"] is False
|
||||
assert d["percentage"] == 0
|
||||
assert d["whitelist"] == []
|
||||
|
||||
def test_to_dict_with_values(self):
|
||||
config = FeatureFlagConfig(
|
||||
name="test",
|
||||
enabled=True,
|
||||
percentage=75,
|
||||
whitelist={"a", "b", "c"},
|
||||
)
|
||||
d = config.to_dict()
|
||||
assert d["name"] == "test"
|
||||
assert d["enabled"] is True
|
||||
assert d["percentage"] == 75
|
||||
# whitelist 排序后输出
|
||||
assert sorted(d["whitelist"]) == ["a", "b", "c"]
|
||||
|
||||
def test_from_dict_minimal(self):
|
||||
d = {"name": "test"}
|
||||
config = FeatureFlagConfig.from_dict(d)
|
||||
assert config.name == "test"
|
||||
assert config.enabled is False
|
||||
assert config.percentage == 0
|
||||
assert config.whitelist == set()
|
||||
|
||||
def test_from_dict_full(self):
|
||||
d = {
|
||||
"name": "full",
|
||||
"enabled": True,
|
||||
"percentage": 30,
|
||||
"whitelist": ["u1", "u2"],
|
||||
}
|
||||
config = FeatureFlagConfig.from_dict(d)
|
||||
assert config.name == "full"
|
||||
assert config.enabled is True
|
||||
assert config.percentage == 30
|
||||
assert config.whitelist == {"u1", "u2"}
|
||||
|
||||
def test_round_trip(self):
|
||||
original = FeatureFlagConfig(
|
||||
name="round_trip",
|
||||
enabled=True,
|
||||
percentage=42,
|
||||
whitelist={"alice", "bob", "charlie"},
|
||||
)
|
||||
d = original.to_dict()
|
||||
restored = FeatureFlagConfig.from_dict(d)
|
||||
assert restored.name == original.name
|
||||
assert restored.enabled == original.enabled
|
||||
assert restored.percentage == original.percentage
|
||||
assert restored.whitelist == original.whitelist
|
||||
|
||||
def test_from_dict_coerces_types(self):
|
||||
"""from_dict 应该做类型转换"""
|
||||
d = {
|
||||
"name": "coerce",
|
||||
"enabled": 1, # int → bool
|
||||
"percentage": "50", # str → int
|
||||
"whitelist": ("a", "b"), # tuple → set
|
||||
}
|
||||
config = FeatureFlagConfig.from_dict(d)
|
||||
assert config.enabled is True
|
||||
assert config.percentage == 50
|
||||
assert config.whitelist == {"a", "b"}
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FeatureFlagConfig.is_active - 全局开关
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestIsActiveGlobalSwitch:
|
||||
"""is_active - 全局开关基础"""
|
||||
|
||||
def test_disabled_returns_false(self):
|
||||
config = FeatureFlagConfig(name="test", enabled=False)
|
||||
assert config.is_active() is False
|
||||
|
||||
def test_disabled_with_identifier_returns_false(self):
|
||||
config = FeatureFlagConfig(name="test", enabled=False)
|
||||
assert config.is_active(identifier="user1") is False
|
||||
|
||||
def test_enabled_no_percentage_no_whitelist_returns_true(self):
|
||||
config = FeatureFlagConfig(name="test", enabled=True)
|
||||
# percentage=0, whitelist=空,但 enabled=True
|
||||
# 按逻辑:全局开了但百分比0且无白名单 → 其实应该是 False?
|
||||
# 让我看代码...
|
||||
# 代码里 percentage <= 0 时返回 False(没有白名单且百分比为0)
|
||||
assert config.is_active() is False
|
||||
|
||||
def test_enabled_100_percent_returns_true(self):
|
||||
config = FeatureFlagConfig(name="test", enabled=True, percentage=100)
|
||||
assert config.is_active() is True
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FeatureFlagConfig.is_active - 白名单
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestIsActiveWhitelist:
|
||||
"""is_active - 白名单优先级"""
|
||||
|
||||
def test_whitelist_match_returns_true(self):
|
||||
config = FeatureFlagConfig(
|
||||
name="test",
|
||||
enabled=True,
|
||||
whitelist={"user1", "user2"},
|
||||
)
|
||||
assert config.is_active(identifier="user1") is True
|
||||
|
||||
def test_whitelist_no_match_falls_through(self):
|
||||
config = FeatureFlagConfig(
|
||||
name="test",
|
||||
enabled=True,
|
||||
percentage=0,
|
||||
whitelist={"user1"},
|
||||
)
|
||||
# 不在白名单,且百分比为0 → False
|
||||
assert config.is_active(identifier="user3") is False
|
||||
|
||||
def test_whitelist_overrides_percentage_zero(self):
|
||||
"""白名单优先级最高,即使百分比为0也能启用"""
|
||||
config = FeatureFlagConfig(
|
||||
name="test",
|
||||
enabled=True,
|
||||
percentage=0,
|
||||
whitelist={"vip_user"},
|
||||
)
|
||||
assert config.is_active(identifier="vip_user") is True
|
||||
|
||||
def test_whitelist_overrides_partial_percentage(self):
|
||||
"""白名单用户即使在百分比外也能启用"""
|
||||
config = FeatureFlagConfig(
|
||||
name="test",
|
||||
enabled=True,
|
||||
percentage=1, # 只有1%的用户
|
||||
whitelist={"important_user"},
|
||||
)
|
||||
# 白名单用户直接通过
|
||||
assert config.is_active(identifier="important_user") is True
|
||||
|
||||
def test_no_identifier_no_whitelist_check(self):
|
||||
"""不传 identifier 时不做白名单检查"""
|
||||
config = FeatureFlagConfig(
|
||||
name="test",
|
||||
enabled=True,
|
||||
percentage=100,
|
||||
whitelist={"user1"},
|
||||
)
|
||||
# 无 identifier,直接看百分比(100%)
|
||||
assert config.is_active() is True
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FeatureFlagConfig.is_active - 百分比边界值
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestIsActivePercentageBoundaries:
|
||||
"""is_active - 百分比边界值"""
|
||||
|
||||
def test_percentage_0_returns_false(self):
|
||||
config = FeatureFlagConfig(name="test", enabled=True, percentage=0)
|
||||
assert config.is_active(identifier="any_user") is False
|
||||
|
||||
def test_percentage_100_returns_true(self):
|
||||
config = FeatureFlagConfig(name="test", enabled=True, percentage=100)
|
||||
assert config.is_active(identifier="any_user") is True
|
||||
|
||||
def test_percentage_negative_treated_as_0(self):
|
||||
"""percentage < 0 应该按 0 处理"""
|
||||
config = FeatureFlagConfig(name="test", enabled=True, percentage=-5)
|
||||
assert config.is_active(identifier="any_user") is False
|
||||
|
||||
def test_percentage_over_100_treated_as_100(self):
|
||||
"""percentage > 100 应该按 100 处理"""
|
||||
config = FeatureFlagConfig(name="test", enabled=True, percentage=150)
|
||||
assert config.is_active(identifier="any_user") is True
|
||||
|
||||
|
||||
# ============================================================
|
||||
# FeatureFlagConfig.is_active - 哈希一致性
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestIsActiveHashConsistency:
|
||||
"""is_active - 哈希取模一致性验证"""
|
||||
|
||||
def test_same_user_same_result_every_time(self):
|
||||
"""同一用户多次调用结果一致(确定性哈希)"""
|
||||
config = FeatureFlagConfig(name="test", enabled=True, percentage=50)
|
||||
results = {config.is_active(identifier="user_xyz") for _ in range(100)}
|
||||
assert len(results) == 1 # 全部相同
|
||||
|
||||
def test_different_flags_same_user_can_differ(self):
|
||||
"""不同 flag 对同一用户可以有不同结果(因为 flag name 参与哈希)"""
|
||||
config_a = FeatureFlagConfig(name="flag_a", enabled=True, percentage=50)
|
||||
config_b = FeatureFlagConfig(name="flag_b", enabled=True, percentage=50)
|
||||
# 不保证一定不同,但大部分情况下应该不同
|
||||
# 这里只验证哈希输入包含了 flag name(通过机制保证)
|
||||
# 具体是否不同取决于哈希值
|
||||
|
||||
def test_percentage_coverage_roughly_correct(self):
|
||||
"""大量用户中,命中比例大致接近百分比"""
|
||||
config = FeatureFlagConfig(name="coverage_test", enabled=True, percentage=30)
|
||||
users = [f"user_{i}" for i in range(1000)]
|
||||
active_count = sum(1 for u in users if config.is_active(identifier=u))
|
||||
# 30% ± 10% 的容差
|
||||
assert 200 <= active_count <= 400
|
||||
|
||||
def test_50_percent_roughly_half(self):
|
||||
config = FeatureFlagConfig(name="half_test", enabled=True, percentage=50)
|
||||
users = [f"user_{i}" for i in range(1000)]
|
||||
active_count = sum(1 for u in users if config.is_active(identifier=u))
|
||||
# 50% ± 10%
|
||||
assert 400 <= active_count <= 600
|
||||
|
||||
def test_10_percent_roughly_tenth(self):
|
||||
config = FeatureFlagConfig(name="ten_pct", enabled=True, percentage=10)
|
||||
users = [f"user_{i}" for i in range(1000)]
|
||||
active_count = sum(1 for u in users if config.is_active(identifier=u))
|
||||
assert 50 <= active_count <= 150
|
||||
|
||||
def test_empty_identifier_treated_as_no_identifier(self):
|
||||
"""空字符串 identifier 应该如何处理?"""
|
||||
config = FeatureFlagConfig(name="test", enabled=True, percentage=50)
|
||||
# 空字符串是 falsy,走无 identifier 分支(随机)
|
||||
# 但白名单检查也会跳过
|
||||
# 验证不会崩溃
|
||||
result = config.is_active(identifier="")
|
||||
assert isinstance(result, bool)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# InMemoryFeatureFlagStore - CRUD
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestInMemoryFeatureFlagStore:
|
||||
"""InMemoryFeatureFlagStore 内存实现"""
|
||||
|
||||
def test_get_nonexistent_returns_default_disabled(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
config = store.get("nonexistent")
|
||||
assert config.name == "nonexistent"
|
||||
assert config.enabled is False
|
||||
assert config.percentage == 0
|
||||
|
||||
def test_set_and_get(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
original = FeatureFlagConfig(
|
||||
name="my_flag",
|
||||
enabled=True,
|
||||
percentage=50,
|
||||
whitelist={"admin"},
|
||||
)
|
||||
store.set(original)
|
||||
retrieved = store.get("my_flag")
|
||||
assert retrieved.name == "my_flag"
|
||||
assert retrieved.enabled is True
|
||||
assert retrieved.percentage == 50
|
||||
assert retrieved.whitelist == {"admin"}
|
||||
|
||||
def test_set_overwrites_existing(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
store.set(FeatureFlagConfig(name="flag", enabled=True, percentage=30))
|
||||
store.set(FeatureFlagConfig(name="flag", enabled=False, percentage=70))
|
||||
config = store.get("flag")
|
||||
assert config.enabled is False
|
||||
assert config.percentage == 70
|
||||
|
||||
def test_delete_existing_returns_true(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
store.set(FeatureFlagConfig(name="delete_me"))
|
||||
result = store.delete("delete_me")
|
||||
assert result is True
|
||||
# 删除后获取返回默认配置
|
||||
assert store.get("delete_me").enabled is False
|
||||
|
||||
def test_delete_nonexistent_returns_false(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
result = store.delete("no_such_flag")
|
||||
assert result is False
|
||||
|
||||
def test_list_all_empty(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
assert store.list_all() == {}
|
||||
|
||||
def test_list_all_multiple(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
store.set(FeatureFlagConfig(name="flag1", enabled=True))
|
||||
store.set(FeatureFlagConfig(name="flag2", percentage=50))
|
||||
store.set(FeatureFlagConfig(name="flag3"))
|
||||
|
||||
all_flags = store.list_all()
|
||||
assert len(all_flags) == 3
|
||||
assert "flag1" in all_flags
|
||||
assert "flag2" in all_flags
|
||||
assert "flag3" in all_flags
|
||||
assert all_flags["flag1"].enabled is True
|
||||
assert all_flags["flag2"].percentage == 50
|
||||
|
||||
def test_list_all_returns_copy(self):
|
||||
"""返回的是副本,修改不影响内部状态"""
|
||||
store = InMemoryFeatureFlagStore()
|
||||
store.set(FeatureFlagConfig(name="flag1"))
|
||||
flags = store.list_all()
|
||||
flags["fake"] = FeatureFlagConfig(name="fake")
|
||||
assert "fake" not in store.list_all()
|
||||
|
||||
|
||||
# ============================================================
|
||||
# InMemoryFeatureFlagStore - is_active
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestInMemoryStoreIsActive:
|
||||
"""store.is_active 便捷方法"""
|
||||
|
||||
def test_is_active_enabled_flag(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
store.set(FeatureFlagConfig(name="on", enabled=True, percentage=100))
|
||||
assert store.is_active("on") is True
|
||||
|
||||
def test_is_active_disabled_flag(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
store.set(FeatureFlagConfig(name="off", enabled=False))
|
||||
assert store.is_active("off") is False
|
||||
|
||||
def test_is_active_nonexistent_flag(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
assert store.is_active("unknown") is False
|
||||
|
||||
def test_is_active_with_identifier_whitelist(self):
|
||||
store = InMemoryFeatureFlagStore()
|
||||
store.set(
|
||||
FeatureFlagConfig(
|
||||
name="beta",
|
||||
enabled=True,
|
||||
percentage=0,
|
||||
whitelist={"tester1"},
|
||||
)
|
||||
)
|
||||
assert store.is_active("beta", identifier="tester1") is True
|
||||
assert store.is_active("beta", identifier="other_user") is False
|
||||
Executable
+569
@@ -0,0 +1,569 @@
|
||||
"""
|
||||
Module Registry 模块注册中心单元测试
|
||||
|
||||
覆盖:
|
||||
- ModuleStatus 枚举
|
||||
- QuotaRule / ModuleCapability / Module 数据类
|
||||
- Module.activate / disable 状态转换
|
||||
- ModuleRegistry 注册/注销/查询/能力发现/依赖检查
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.infrastructure.module_registry import (
|
||||
Module,
|
||||
ModuleCapability,
|
||||
ModuleRegistry,
|
||||
ModuleStatus,
|
||||
QuotaRule,
|
||||
module_registry,
|
||||
)
|
||||
|
||||
# ============================================================
|
||||
# ModuleStatus
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleStatus:
|
||||
"""ModuleStatus 枚举"""
|
||||
|
||||
def test_enum_values(self):
|
||||
assert ModuleStatus.REGISTERED.value == "registered"
|
||||
assert ModuleStatus.ACTIVE.value == "active"
|
||||
assert ModuleStatus.DISABLED.value == "disabled"
|
||||
assert ModuleStatus.ERROR.value == "error"
|
||||
|
||||
def test_is_str_enum(self):
|
||||
assert isinstance(ModuleStatus.ACTIVE, str)
|
||||
assert ModuleStatus.ACTIVE == "active"
|
||||
|
||||
def test_has_four_states(self):
|
||||
assert len(ModuleStatus) == 4
|
||||
|
||||
|
||||
# ============================================================
|
||||
# QuotaRule
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestQuotaRule:
|
||||
"""QuotaRule 配额规则"""
|
||||
|
||||
def test_required_fields(self):
|
||||
rule = QuotaRule(dimension="ai_credits", per_operation=1.0)
|
||||
assert rule.dimension == "ai_credits"
|
||||
assert rule.per_operation == 1.0
|
||||
|
||||
def test_default_description_empty(self):
|
||||
rule = QuotaRule(dimension="storage_gb", per_operation=0.5)
|
||||
assert rule.description == ""
|
||||
|
||||
def test_custom_description(self):
|
||||
rule = QuotaRule(
|
||||
dimension="credits",
|
||||
per_operation=2.0,
|
||||
description="每次生成消耗2积分",
|
||||
)
|
||||
assert rule.description == "每次生成消耗2积分"
|
||||
|
||||
def test_float_per_operation(self):
|
||||
rule = QuotaRule(dimension="gb", per_operation=0.25)
|
||||
assert rule.per_operation == 0.25
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ModuleCapability
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleCapability:
|
||||
"""ModuleCapability 能力定义"""
|
||||
|
||||
def test_required_name(self):
|
||||
cap = ModuleCapability(name="generate_voice")
|
||||
assert cap.name == "generate_voice"
|
||||
|
||||
def test_defaults(self):
|
||||
cap = ModuleCapability(name="test_cap")
|
||||
assert cap.description == ""
|
||||
assert cap.quota_rules == []
|
||||
assert cap.metadata == {}
|
||||
|
||||
def test_with_quota_rules(self):
|
||||
rules = [QuotaRule(dimension="credits", per_operation=1.0)]
|
||||
cap = ModuleCapability(
|
||||
name="generate",
|
||||
description="生成功能",
|
||||
quota_rules=rules,
|
||||
)
|
||||
assert cap.description == "生成功能"
|
||||
assert len(cap.quota_rules) == 1
|
||||
assert cap.quota_rules[0].dimension == "credits"
|
||||
|
||||
def test_with_metadata(self):
|
||||
cap = ModuleCapability(
|
||||
name="export",
|
||||
metadata={"format": "mp4", "max_resolution": "1080p"},
|
||||
)
|
||||
assert cap.metadata["format"] == "mp4"
|
||||
assert cap.metadata["max_resolution"] == "1080p"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# Module
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleDefaults:
|
||||
"""Module 数据类默认值"""
|
||||
|
||||
def test_required_name(self):
|
||||
mod = Module(name="ai_voice")
|
||||
assert mod.name == "ai_voice"
|
||||
|
||||
def test_default_version(self):
|
||||
mod = Module(name="test")
|
||||
assert mod.version == "1.0.0"
|
||||
|
||||
def test_default_description(self):
|
||||
mod = Module(name="test")
|
||||
assert mod.description == ""
|
||||
|
||||
def test_default_capabilities_empty(self):
|
||||
mod = Module(name="test")
|
||||
assert mod.capabilities == []
|
||||
|
||||
def test_default_dependencies_empty(self):
|
||||
mod = Module(name="test")
|
||||
assert mod.dependencies == []
|
||||
|
||||
def test_default_status_registered(self):
|
||||
mod = Module(name="test")
|
||||
assert mod.status == ModuleStatus.REGISTERED
|
||||
|
||||
def test_default_config_empty(self):
|
||||
mod = Module(name="test")
|
||||
assert mod.config == {}
|
||||
|
||||
def test_full_module(self):
|
||||
cap = ModuleCapability(name="do_something")
|
||||
mod = Module(
|
||||
name="full_module",
|
||||
version="2.0.0",
|
||||
description="完整模块",
|
||||
capabilities=[cap],
|
||||
dependencies=["dep1", "dep2"],
|
||||
status=ModuleStatus.ACTIVE,
|
||||
config={"key": "value"},
|
||||
)
|
||||
assert mod.version == "2.0.0"
|
||||
assert mod.description == "完整模块"
|
||||
assert len(mod.capabilities) == 1
|
||||
assert mod.dependencies == ["dep1", "dep2"]
|
||||
assert mod.status == ModuleStatus.ACTIVE
|
||||
assert mod.config["key"] == "value"
|
||||
|
||||
|
||||
class TestModuleActivate:
|
||||
"""Module.activate 状态转换"""
|
||||
|
||||
def test_activate_from_registered(self):
|
||||
mod = Module(name="test")
|
||||
mod.activate()
|
||||
assert mod.status == ModuleStatus.ACTIVE
|
||||
|
||||
def test_activate_from_disabled(self):
|
||||
mod = Module(name="test", status=ModuleStatus.DISABLED)
|
||||
mod.activate()
|
||||
assert mod.status == ModuleStatus.ACTIVE
|
||||
|
||||
def test_activate_from_error_stays_error(self):
|
||||
mod = Module(name="test", status=ModuleStatus.ERROR)
|
||||
mod.activate()
|
||||
# error 状态不可激活
|
||||
assert mod.status == ModuleStatus.ERROR
|
||||
|
||||
def test_activate_already_active(self):
|
||||
mod = Module(name="test", status=ModuleStatus.ACTIVE)
|
||||
mod.activate()
|
||||
assert mod.status == ModuleStatus.ACTIVE
|
||||
|
||||
|
||||
class TestModuleDisable:
|
||||
"""Module.disable 状态转换"""
|
||||
|
||||
def test_disable_from_registered(self):
|
||||
mod = Module(name="test")
|
||||
mod.disable()
|
||||
assert mod.status == ModuleStatus.DISABLED
|
||||
|
||||
def test_disable_from_active(self):
|
||||
mod = Module(name="test", status=ModuleStatus.ACTIVE)
|
||||
mod.disable()
|
||||
assert mod.status == ModuleStatus.DISABLED
|
||||
|
||||
def test_disable_from_error(self):
|
||||
mod = Module(name="test", status=ModuleStatus.ERROR)
|
||||
mod.disable()
|
||||
assert mod.status == ModuleStatus.DISABLED
|
||||
|
||||
def test_disable_already_disabled(self):
|
||||
mod = Module(name="test", status=ModuleStatus.DISABLED)
|
||||
mod.disable()
|
||||
assert mod.status == ModuleStatus.DISABLED
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ModuleRegistry - 基础操作
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleRegistryBasic:
|
||||
"""ModuleRegistry 基础操作"""
|
||||
|
||||
def test_empty_registry(self):
|
||||
registry = ModuleRegistry()
|
||||
assert registry.list_modules() == []
|
||||
assert registry.get_active_capabilities() == {}
|
||||
|
||||
def test_register_single_module(self):
|
||||
registry = ModuleRegistry()
|
||||
mod = Module(name="test_mod")
|
||||
registry.register(mod)
|
||||
assert registry.get("test_mod") is mod
|
||||
|
||||
def test_register_duplicate_raises(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="test_mod"))
|
||||
with pytest.raises(ValueError, match="already registered"):
|
||||
registry.register(Module(name="test_mod"))
|
||||
|
||||
def test_get_nonexistent_returns_none(self):
|
||||
registry = ModuleRegistry()
|
||||
assert registry.get("no_such_module") is None
|
||||
|
||||
def test_unregister_success(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="test_mod"))
|
||||
registry.unregister("test_mod")
|
||||
assert registry.get("test_mod") is None
|
||||
|
||||
def test_unregister_nonexistent_raises(self):
|
||||
registry = ModuleRegistry()
|
||||
with pytest.raises(KeyError, match="not found"):
|
||||
registry.unregister("no_such_module")
|
||||
|
||||
def test_unregister_with_dependents_raises(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="base_module"))
|
||||
registry.register(Module(name="dependent_module", dependencies=["base_module"]))
|
||||
with pytest.raises(ValueError, match="depended on by"):
|
||||
registry.unregister("base_module")
|
||||
|
||||
def test_clear(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="mod1"))
|
||||
registry.register(Module(name="mod2"))
|
||||
registry.clear()
|
||||
assert registry.list_modules() == []
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ModuleRegistry - 自动激活 & 依赖
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleRegistryAutoActivate:
|
||||
"""注册时自动激活逻辑"""
|
||||
|
||||
def test_no_deps_auto_activates(self):
|
||||
registry = ModuleRegistry()
|
||||
mod = Module(name="standalone")
|
||||
registry.register(mod)
|
||||
assert mod.status == ModuleStatus.ACTIVE
|
||||
|
||||
def test_with_deps_all_satisfied_auto_activates(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="base")) # 无依赖,自动激活
|
||||
dep_mod = Module(name="dependent", dependencies=["base"])
|
||||
registry.register(dep_mod)
|
||||
assert dep_mod.status == ModuleStatus.ACTIVE
|
||||
|
||||
def test_with_deps_not_satisfied_stays_registered(self):
|
||||
registry = ModuleRegistry()
|
||||
mod = Module(name="dependent", dependencies=["missing_dep"])
|
||||
registry.register(mod)
|
||||
# 依赖不满足,保持 REGISTERED
|
||||
assert mod.status == ModuleStatus.REGISTERED
|
||||
|
||||
def test_later_dep_registered_manual_activate(self):
|
||||
"""先注册依赖模块,再注册被依赖模块时不自动激活前者
|
||||
(需要手动或在注册完所有模块后调用 check_dependencies + activate)"""
|
||||
registry = ModuleRegistry()
|
||||
# 先注册依赖方(依赖未满足,不激活)
|
||||
dependent = Module(name="dependent", dependencies=["base"])
|
||||
registry.register(dependent)
|
||||
assert dependent.status == ModuleStatus.REGISTERED
|
||||
|
||||
# 再注册被依赖方
|
||||
base = Module(name="base")
|
||||
registry.register(base)
|
||||
assert base.status == ModuleStatus.ACTIVE
|
||||
|
||||
# 依赖方仍然是 REGISTERED(不会自动激活)
|
||||
assert dependent.status == ModuleStatus.REGISTERED
|
||||
|
||||
|
||||
class TestModuleRegistryCheckDependencies:
|
||||
"""check_dependencies 依赖检查"""
|
||||
|
||||
def test_module_not_found_returns_false(self):
|
||||
registry = ModuleRegistry()
|
||||
assert registry.check_dependencies("nonexistent") is False
|
||||
|
||||
def test_no_deps_returns_true(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="standalone"))
|
||||
assert registry.check_dependencies("standalone") is True
|
||||
|
||||
def test_all_deps_active_returns_true(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="dep1"))
|
||||
registry.register(Module(name="dep2"))
|
||||
registry.register(Module(name="main", dependencies=["dep1", "dep2"]))
|
||||
# main 在注册时因依赖满足已自动激活
|
||||
assert registry.check_dependencies("main") is True
|
||||
|
||||
def test_dep_not_registered_returns_false(self):
|
||||
registry = ModuleRegistry()
|
||||
mod = Module(name="main", dependencies=["missing"])
|
||||
registry.register(mod)
|
||||
assert registry.check_dependencies("main") is False
|
||||
|
||||
def test_dep_registered_but_not_active_returns_false(self):
|
||||
registry = ModuleRegistry()
|
||||
dep = Module(name="dep", status=ModuleStatus.DISABLED)
|
||||
registry.register(dep)
|
||||
# 手动设为 disabled(因为 register 时无依赖会自动激活)
|
||||
dep.disable()
|
||||
main = Module(name="main", dependencies=["dep"])
|
||||
registry.register(main)
|
||||
# 依赖未激活
|
||||
assert registry.check_dependencies("main") is False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ModuleRegistry - list_modules & 状态过滤
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleRegistryList:
|
||||
"""list_modules 列表与过滤"""
|
||||
|
||||
def test_list_all(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="mod1"))
|
||||
registry.register(Module(name="mod2"))
|
||||
modules = registry.list_modules()
|
||||
assert len(modules) == 2
|
||||
names = {m.name for m in modules}
|
||||
assert names == {"mod1", "mod2"}
|
||||
|
||||
def test_filter_by_active(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="active_mod")) # 自动激活
|
||||
disabled = Module(name="disabled_mod")
|
||||
registry.register(disabled)
|
||||
disabled.disable()
|
||||
|
||||
active = registry.list_modules(status=ModuleStatus.ACTIVE)
|
||||
assert len(active) == 1
|
||||
assert active[0].name == "active_mod"
|
||||
|
||||
def test_filter_by_disabled(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="active_mod"))
|
||||
disabled = Module(name="disabled_mod")
|
||||
registry.register(disabled)
|
||||
disabled.disable()
|
||||
|
||||
disabled_list = registry.list_modules(status=ModuleStatus.DISABLED)
|
||||
assert len(disabled_list) == 1
|
||||
assert disabled_list[0].name == "disabled_mod"
|
||||
|
||||
def test_filter_registered(self):
|
||||
registry = ModuleRegistry()
|
||||
# 有依赖未满足的模块保持 REGISTERED
|
||||
mod = Module(name="waiting_mod", dependencies=["missing"])
|
||||
registry.register(mod)
|
||||
|
||||
registered = registry.list_modules(status=ModuleStatus.REGISTERED)
|
||||
assert len(registered) == 1
|
||||
assert registered[0].name == "waiting_mod"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ModuleRegistry - 能力发现
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleRegistryCapabilities:
|
||||
"""能力发现:has_capability / get_capability / get_quota_rules"""
|
||||
|
||||
def test_has_capability_true(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(
|
||||
Module(
|
||||
name="voice_module",
|
||||
capabilities=[ModuleCapability(name="generate_voice")],
|
||||
)
|
||||
)
|
||||
assert registry.has_capability("generate_voice") is True
|
||||
|
||||
def test_has_capability_false(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(
|
||||
Module(
|
||||
name="voice_module",
|
||||
capabilities=[ModuleCapability(name="generate_voice")],
|
||||
)
|
||||
)
|
||||
assert registry.has_capability("generate_video") is False
|
||||
|
||||
def test_has_capability_inactive_module_not_counted(self):
|
||||
registry = ModuleRegistry()
|
||||
mod = Module(
|
||||
name="inactive_mod",
|
||||
capabilities=[ModuleCapability(name="secret_cap")],
|
||||
)
|
||||
registry.register(mod)
|
||||
mod.disable()
|
||||
assert registry.has_capability("secret_cap") is False
|
||||
|
||||
def test_get_capability_returns_first_match(self):
|
||||
registry = ModuleRegistry()
|
||||
cap1 = ModuleCapability(name="export", description="导出1")
|
||||
cap2 = ModuleCapability(name="export", description="导出2")
|
||||
registry.register(Module(name="mod1", capabilities=[cap1]))
|
||||
registry.register(Module(name="mod2", capabilities=[cap2]))
|
||||
|
||||
result = registry.get_capability("export")
|
||||
assert result is not None
|
||||
assert result.name == "export"
|
||||
# 返回第一个匹配的(mod1)
|
||||
assert result.description == "导出1"
|
||||
|
||||
def test_get_capability_nonexistent_returns_none(self):
|
||||
registry = ModuleRegistry()
|
||||
assert registry.get_capability("no_such_cap") is None
|
||||
|
||||
def test_get_quota_rules(self):
|
||||
rules = [
|
||||
QuotaRule(dimension="credits", per_operation=1.0),
|
||||
QuotaRule(dimension="storage", per_operation=0.5),
|
||||
]
|
||||
registry = ModuleRegistry()
|
||||
registry.register(
|
||||
Module(
|
||||
name="voice_mod",
|
||||
capabilities=[ModuleCapability(name="gen", quota_rules=rules)],
|
||||
)
|
||||
)
|
||||
result = registry.get_quota_rules("gen")
|
||||
assert len(result) == 2
|
||||
assert result[0].dimension == "credits"
|
||||
assert result[1].dimension == "storage"
|
||||
|
||||
def test_get_quota_rules_nonexistent_returns_empty(self):
|
||||
registry = ModuleRegistry()
|
||||
assert registry.get_quota_rules("no_cap") == []
|
||||
|
||||
|
||||
# ============================================================
|
||||
# ModuleRegistry - get_active_capabilities
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestModuleRegistryActiveCapabilities:
|
||||
"""get_active_capabilities 已激活能力汇总"""
|
||||
|
||||
def test_empty_registry(self):
|
||||
registry = ModuleRegistry()
|
||||
assert registry.get_active_capabilities() == {}
|
||||
|
||||
def test_single_module_with_caps(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(
|
||||
Module(
|
||||
name="voice_mod",
|
||||
capabilities=[
|
||||
ModuleCapability(name="generate_voice"),
|
||||
ModuleCapability(name="clone_voice"),
|
||||
],
|
||||
)
|
||||
)
|
||||
result = registry.get_active_capabilities()
|
||||
assert "voice_mod" in result
|
||||
assert set(result["voice_mod"]) == {"generate_voice", "clone_voice"}
|
||||
|
||||
def test_skips_inactive_modules(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(
|
||||
Module(
|
||||
name="active_mod",
|
||||
capabilities=[ModuleCapability(name="active_cap")],
|
||||
)
|
||||
)
|
||||
inactive = Module(
|
||||
name="inactive_mod",
|
||||
capabilities=[ModuleCapability(name="inactive_cap")],
|
||||
)
|
||||
registry.register(inactive)
|
||||
inactive.disable()
|
||||
|
||||
result = registry.get_active_capabilities()
|
||||
assert "active_mod" in result
|
||||
assert "inactive_mod" not in result
|
||||
|
||||
def test_skips_modules_without_caps(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(Module(name="no_cap_mod"))
|
||||
result = registry.get_active_capabilities()
|
||||
assert "no_cap_mod" not in result
|
||||
|
||||
def test_multiple_modules(self):
|
||||
registry = ModuleRegistry()
|
||||
registry.register(
|
||||
Module(
|
||||
name="mod1",
|
||||
capabilities=[ModuleCapability(name="cap_a")],
|
||||
)
|
||||
)
|
||||
registry.register(
|
||||
Module(
|
||||
name="mod2",
|
||||
capabilities=[ModuleCapability(name="cap_b"), ModuleCapability(name="cap_c")],
|
||||
)
|
||||
)
|
||||
result = registry.get_active_capabilities()
|
||||
assert len(result) == 2
|
||||
assert result["mod1"] == ["cap_a"]
|
||||
assert set(result["mod2"]) == {"cap_b", "cap_c"}
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 全局单例
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestGlobalSingleton:
|
||||
"""全局 module_registry 单例"""
|
||||
|
||||
def test_singleton_exists(self):
|
||||
assert module_registry is not None
|
||||
assert isinstance(module_registry, ModuleRegistry)
|
||||
|
||||
def test_singleton_is_same_instance(self):
|
||||
from packages.infrastructure.module_registry import module_registry as mr2
|
||||
|
||||
assert module_registry is mr2
|
||||
Executable
+337
@@ -0,0 +1,337 @@
|
||||
"""
|
||||
pagination 通用分页器单元测试
|
||||
|
||||
覆盖:
|
||||
- PaginationParams: 默认值/边界/校验/offset/limit
|
||||
- PaginationMeta: from_params 各种边界场景
|
||||
- PaginatedResponse: create 工厂方法
|
||||
- paginate: 内存分页函数
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from pydantic import ValidationError
|
||||
|
||||
from packages.application.common.pagination import (
|
||||
PaginatedResponse,
|
||||
PaginationMeta,
|
||||
PaginationParams,
|
||||
paginate,
|
||||
)
|
||||
|
||||
# ============================================================
|
||||
# PaginationParams
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestPaginationParamsDefaults:
|
||||
"""默认值测试"""
|
||||
|
||||
def test_default_page_is_1(self):
|
||||
params = PaginationParams()
|
||||
assert params.page == 1
|
||||
|
||||
def test_default_page_size_is_20(self):
|
||||
params = PaginationParams()
|
||||
assert params.page_size == 20
|
||||
|
||||
def test_default_offset_is_0(self):
|
||||
params = PaginationParams()
|
||||
assert params.offset == 0
|
||||
|
||||
def test_default_limit_is_20(self):
|
||||
params = PaginationParams()
|
||||
assert params.limit == 20
|
||||
|
||||
|
||||
class TestPaginationParamsValidation:
|
||||
"""参数校验"""
|
||||
|
||||
@pytest.mark.parametrize("page", [1, 2, 100, 9999])
|
||||
def test_valid_page_values(self, page):
|
||||
params = PaginationParams(page=page)
|
||||
assert params.page == page
|
||||
|
||||
def test_page_zero_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
PaginationParams(page=0)
|
||||
|
||||
def test_page_negative_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
PaginationParams(page=-1)
|
||||
|
||||
@pytest.mark.parametrize("page_size", [1, 20, 50, 100])
|
||||
def test_valid_page_size_values(self, page_size):
|
||||
params = PaginationParams(page_size=page_size)
|
||||
assert params.page_size == page_size
|
||||
|
||||
def test_page_size_zero_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
PaginationParams(page_size=0)
|
||||
|
||||
def test_page_size_negative_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
PaginationParams(page_size=-5)
|
||||
|
||||
def test_page_size_over_100_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
PaginationParams(page_size=101)
|
||||
|
||||
def test_invalid_page_type_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
PaginationParams(page="abc")
|
||||
|
||||
def test_invalid_page_size_type_raises(self):
|
||||
with pytest.raises(ValidationError):
|
||||
PaginationParams(page_size="abc")
|
||||
|
||||
|
||||
class TestPaginationParamsOffset:
|
||||
"""offset 属性计算"""
|
||||
|
||||
def test_page_1_offset_0(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
assert params.offset == 0
|
||||
|
||||
def test_page_2_offset_page_size(self):
|
||||
params = PaginationParams(page=2, page_size=20)
|
||||
assert params.offset == 20
|
||||
|
||||
def test_page_3_offset_2x_page_size(self):
|
||||
params = PaginationParams(page=3, page_size=20)
|
||||
assert params.offset == 40
|
||||
|
||||
def test_page_5_page_size_10_offset_40(self):
|
||||
params = PaginationParams(page=5, page_size=10)
|
||||
assert params.offset == 40
|
||||
|
||||
def test_page_1_page_size_100_offset_0(self):
|
||||
params = PaginationParams(page=1, page_size=100)
|
||||
assert params.offset == 0
|
||||
|
||||
|
||||
class TestPaginationParamsLimit:
|
||||
"""limit 属性"""
|
||||
|
||||
def test_limit_equals_page_size(self):
|
||||
params = PaginationParams(page_size=20)
|
||||
assert params.limit == 20
|
||||
|
||||
def test_limit_1(self):
|
||||
params = PaginationParams(page_size=1)
|
||||
assert params.limit == 1
|
||||
|
||||
def test_limit_100(self):
|
||||
params = PaginationParams(page_size=100)
|
||||
assert params.limit == 100
|
||||
|
||||
|
||||
# ============================================================
|
||||
# PaginationMeta.from_params
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestPaginationMetaFromParams:
|
||||
"""from_params 工厂方法"""
|
||||
|
||||
def test_empty_total_zero(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=0)
|
||||
assert meta.total == 0
|
||||
assert meta.total_pages == 0
|
||||
assert meta.has_next is False
|
||||
assert meta.has_prev is False
|
||||
|
||||
def test_exactly_one_page(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=20)
|
||||
assert meta.total_pages == 1
|
||||
assert meta.has_next is False
|
||||
assert meta.has_prev is False
|
||||
|
||||
def test_less_than_one_page(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=15)
|
||||
assert meta.total_pages == 1
|
||||
assert meta.has_next is False
|
||||
assert meta.has_prev is False
|
||||
|
||||
def test_multiple_pages_first_page(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=50)
|
||||
assert meta.total_pages == 3
|
||||
assert meta.has_next is True
|
||||
assert meta.has_prev is False
|
||||
|
||||
def test_multiple_pages_middle_page(self):
|
||||
params = PaginationParams(page=2, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=50)
|
||||
assert meta.total_pages == 3
|
||||
assert meta.has_next is True
|
||||
assert meta.has_prev is True
|
||||
|
||||
def test_multiple_pages_last_page(self):
|
||||
params = PaginationParams(page=3, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=50)
|
||||
assert meta.total_pages == 3
|
||||
assert meta.has_next is False
|
||||
assert meta.has_prev is True
|
||||
|
||||
def test_exact_division(self):
|
||||
params = PaginationParams(page=2, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=40)
|
||||
assert meta.total_pages == 2
|
||||
assert meta.has_next is False
|
||||
assert meta.has_prev is True
|
||||
|
||||
def test_non_exact_division_ceil(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=41)
|
||||
assert meta.total_pages == 3
|
||||
|
||||
def test_total_1_page_size_20(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=1)
|
||||
assert meta.total_pages == 1
|
||||
assert meta.has_next is False
|
||||
assert meta.has_prev is False
|
||||
|
||||
def test_page_beyond_total_pages(self):
|
||||
params = PaginationParams(page=10, page_size=20)
|
||||
meta = PaginationMeta.from_params(params, total=50)
|
||||
assert meta.total_pages == 3
|
||||
assert meta.has_next is False
|
||||
assert meta.has_prev is True
|
||||
|
||||
def test_preserves_params_values(self):
|
||||
params = PaginationParams(page=3, page_size=15)
|
||||
meta = PaginationMeta.from_params(params, total=100)
|
||||
assert meta.page == 3
|
||||
assert meta.page_size == 15
|
||||
assert meta.total == 100
|
||||
|
||||
|
||||
# ============================================================
|
||||
# PaginatedResponse.create
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestPaginatedResponseCreate:
|
||||
"""create 工厂方法"""
|
||||
|
||||
def test_create_with_data(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
data = [1, 2, 3]
|
||||
response = PaginatedResponse.create(data, params, total=100)
|
||||
assert response.data == data
|
||||
assert response.pagination.total == 100
|
||||
assert response.pagination.page == 1
|
||||
assert response.pagination.page_size == 20
|
||||
|
||||
def test_create_with_empty_data(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
response = PaginatedResponse.create([], params, total=0)
|
||||
assert response.data == []
|
||||
assert response.pagination.total == 0
|
||||
assert response.pagination.total_pages == 0
|
||||
|
||||
def test_create_preserves_list_type(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
data = ["a", "b", "c"]
|
||||
response = PaginatedResponse.create(data, params, total=10)
|
||||
assert response.data == ["a", "b", "c"]
|
||||
assert len(response.data) == 3
|
||||
|
||||
|
||||
# ============================================================
|
||||
# paginate 函数
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestPaginateFunction:
|
||||
"""内存分页函数"""
|
||||
|
||||
def test_empty_list(self):
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
result = paginate([], params)
|
||||
assert result.data == []
|
||||
assert result.pagination.total == 0
|
||||
assert result.pagination.total_pages == 0
|
||||
|
||||
def test_first_page(self):
|
||||
items = list(range(50))
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
result = paginate(items, params)
|
||||
assert result.data == list(range(20))
|
||||
assert result.pagination.total == 50
|
||||
assert result.pagination.total_pages == 3
|
||||
assert result.pagination.has_next is True
|
||||
assert result.pagination.has_prev is False
|
||||
|
||||
def test_middle_page(self):
|
||||
items = list(range(50))
|
||||
params = PaginationParams(page=2, page_size=20)
|
||||
result = paginate(items, params)
|
||||
assert result.data == list(range(20, 40))
|
||||
assert result.pagination.has_next is True
|
||||
assert result.pagination.has_prev is True
|
||||
|
||||
def test_last_page(self):
|
||||
items = list(range(50))
|
||||
params = PaginationParams(page=3, page_size=20)
|
||||
result = paginate(items, params)
|
||||
assert result.data == list(range(40, 50))
|
||||
assert len(result.data) == 10
|
||||
assert result.pagination.has_next is False
|
||||
assert result.pagination.has_prev is True
|
||||
|
||||
def test_page_beyond_total(self):
|
||||
items = list(range(25))
|
||||
params = PaginationParams(page=10, page_size=20)
|
||||
result = paginate(items, params)
|
||||
assert result.data == []
|
||||
assert result.pagination.total == 25
|
||||
assert result.pagination.total_pages == 2
|
||||
|
||||
def test_page_size_larger_than_total(self):
|
||||
items = list(range(5))
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
result = paginate(items, params)
|
||||
assert result.data == items
|
||||
assert result.pagination.total_pages == 1
|
||||
assert result.pagination.has_next is False
|
||||
|
||||
def test_single_item(self):
|
||||
items = [42]
|
||||
params = PaginationParams(page=1, page_size=20)
|
||||
result = paginate(items, params)
|
||||
assert result.data == [42]
|
||||
assert result.pagination.total == 1
|
||||
|
||||
def test_page_size_1(self):
|
||||
items = list(range(5))
|
||||
params = PaginationParams(page=3, page_size=1)
|
||||
result = paginate(items, params)
|
||||
assert result.data == [2]
|
||||
assert result.pagination.total_pages == 5
|
||||
|
||||
def test_exact_page_size(self):
|
||||
items = list(range(40))
|
||||
params = PaginationParams(page=2, page_size=20)
|
||||
result = paginate(items, params)
|
||||
assert result.data == list(range(20, 40))
|
||||
assert result.pagination.total_pages == 2
|
||||
assert result.pagination.has_next is False
|
||||
|
||||
def test_string_items(self):
|
||||
items = ["a", "b", "c", "d", "e"]
|
||||
params = PaginationParams(page=2, page_size=2)
|
||||
result = paginate(items, params)
|
||||
assert result.data == ["c", "d"]
|
||||
assert result.pagination.total == 5
|
||||
|
||||
def test_does_not_mutate_original_list(self):
|
||||
items = list(range(10))
|
||||
original = items.copy()
|
||||
params = PaginationParams(page=1, page_size=3)
|
||||
paginate(items, params)
|
||||
assert items == original
|
||||
Executable
+539
@@ -0,0 +1,539 @@
|
||||
"""
|
||||
SharedStorageService 单元测试
|
||||
|
||||
重点覆盖纯逻辑部分:
|
||||
- _normalize_storage_key: URL提取 + URL解码
|
||||
- _is_local_generated_url: 本地生成URL判断
|
||||
- get_url: 公共URL拼接
|
||||
- create_direct_upload_post: policy + HMAC签名
|
||||
- get_download_url: bucket=None时的fallback
|
||||
- 未配置OSS时的错误处理
|
||||
- 单例模式
|
||||
"""
|
||||
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.shared.storage import (
|
||||
SharedStorageService,
|
||||
get_shared_storage_service,
|
||||
get_storage_service,
|
||||
)
|
||||
|
||||
# ============================================================
|
||||
# Fixtures
|
||||
# ============================================================
|
||||
|
||||
|
||||
def _make_service(
|
||||
bucket_name="test-bucket",
|
||||
endpoint="oss-cn-hangzhou.aliyuncs.com",
|
||||
access_key_id="test-key-id",
|
||||
access_key_secret="test-key-secret",
|
||||
local_url_prefix="/generated-files",
|
||||
with_bucket=True,
|
||||
):
|
||||
"""创建一个 SharedStorageService 实例,mock 掉 oss2 和 settings。"""
|
||||
mock_settings = MagicMock()
|
||||
mock_settings.oss_bucket_name = bucket_name
|
||||
mock_settings.oss_endpoint = endpoint
|
||||
mock_settings.oss_access_key_id = access_key_id
|
||||
mock_settings.oss_access_key_secret = access_key_secret
|
||||
|
||||
mock_bucket = MagicMock() if with_bucket else None
|
||||
|
||||
with (
|
||||
patch("packages.shared.storage.get_shared_settings", return_value=mock_settings),
|
||||
patch.dict(os.environ, {"GENERATED_FILES_URL_PREFIX": local_url_prefix}, clear=False),
|
||||
):
|
||||
if with_bucket:
|
||||
with patch("packages.shared.storage.oss2") as mock_oss2:
|
||||
mock_oss2.Auth.return_value = MagicMock()
|
||||
mock_oss2.Bucket.return_value = mock_bucket
|
||||
service = SharedStorageService()
|
||||
service.bucket = mock_bucket
|
||||
return service, mock_bucket, mock_settings
|
||||
else:
|
||||
service = SharedStorageService()
|
||||
service.bucket = None
|
||||
return service, None, mock_settings
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _normalize_storage_key
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestNormalizeStorageKey:
|
||||
"""_normalize_storage_key URL 提取与解码"""
|
||||
|
||||
def test_plain_key_returns_as_is(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("videos/clip.mp4")
|
||||
assert result == "videos/clip.mp4"
|
||||
|
||||
def test_key_with_leading_slash_stripped(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("/videos/clip.mp4")
|
||||
assert result == "videos/clip.mp4"
|
||||
|
||||
def test_https_url_extracts_path(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://test-bucket.oss-cn-hangzhou.aliyuncs.com/videos/clip.mp4")
|
||||
assert result == "videos/clip.mp4"
|
||||
|
||||
def test_http_url_extracts_path(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("http://test-bucket.oss-cn-hangzhou.aliyuncs.com/audio/voice.mp3")
|
||||
assert result == "audio/voice.mp3"
|
||||
|
||||
def test_url_with_query_strips_query(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss-cn.com/file.mp4?signature=abc&expires=123")
|
||||
assert result == "file.mp4"
|
||||
|
||||
def test_url_with_leading_slash_in_path(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss.com//double/slash.jpg")
|
||||
assert result == "double/slash.jpg"
|
||||
|
||||
def test_url_decodes_percent_encoded_spaces(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss.com/my%20video.mp4")
|
||||
assert result == "my video.mp4"
|
||||
|
||||
def test_url_decodes_percent_encoded_chinese(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss.com/%E4%B8%AD%E6%96%87.mp4")
|
||||
assert result == "中文.mp4"
|
||||
|
||||
def test_url_with_special_chars_decoded(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss.com/file%281%29.jpg")
|
||||
assert result == "file(1).jpg"
|
||||
|
||||
def test_plain_key_with_percent_not_decoded(self):
|
||||
"""原始 key 不以 http 开头,不做 URL 解码,直接 lstrip('/')"""
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("file%20name.mp4")
|
||||
# 不是 URL,直接返回(去掉前导/)
|
||||
assert result == "file%20name.mp4"
|
||||
|
||||
def test_empty_string(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("")
|
||||
assert result == ""
|
||||
|
||||
def test_root_slash_url(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss.com/")
|
||||
assert result == ""
|
||||
|
||||
def test_nested_path_url(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss.com/a/b/c/d/file.txt")
|
||||
assert result == "a/b/c/d/file.txt"
|
||||
|
||||
def test_url_with_port(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service._normalize_storage_key("https://bucket.oss.com:443/file.txt")
|
||||
assert result == "file.txt"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# _is_local_generated_url
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestIsLocalGeneratedUrl:
|
||||
"""_is_local_generated_url 本地URL判断"""
|
||||
|
||||
def test_local_prefix_returns_true(self):
|
||||
service, _, _ = _make_service()
|
||||
assert service._is_local_generated_url("/generated-files/abc.mp4") is True
|
||||
|
||||
def test_relative_local_returns_true(self):
|
||||
service, _, _ = _make_service()
|
||||
# 没有 scheme,直接用原字符串匹配
|
||||
assert service._is_local_generated_url("/generated-files/out.mp4") is True
|
||||
|
||||
def test_full_url_with_local_path_returns_true(self):
|
||||
service, _, _ = _make_service()
|
||||
assert service._is_local_generated_url("https://example.com/generated-files/abc.mp4") is True
|
||||
|
||||
def test_other_path_returns_false(self):
|
||||
service, _, _ = _make_service()
|
||||
assert service._is_local_generated_url("/videos/abc.mp4") is False
|
||||
|
||||
def test_empty_string_returns_false(self):
|
||||
service, _, _ = _make_service()
|
||||
assert service._is_local_generated_url("") is False
|
||||
|
||||
def test_custom_prefix(self):
|
||||
service, _, _ = _make_service(local_url_prefix="/custom-prefix")
|
||||
assert service._is_local_generated_url("/custom-prefix/file.mp4") is True
|
||||
assert service._is_local_generated_url("/generated-files/file.mp4") is False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# get_url
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestGetUrl:
|
||||
"""get_url 公共URL拼接"""
|
||||
|
||||
def test_returns_public_url_plus_key(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.get_url("videos/test.mp4")
|
||||
assert result == "https://test-bucket.oss-cn-hangzhou.aliyuncs.com/videos/test.mp4"
|
||||
|
||||
def test_empty_key(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.get_url("")
|
||||
assert result == "https://test-bucket.oss-cn-hangzhou.aliyuncs.com/"
|
||||
|
||||
def test_custom_bucket_and_endpoint(self):
|
||||
service, _, _ = _make_service(
|
||||
bucket_name="my-bucket",
|
||||
endpoint="oss-us-east-1.aliyuncs.com",
|
||||
)
|
||||
result = service.get_url("file.txt")
|
||||
assert result == "https://my-bucket.oss-us-east-1.aliyuncs.com/file.txt"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# create_direct_upload_post
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestCreateDirectUploadPost:
|
||||
"""create_direct_upload_post 直传表单生成"""
|
||||
|
||||
def test_returns_dict_with_expected_keys(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post(
|
||||
storage_key="uploads/test.jpg",
|
||||
content_type="image/jpeg",
|
||||
max_size_bytes=10 * 1024 * 1024,
|
||||
expires_seconds=3600,
|
||||
)
|
||||
assert "url" in result
|
||||
assert "method" in result
|
||||
assert "storage_key" in result
|
||||
assert "expires_at" in result
|
||||
assert "fields" in result
|
||||
|
||||
def test_method_is_post(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 1024, 3600)
|
||||
assert result["method"] == "POST"
|
||||
|
||||
def test_url_is_public_url(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 1024, 3600)
|
||||
assert result["url"] == "https://test-bucket.oss-cn-hangzhou.aliyuncs.com"
|
||||
|
||||
def test_storage_key_normalized(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post("/uploads/test.jpg", "image/jpeg", 1024, 3600)
|
||||
assert result["storage_key"] == "uploads/test.jpg"
|
||||
assert result["fields"]["key"] == "uploads/test.jpg"
|
||||
|
||||
def test_fields_contain_required_keys(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 1024, 3600)
|
||||
fields = result["fields"]
|
||||
assert fields["key"] == "uploads/a.jpg"
|
||||
assert fields["OSSAccessKeyId"] == "test-key-id"
|
||||
assert fields["success_action_status"] == "201"
|
||||
assert fields["Content-Type"] == "image/jpeg"
|
||||
assert "policy" in fields
|
||||
assert "Signature" in fields
|
||||
|
||||
def test_policy_signature_is_valid_hmac_sha1(self):
|
||||
"""验证 HMAC-SHA1 签名是否正确"""
|
||||
secret = "my-secret-key-123"
|
||||
service, _, _ = _make_service(access_key_secret=secret)
|
||||
result = service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 1024, 3600)
|
||||
policy = result["fields"]["policy"]
|
||||
signature = result["fields"]["Signature"]
|
||||
|
||||
# 手动计算签名验证
|
||||
expected = base64.b64encode(
|
||||
hmac.new(secret.encode("utf-8"), policy.encode("utf-8"), hashlib.sha1).digest()
|
||||
).decode("ascii")
|
||||
assert signature == expected
|
||||
|
||||
def test_policy_contains_bucket_and_key(self):
|
||||
service, _, _ = _make_service(bucket_name="my-bucket")
|
||||
result = service.create_direct_upload_post("uploads/photo.png", "image/png", 2048, 1800)
|
||||
policy = json.loads(base64.b64decode(result["fields"]["policy"]))
|
||||
conditions = policy["conditions"]
|
||||
|
||||
assert {"bucket": "my-bucket"} in conditions
|
||||
assert {"key": "uploads/photo.png"} in conditions
|
||||
|
||||
def test_policy_contains_content_length_range(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 5242880, 3600)
|
||||
policy = json.loads(base64.b64decode(result["fields"]["policy"]))
|
||||
conditions = policy["conditions"]
|
||||
|
||||
size_condition = [c for c in conditions if isinstance(c, list) and c[0] == "content-length-range"]
|
||||
assert len(size_condition) == 1
|
||||
assert size_condition[0][1] == 1
|
||||
assert size_condition[0][2] == 5242880
|
||||
|
||||
def test_policy_content_type_starts_with(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 1024, 3600)
|
||||
policy = json.loads(base64.b64decode(result["fields"]["policy"]))
|
||||
conditions = policy["conditions"]
|
||||
|
||||
ct_condition = [c for c in conditions if isinstance(c, list) and c[0] == "starts-with"]
|
||||
assert len(ct_condition) == 1
|
||||
assert ct_condition[0][1] == "$Content-Type"
|
||||
assert ct_condition[0][2] == "image/"
|
||||
|
||||
def test_policy_has_expiration(self):
|
||||
service, _, _ = _make_service()
|
||||
result = service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 1024, 3600)
|
||||
policy = json.loads(base64.b64decode(result["fields"]["policy"]))
|
||||
assert "expiration" in policy
|
||||
# ISO 8601 格式
|
||||
assert policy["expiration"].endswith("Z")
|
||||
|
||||
def test_non_uploads_key_raises_value_error(self):
|
||||
service, _, _ = _make_service()
|
||||
with pytest.raises(ValueError, match="uploads/"):
|
||||
service.create_direct_upload_post("videos/a.mp4", "video/mp4", 1024, 3600)
|
||||
|
||||
def test_no_credentials_raises_runtime_error(self):
|
||||
service, _, _ = _make_service(access_key_id="", access_key_secret="", with_bucket=False)
|
||||
with pytest.raises(RuntimeError, match="not configured"):
|
||||
service.create_direct_upload_post("uploads/a.jpg", "image/jpeg", 1024, 3600)
|
||||
|
||||
def test_url_normalized_key_in_uploads(self):
|
||||
service, _, _ = _make_service()
|
||||
# URL 形式的 key 被 normalize 后如果在 uploads/ 下应该可以
|
||||
result = service.create_direct_upload_post(
|
||||
"https://test-bucket.oss-cn-hangzhou.aliyuncs.com/uploads/from_url.jpg",
|
||||
"image/jpeg",
|
||||
1024,
|
||||
3600,
|
||||
)
|
||||
assert result["storage_key"] == "uploads/from_url.jpg"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# get_download_url (bucket=None 时的 fallback)
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestGetDownloadUrlFallback:
|
||||
"""get_download_url 在 bucket 未配置时的 fallback 逻辑"""
|
||||
|
||||
def test_no_bucket_local_url_returns_as_is(self):
|
||||
service, _, _ = _make_service(with_bucket=False)
|
||||
result = service.get_download_url("/generated-files/test.mp4")
|
||||
assert result == "/generated-files/test.mp4"
|
||||
|
||||
def test_no_bucket_regular_key_returns_public_url(self):
|
||||
service, _, _ = _make_service(with_bucket=False)
|
||||
result = service.get_download_url("videos/test.mp4")
|
||||
assert result == "https://test-bucket.oss-cn-hangzhou.aliyuncs.com/videos/test.mp4"
|
||||
|
||||
def test_no_bucket_url_input_normalized(self):
|
||||
service, _, _ = _make_service(with_bucket=False)
|
||||
result = service.get_download_url("https://test-bucket.oss-cn-hangzhou.aliyuncs.com/videos/test.mp4")
|
||||
assert result == "https://test-bucket.oss-cn-hangzhou.aliyuncs.com/videos/test.mp4"
|
||||
|
||||
def test_with_bucket_calls_sign_url(self):
|
||||
service, mock_bucket, _ = _make_service(with_bucket=True)
|
||||
mock_bucket.sign_url.return_value = "https://signed-url.com/file?sig=abc"
|
||||
|
||||
result = service.get_download_url("videos/test.mp4", expires_seconds=7200)
|
||||
|
||||
mock_bucket.sign_url.assert_called_once_with("GET", "videos/test.mp4", 7200)
|
||||
assert result == "https://signed-url.com/file?sig=abc"
|
||||
|
||||
def test_sign_url_exception_falls_back_to_public_url(self):
|
||||
service, mock_bucket, _ = _make_service(with_bucket=True)
|
||||
mock_bucket.sign_url.side_effect = Exception("sign error")
|
||||
|
||||
result = service.get_download_url("videos/test.mp4")
|
||||
|
||||
assert result == "https://test-bucket.oss-cn-hangzhou.aliyuncs.com/videos/test.mp4"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 未配置 OSS 时的错误处理
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestNoBucketErrorHandling:
|
||||
"""bucket=None 时的错误处理"""
|
||||
|
||||
def test_upload_file_raises(self):
|
||||
service, _, _ = _make_service(with_bucket=False)
|
||||
with pytest.raises(RuntimeError, match="not configured"):
|
||||
service.upload_file("/tmp/test.txt", "uploads/test.txt")
|
||||
|
||||
def test_download_file_raises(self):
|
||||
service, _, _ = _make_service(with_bucket=False)
|
||||
with pytest.raises(RuntimeError, match="not configured"):
|
||||
service.download_file("uploads/test.txt", "/tmp/test.txt")
|
||||
|
||||
def test_delete_file_silent_noop(self):
|
||||
service, _, _ = _make_service(with_bucket=False)
|
||||
# 不抛异常
|
||||
result = service.delete_file("uploads/test.txt")
|
||||
assert result is None
|
||||
|
||||
def test_file_exists_returns_false(self):
|
||||
service, _, _ = _make_service(with_bucket=False)
|
||||
assert service.file_exists("uploads/test.txt") is False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# upload_file / delete_file / file_exists 正常路径
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestBucketOperations:
|
||||
"""有 bucket 时的操作调用验证"""
|
||||
|
||||
def test_upload_file_with_path_string(self):
|
||||
service, mock_bucket, _ = _make_service()
|
||||
result = service.upload_file("/tmp/file.txt", "uploads/file.txt", "text/plain")
|
||||
|
||||
mock_bucket.put_object_from_file.assert_called_once()
|
||||
args = mock_bucket.put_object_from_file.call_args
|
||||
assert args[0][0] == "uploads/file.txt"
|
||||
assert args[0][1] == "/tmp/file.txt"
|
||||
assert result.startswith("https://test-bucket.")
|
||||
|
||||
def test_upload_file_with_file_object(self):
|
||||
service, mock_bucket, _ = _make_service()
|
||||
mock_file = MagicMock()
|
||||
result = service.upload_file(mock_file, "uploads/file.bin", "application/octet-stream")
|
||||
|
||||
mock_file.seek.assert_called_once_with(0)
|
||||
mock_bucket.put_object.assert_called_once()
|
||||
assert result.startswith("https://test-bucket.")
|
||||
|
||||
def test_delete_file_calls_bucket(self):
|
||||
service, mock_bucket, _ = _make_service()
|
||||
service.delete_file("uploads/test.txt")
|
||||
mock_bucket.delete_object.assert_called_once_with("uploads/test.txt")
|
||||
|
||||
def test_delete_file_exception_logged_not_raised(self):
|
||||
service, mock_bucket, _ = _make_service()
|
||||
mock_bucket.delete_object.side_effect = Exception("delete error")
|
||||
# 不抛异常
|
||||
service.delete_file("uploads/test.txt")
|
||||
|
||||
def test_file_exists_delegates_to_bucket(self):
|
||||
service, mock_bucket, _ = _make_service()
|
||||
mock_bucket.object_exists.return_value = True
|
||||
assert service.file_exists("some/key") is True
|
||||
mock_bucket.object_exists.assert_called_once_with("some/key")
|
||||
|
||||
def test_file_exists_false(self):
|
||||
service, mock_bucket, _ = _make_service()
|
||||
mock_bucket.object_exists.return_value = False
|
||||
assert service.file_exists("some/key") is False
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 单例 & 兼容别名
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestSingleton:
|
||||
"""get_shared_storage_service 单例模式"""
|
||||
|
||||
def test_get_storage_service_is_alias(self):
|
||||
# 两个函数返回同一个实例
|
||||
with patch("packages.shared.storage._storage_service", None):
|
||||
with patch("packages.shared.storage.SharedStorageService") as mock_cls:
|
||||
mock_instance = MagicMock()
|
||||
mock_cls.return_value = mock_instance
|
||||
|
||||
svc1 = get_shared_storage_service()
|
||||
svc2 = get_storage_service()
|
||||
|
||||
assert svc1 is svc2
|
||||
# 因为是同一个单例,类只实例化一次
|
||||
assert mock_cls.call_count == 1
|
||||
|
||||
|
||||
# ============================================================
|
||||
# __init__ endpoint 处理
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestInitEndpointHandling:
|
||||
"""初始化时 endpoint https 前缀处理"""
|
||||
|
||||
def test_endpoint_without_https_gets_prefix(self):
|
||||
mock_settings = MagicMock()
|
||||
mock_settings.oss_bucket_name = "test-bucket"
|
||||
mock_settings.oss_endpoint = "oss-cn-hangzhou.aliyuncs.com"
|
||||
mock_settings.oss_access_key_id = "key-id"
|
||||
mock_settings.oss_access_key_secret = "key-secret"
|
||||
|
||||
with (
|
||||
patch("packages.shared.storage.get_shared_settings", return_value=mock_settings),
|
||||
patch("packages.shared.storage.oss2") as mock_oss2,
|
||||
):
|
||||
mock_oss2.Bucket.return_value = MagicMock()
|
||||
|
||||
service = SharedStorageService()
|
||||
|
||||
# 验证 Bucket 构造时 endpoint 带了 https://
|
||||
call_args = mock_oss2.Bucket.call_args
|
||||
assert call_args[0][1] == "https://oss-cn-hangzhou.aliyuncs.com"
|
||||
|
||||
def test_endpoint_with_https_keeps_as_is(self):
|
||||
mock_settings = MagicMock()
|
||||
mock_settings.oss_bucket_name = "test-bucket"
|
||||
mock_settings.oss_endpoint = "https://oss-cn-hangzhou.aliyuncs.com"
|
||||
mock_settings.oss_access_key_id = "key-id"
|
||||
mock_settings.oss_access_key_secret = "key-secret"
|
||||
|
||||
with (
|
||||
patch("packages.shared.storage.get_shared_settings", return_value=mock_settings),
|
||||
patch("packages.shared.storage.oss2") as mock_oss2,
|
||||
):
|
||||
mock_oss2.Bucket.return_value = MagicMock()
|
||||
|
||||
service = SharedStorageService()
|
||||
|
||||
call_args = mock_oss2.Bucket.call_args
|
||||
assert call_args[0][1] == "https://oss-cn-hangzhou.aliyuncs.com"
|
||||
|
||||
def test_endpoint_with_http_keeps_as_is(self):
|
||||
mock_settings = MagicMock()
|
||||
mock_settings.oss_bucket_name = "test-bucket"
|
||||
mock_settings.oss_endpoint = "http://oss-cn-hangzhou.aliyuncs.com"
|
||||
mock_settings.oss_access_key_id = "key-id"
|
||||
mock_settings.oss_access_key_secret = "key-secret"
|
||||
|
||||
with (
|
||||
patch("packages.shared.storage.get_shared_settings", return_value=mock_settings),
|
||||
patch("packages.shared.storage.oss2") as mock_oss2,
|
||||
):
|
||||
mock_oss2.Bucket.return_value = MagicMock()
|
||||
|
||||
service = SharedStorageService()
|
||||
|
||||
call_args = mock_oss2.Bucket.call_args
|
||||
assert call_args[0][1] == "http://oss-cn-hangzhou.aliyuncs.com"
|
||||
Executable
+315
@@ -0,0 +1,315 @@
|
||||
"""
|
||||
text_splitter 长文本分段工具单元测试
|
||||
|
||||
覆盖:
|
||||
- 空文本 / 短文本
|
||||
- 句子边界分段(。!?;\n . ! ? ;)
|
||||
- 超长句子硬切
|
||||
- 过短段落合并
|
||||
- max_chars 参数
|
||||
- 中英文混合
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from packages.application.tts_job.text_splitter import split_text
|
||||
|
||||
# ============================================================
|
||||
# 基础场景
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestBasicCases:
|
||||
"""基础场景"""
|
||||
|
||||
def test_empty_text_returns_empty_list(self):
|
||||
assert split_text("") == []
|
||||
|
||||
def test_whitespace_only_returns_empty(self):
|
||||
assert split_text(" \n\n ") == []
|
||||
|
||||
def test_short_text_single_segment(self):
|
||||
text = "这是一段短文本。"
|
||||
result = split_text(text, max_chars=500)
|
||||
assert result == [text]
|
||||
|
||||
def test_exactly_max_chars_single_segment(self):
|
||||
text = "a" * 500
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
assert len(result[0]) == 500
|
||||
|
||||
def test_text_stripped(self):
|
||||
text = " 你好世界。 "
|
||||
result = split_text(text, max_chars=500)
|
||||
assert result == ["你好世界。"]
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 句子边界分段
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestSentenceBoundarySplitting:
|
||||
"""句子边界分段"""
|
||||
|
||||
def test_split_by_chinese_period(self):
|
||||
text = "第一句。第二句。第三句。"
|
||||
# 三句都很短,应该合并成一段
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_split_by_chinese_period_long_text(self):
|
||||
"""多段长句子,按句号分段"""
|
||||
sentence1 = "我是第一句" + "啊" * 100 + "。"
|
||||
sentence2 = "我是第二句" + "哦" * 100 + "。"
|
||||
sentence3 = "我是第三句" + "嗯" * 100 + "。"
|
||||
text = sentence1 + sentence2 + sentence3
|
||||
|
||||
result = split_text(text, max_chars=150)
|
||||
# 每句106字符,超过150的阈值?不,106<150
|
||||
# 但累计到一定程度会切
|
||||
assert len(result) >= 2
|
||||
# 每段都不超过 max_chars
|
||||
for seg in result:
|
||||
assert len(seg) <= 150
|
||||
|
||||
def test_split_by_question_mark(self):
|
||||
text = "你是谁?你从哪里来?你要到哪里去?"
|
||||
result = split_text(text, max_chars=500)
|
||||
# 三句都很短,合并成一段
|
||||
assert len(result) == 1
|
||||
|
||||
def test_split_by_exclamation_mark(self):
|
||||
text = "太棒了!太厉害了!太牛了!"
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_split_by_newline(self):
|
||||
text = "第一段\n第二段\n第三段"
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_split_by_semicolon(self):
|
||||
text = "第一部分;第二部分;第三部分。"
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_mixed_punctuation(self):
|
||||
"""混合标点符号的句子边界"""
|
||||
parts = []
|
||||
for i in range(20):
|
||||
parts.append(f"第{i}句的内容" + "字" * 30 + "。")
|
||||
text = "".join(parts)
|
||||
|
||||
result = split_text(text, max_chars=200)
|
||||
# 每句约35字符,200字符大约能放5-6句
|
||||
assert len(result) >= 2
|
||||
for seg in result:
|
||||
assert len(seg) <= 200
|
||||
|
||||
def test_english_period_splitting(self):
|
||||
text = "Hello. How are you. I am fine."
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
|
||||
def test_english_question(self):
|
||||
text = "What? Why? How?"
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 超长硬切
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestLongSentenceHardCut:
|
||||
"""超长句子硬切"""
|
||||
|
||||
def test_single_very_long_sentence_hard_cut(self):
|
||||
"""单个超长句子,没有标点,硬切"""
|
||||
text = "字" * 1000
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 2
|
||||
assert len(result[0]) == 500
|
||||
assert len(result[1]) == 500
|
||||
|
||||
def test_three_times_max_chars(self):
|
||||
text = "字" * 1500
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 3
|
||||
for seg in result:
|
||||
assert len(seg) == 500
|
||||
|
||||
def test_not_exact_multiple(self):
|
||||
text = "字" * 1250
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 3
|
||||
assert len(result[0]) == 500
|
||||
assert len(result[1]) == 500
|
||||
assert len(result[2]) == 250
|
||||
|
||||
def test_all_segments_within_limit(self):
|
||||
"""所有段都不超过 max_chars"""
|
||||
import random
|
||||
|
||||
random.seed(42)
|
||||
# 生成随机长度的文本
|
||||
text = "".join(random.choices("字字字字。!?;\n", k=5000))
|
||||
for max_chars in [100, 200, 500]:
|
||||
result = split_text(text, max_chars=max_chars)
|
||||
for i, seg in enumerate(result):
|
||||
assert len(seg) <= max_chars, f"Segment {i} length {len(seg)} > {max_chars}"
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 过短段落合并
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestShortSegmentMerging:
|
||||
"""过短段落合并"""
|
||||
|
||||
def test_short_final_segment_merged(self):
|
||||
"""最后一段过短,应该合并到前一段"""
|
||||
# 构造:前一段接近上限,后一段很短
|
||||
long_part = "字" * 480 + "。"
|
||||
short_part = "好的。"
|
||||
text = long_part + short_part
|
||||
|
||||
result = split_text(text, max_chars=500)
|
||||
# 两段加起来 481+3=484 < 500,可能合并
|
||||
# 但要看具体实现...
|
||||
# 至少验证所有段不超长
|
||||
for seg in result:
|
||||
assert len(seg) <= 500
|
||||
|
||||
def test_multiple_short_segments(self):
|
||||
"""多个短段落应该合并"""
|
||||
sentences = ["你好。", "我好。", "大家好。", "今天天气不错。", "适合出去玩。"]
|
||||
text = "".join(sentences)
|
||||
result = split_text(text, max_chars=500)
|
||||
# 5个短句子,应该合并成一段
|
||||
assert len(result) == 1
|
||||
|
||||
|
||||
# ============================================================
|
||||
# max_chars 参数
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestMaxCharsParameter:
|
||||
"""max_chars 参数"""
|
||||
|
||||
def test_small_max_chars(self):
|
||||
text = "一二三四五六七八九十一二三四五六七八九十。"
|
||||
result = split_text(text, max_chars=10)
|
||||
# 应该被切成多段
|
||||
assert len(result) >= 2
|
||||
for seg in result:
|
||||
assert len(seg) <= 10
|
||||
|
||||
def test_custom_max_chars_200(self):
|
||||
text = "测试文本" * 100 # 400字符
|
||||
result = split_text(text, max_chars=200)
|
||||
assert len(result) == 2
|
||||
assert len(result[0]) == 200
|
||||
assert len(result[1]) == 200
|
||||
|
||||
def test_very_small_max_chars(self):
|
||||
text = "abcdefghij"
|
||||
result = split_text(text, max_chars=3)
|
||||
assert len(result) >= 3
|
||||
for seg in result:
|
||||
assert len(seg) <= 3
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 中英文混合
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestMixedContent:
|
||||
"""中英文混合内容"""
|
||||
|
||||
def test_chinese_english_mixed(self):
|
||||
text = "今天天气很好,Today is sunny. 我们去公园玩吧!Let's go to the park."
|
||||
result = split_text(text, max_chars=500)
|
||||
assert len(result) == 1
|
||||
assert result[0] == text.strip()
|
||||
|
||||
def test_mixed_long_text(self):
|
||||
parts = []
|
||||
for i in range(50):
|
||||
parts.append(f"第{i}段中文内容" + "字" * 20 + ". English part " + "word " * 10 + "。")
|
||||
text = "".join(parts)
|
||||
|
||||
result = split_text(text, max_chars=300)
|
||||
assert len(result) >= 2
|
||||
for seg in result:
|
||||
assert len(seg) <= 300
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 输出完整性
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestOutputIntegrity:
|
||||
"""输出完整性验证"""
|
||||
|
||||
def test_combined_length_equals_original(self):
|
||||
"""所有段拼接起来(去掉空段)应该等于原文长度"""
|
||||
text = "这是第一段。这是第二段。这是第三段。这是第四段。这是第五段。" * 20
|
||||
result = split_text(text, max_chars=100)
|
||||
combined = "".join(result)
|
||||
# 由于 strip 可能去掉一些空格,原文也 strip 比较
|
||||
assert len(combined) == len(text.strip())
|
||||
|
||||
def test_order_preserved(self):
|
||||
"""分段后再拼接,文本顺序不变"""
|
||||
text = "第一。第二。第三。第四。第五。" * 10
|
||||
result = split_text(text, max_chars=50)
|
||||
combined = "".join(result)
|
||||
assert combined == text.strip()
|
||||
|
||||
def test_no_empty_strings_in_result(self):
|
||||
"""结果中没有空字符串"""
|
||||
text = "句子一。句子二。句子三。"
|
||||
result = split_text(text, max_chars=10)
|
||||
for seg in result:
|
||||
assert seg != ""
|
||||
assert len(seg) > 0
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 边界情况
|
||||
# ============================================================
|
||||
|
||||
|
||||
class TestEdgeCases:
|
||||
"""边界情况"""
|
||||
|
||||
def test_single_character(self):
|
||||
assert split_text("一", max_chars=500) == ["一"]
|
||||
|
||||
def test_only_punctuation(self):
|
||||
text = "。。。。。"
|
||||
result = split_text(text, max_chars=500)
|
||||
# 都是标点,也算文本
|
||||
assert len(result) == 1
|
||||
|
||||
def test_only_newlines(self):
|
||||
text = "\n\n\n"
|
||||
result = split_text(text, max_chars=500)
|
||||
assert result == []
|
||||
|
||||
def test_long_text_many_sentences(self):
|
||||
"""大量句子的长文本"""
|
||||
sentences = [f"第{i}句的完整内容。" for i in range(100)]
|
||||
text = "".join(sentences)
|
||||
result = split_text(text, max_chars=200)
|
||||
assert len(result) >= 5
|
||||
for seg in result:
|
||||
assert len(seg) <= 200
|
||||
+553
-252
@@ -1,296 +1,597 @@
|
||||
"""URL 安全校验工具单元测试 — SSRF 防护."""
|
||||
"""
|
||||
url_security URL安全校验单元测试
|
||||
|
||||
from __future__ import annotations
|
||||
覆盖:
|
||||
- validate_url_safety: scheme/主机/端口/SSRF/内网域名/白名单
|
||||
- is_url_safe: 便捷函数
|
||||
- UrlSecurityError / NoRedirectHandler
|
||||
- _validate_magic_number: 文件魔数校验
|
||||
- safe_download_file / safe_download_bytes: mock 网络测试
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "apps", "worker"))
|
||||
|
||||
import shutil
|
||||
import tempfile
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from video_processing.url_security import ( # noqa: E402
|
||||
import pytest
|
||||
|
||||
from packages.shared.url_security import (
|
||||
ALLOWED_AUDIO_MIME_TYPES,
|
||||
ALLOWED_IMAGE_MIME_TYPES,
|
||||
ALLOWED_PORTS,
|
||||
ALLOWED_SCHEMES,
|
||||
MAX_URL_LENGTH,
|
||||
NoRedirectHandler,
|
||||
UrlSecurityError,
|
||||
_check_internal_hostnames,
|
||||
_is_trusted_domain,
|
||||
_validate_magic_number,
|
||||
is_url_safe,
|
||||
safe_download_bytes,
|
||||
safe_download_file,
|
||||
validate_url_safety,
|
||||
)
|
||||
|
||||
|
||||
class TestUrlSecurityValidation(unittest.TestCase):
|
||||
"""URL 安全校验测试."""
|
||||
|
||||
# ── Scheme 白名单 ──────────────────────────────────────────────────────
|
||||
|
||||
def test_http_scheme_allowed(self):
|
||||
"""HTTP scheme 应该被允许."""
|
||||
result = validate_url_safety("http://example.com/test", purpose="test")
|
||||
self.assertEqual(result, "http://example.com/test")
|
||||
|
||||
def test_https_scheme_allowed(self):
|
||||
"""HTTPS scheme 应该被允许."""
|
||||
result = validate_url_safety("https://example.com/test", purpose="test")
|
||||
self.assertEqual(result, "https://example.com/test")
|
||||
|
||||
def test_file_scheme_rejected(self):
|
||||
"""file:// scheme 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("file:///etc/passwd", purpose="test")
|
||||
|
||||
def test_ftp_scheme_rejected(self):
|
||||
"""ftp:// scheme 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("ftp://example.com/test", purpose="test")
|
||||
|
||||
def test_empty_scheme_rejected(self):
|
||||
"""空 scheme 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("example.com/test", purpose="test")
|
||||
|
||||
# ── 端口白名单 ────────────────────────────────────────────────────────
|
||||
|
||||
def test_port_80_allowed(self):
|
||||
"""端口 80 应该被允许."""
|
||||
# 80端口是默认HTTP端口,不显式指定也可以
|
||||
result = validate_url_safety("http://example.com:80/test", purpose="test")
|
||||
self.assertIn("example.com", result)
|
||||
|
||||
def test_port_443_allowed(self):
|
||||
"""端口 443 应该被允许."""
|
||||
result = validate_url_safety("https://example.com:443/test", purpose="test")
|
||||
self.assertIn("example.com", result)
|
||||
|
||||
def test_port_8080_rejected(self):
|
||||
"""非标准端口 8080 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://example.com:8080/test", purpose="test")
|
||||
|
||||
def test_port_22_rejected(self):
|
||||
"""SSH 端口 22 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://example.com:22/test", purpose="test")
|
||||
|
||||
# ── SSRF: 直接 IP 访问 ───────────────────────────────────────────────
|
||||
|
||||
def test_loopback_ip_rejected(self):
|
||||
"""回环地址 127.0.0.1 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://127.0.0.1/test", purpose="test")
|
||||
|
||||
def test_private_ip_192_rejected(self):
|
||||
"""内网地址 192.168.x.x 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://192.168.1.1/test", purpose="test")
|
||||
|
||||
def test_private_ip_10_rejected(self):
|
||||
"""内网地址 10.x.x.x 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://10.0.0.1/test", purpose="test")
|
||||
|
||||
def test_private_ip_172_rejected(self):
|
||||
"""内网地址 172.16.x.x 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://172.16.0.1/test", purpose="test")
|
||||
|
||||
def test_unspecified_ip_rejected(self):
|
||||
"""未指定地址 0.0.0.0 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://0.0.0.0/test", purpose="test")
|
||||
|
||||
def test_ipv6_loopback_rejected(self):
|
||||
"""IPv6 回环 ::1 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://[::1]/test", purpose="test")
|
||||
|
||||
def test_ipv6_link_local_rejected(self):
|
||||
"""IPv6 链路本地地址应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://[fe80::1]/test", purpose="test")
|
||||
|
||||
# ── SSRF: 内网主机名 ─────────────────────────────────────────────────
|
||||
|
||||
def test_localhost_rejected(self):
|
||||
"""localhost 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://localhost/test", purpose="test")
|
||||
|
||||
def test_local_domain_rejected(self):
|
||||
""".local 域名应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://printer.local/test", purpose="test")
|
||||
|
||||
def test_internal_domain_rejected(self):
|
||||
""".internal 域名应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http://db.internal/test", purpose="test")
|
||||
|
||||
# ── URL 格式校验 ─────────────────────────────────────────────────────
|
||||
|
||||
def test_empty_url_rejected(self):
|
||||
"""空 URL 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("", purpose="test")
|
||||
|
||||
def test_none_url_rejected(self):
|
||||
"""None URL 应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety(None, purpose="test") # type: ignore
|
||||
|
||||
def test_url_too_long_rejected(self):
|
||||
"""超长 URL 应该被拒绝."""
|
||||
long_url = "https://example.com/" + "a" * 3000
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety(long_url, purpose="test")
|
||||
|
||||
def test_no_hostname_rejected(self):
|
||||
"""缺少主机名应该被拒绝."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
validate_url_safety("http:///test", purpose="test")
|
||||
|
||||
# ── is_url_safe 便捷函数 ─────────────────────────────────────────────
|
||||
|
||||
def test_is_url_safe_true(self):
|
||||
"""安全 URL 应该返回 True."""
|
||||
self.assertTrue(is_url_safe("https://example.com/test", purpose="test"))
|
||||
|
||||
def test_is_url_safe_false(self):
|
||||
"""不安全 URL 应该返回 False."""
|
||||
self.assertFalse(is_url_safe("http://127.0.0.1/test", purpose="test"))
|
||||
|
||||
def test_is_url_safe_empty(self):
|
||||
"""空 URL 应该返回 False."""
|
||||
self.assertFalse(is_url_safe("", purpose="test"))
|
||||
# ── validate_url_safety 基础校验 ─────────────────────────────────────────────
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
class TestValidateUrlSafetyBasics:
|
||||
"""URL 安全校验基础测试"""
|
||||
|
||||
def test_valid_http_url(self):
|
||||
url = "http://example.com/file.mp4"
|
||||
result = validate_url_safety(url)
|
||||
assert result == url
|
||||
|
||||
def test_valid_https_url(self):
|
||||
url = "https://example.com/file.mp4"
|
||||
result = validate_url_safety(url)
|
||||
assert result == url
|
||||
|
||||
def test_empty_url_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="为空"):
|
||||
validate_url_safety("")
|
||||
|
||||
def test_none_url_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety(None)
|
||||
|
||||
def test_url_too_long_raises(self):
|
||||
long_url = "https://example.com/" + "a" * 2050
|
||||
with pytest.raises(UrlSecurityError, match="过长"):
|
||||
validate_url_safety(long_url)
|
||||
|
||||
def test_url_at_max_length_ok(self):
|
||||
base = "https://example.com/"
|
||||
pad = "a" * (MAX_URL_LENGTH - len(base))
|
||||
url = base + pad
|
||||
assert len(url) <= MAX_URL_LENGTH
|
||||
result = validate_url_safety(url)
|
||||
assert result == url
|
||||
|
||||
def test_invalid_scheme_ftp_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="scheme"):
|
||||
validate_url_safety("ftp://example.com/file")
|
||||
|
||||
def test_invalid_scheme_file_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="scheme"):
|
||||
validate_url_safety("file:///etc/passwd")
|
||||
|
||||
def test_invalid_scheme_data_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="scheme"):
|
||||
validate_url_safety("data:text/html,<script>")
|
||||
|
||||
def test_missing_scheme_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="scheme"):
|
||||
validate_url_safety("example.com/file")
|
||||
|
||||
def test_missing_hostname_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="主机名"):
|
||||
validate_url_safety("http:///path")
|
||||
|
||||
def test_uppercase_scheme_normalized(self):
|
||||
"""HTTP/HTTPS 大写也能通过"""
|
||||
url = "HTTPS://example.com/file"
|
||||
# scheme 检查用 lower 比较
|
||||
result = validate_url_safety(url)
|
||||
assert result == url
|
||||
|
||||
def test_default_port_80_ok(self):
|
||||
url = "http://example.com:80/file"
|
||||
result = validate_url_safety(url)
|
||||
assert result == url
|
||||
|
||||
def test_default_port_443_ok(self):
|
||||
url = "https://example.com:443/file"
|
||||
result = validate_url_safety(url)
|
||||
assert result == url
|
||||
|
||||
def test_non_standard_port_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="端口"):
|
||||
validate_url_safety("http://example.com:8080/file")
|
||||
|
||||
def test_port_22_ssh_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="端口"):
|
||||
validate_url_safety("http://example.com:22/file")
|
||||
|
||||
def test_port_3306_mysql_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="端口"):
|
||||
validate_url_safety("http://example.com:3306/file")
|
||||
|
||||
|
||||
class TestSafeDownload(unittest.TestCase):
|
||||
"""安全下载函数测试."""
|
||||
# ── 内网主机名 / SSRF 防护 ───────────────────────────────────────────────────
|
||||
|
||||
def setUp(self):
|
||||
self.temp_dir = tempfile.mkdtemp()
|
||||
|
||||
def tearDown(self):
|
||||
shutil.rmtree(self.temp_dir, ignore_errors=True)
|
||||
class TestInternalHostnameProtection:
|
||||
"""内网主机名防护测试"""
|
||||
|
||||
def test_safe_download_file_rejects_ssrf(self):
|
||||
"""SSRF 风险 URL 应该被拒绝下载."""
|
||||
dest = os.path.join(self.temp_dir, "test.bin")
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
safe_download_file("http://127.0.0.1/test", dest, purpose="test")
|
||||
def test_localhost_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="内部主机名"):
|
||||
validate_url_safety("http://localhost/file")
|
||||
|
||||
def test_safe_download_bytes_rejects_ssrf(self):
|
||||
"""SSRF 风险 URL 应该被拒绝下载(bytes 版本)."""
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
safe_download_bytes("http://localhost/test", purpose="test")
|
||||
def test_localhost_mixed_case_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety("http://LocalHost/file")
|
||||
|
||||
def test_safe_download_file_size_limit(self):
|
||||
"""超过大小限制应该被拒绝."""
|
||||
# 用 mock server 测试太大的 content-length
|
||||
dest = os.path.join(self.temp_dir, "test.bin")
|
||||
# 直接验证参数:max_size=0 时任何下载都应超限
|
||||
# (这里用一个可访问的 URL 并设置极小的限制)
|
||||
# 为避免依赖外部网络,这里只测试函数参数传递
|
||||
with unittest.mock.patch("urllib.request.build_opener") as mock_opener:
|
||||
mock_resp = unittest.mock.MagicMock()
|
||||
mock_resp.headers = {"Content-Length": "1000"}
|
||||
mock_resp.read.return_value = b""
|
||||
mock_opener.return_value.open.return_value = mock_resp
|
||||
# 设置 max_size=500,content-length=1000 应被拒绝
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
safe_download_file(
|
||||
"https://example.com/test",
|
||||
def test_localhost_localdomain_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
_check_internal_hostnames("localhost.localdomain")
|
||||
|
||||
def test_metadata_hostname_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
_check_internal_hostnames("metadata")
|
||||
|
||||
def test_metadata_google_internal_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
_check_internal_hostnames("metadata.google.internal")
|
||||
|
||||
def test_dot_local_domain_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="内网域名"):
|
||||
validate_url_safety("http://myservice.local/file")
|
||||
|
||||
def test_dot_internal_domain_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="内网域名"):
|
||||
validate_url_safety("http://myservice.internal/file")
|
||||
|
||||
def test_dot_localdomain_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
_check_internal_hostnames("server.localdomain")
|
||||
|
||||
def test_loopback_ip_127_0_0_1_raises(self):
|
||||
with pytest.raises(UrlSecurityError, match="直接 IP|回环"):
|
||||
validate_url_safety("http://127.0.0.1/file")
|
||||
|
||||
def test_metadata_ip_169_254_raises(self):
|
||||
"""云元数据服务 IP"""
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety("http://169.254.169.254/latest/meta-data/")
|
||||
|
||||
def test_private_ip_10_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety("http://10.0.0.1/file")
|
||||
|
||||
def test_private_ip_172_16_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety("http://172.16.0.1/file")
|
||||
|
||||
def test_private_ip_192_168_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety("http://192.168.1.1/file")
|
||||
|
||||
def test_unspecified_ip_0_0_0_0_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety("http://0.0.0.0/file")
|
||||
|
||||
def test_ipv6_loopback_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
validate_url_safety("http://[::1]/file")
|
||||
|
||||
def test_public_ip_ok(self):
|
||||
"""公网IP在ALLOW_DIRECT_IP默认关闭时应被拦截"""
|
||||
# 默认 ALLOW_DIRECT_IP = false
|
||||
with pytest.raises(UrlSecurityError, match="直接 IP"):
|
||||
validate_url_safety("http://8.8.8.8/file")
|
||||
|
||||
|
||||
# ── 可信域名白名单 ───────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestTrustedDomains:
|
||||
"""可信域名白名单测试"""
|
||||
|
||||
def test_is_trusted_domain_exact_match(self):
|
||||
with patch("packages.shared.url_security.TRUSTED_DOMAINS", {"example.com", "cdn.example.org"}):
|
||||
# 重新加载模块以应用环境变量不太现实,直接测函数
|
||||
# 直接改全局状态再还原
|
||||
import packages.shared.url_security as mod
|
||||
from packages.shared.url_security import _is_trusted_domain
|
||||
|
||||
original = mod.TRUSTED_DOMAINS
|
||||
mod.TRUSTED_DOMAINS = {"example.com", "cdn.example.org"}
|
||||
try:
|
||||
assert _is_trusted_domain("example.com") is True
|
||||
assert _is_trusted_domain("cdn.example.org") is True
|
||||
finally:
|
||||
mod.TRUSTED_DOMAINS = original
|
||||
|
||||
def test_is_trusted_domain_subdomain(self):
|
||||
import packages.shared.url_security as mod
|
||||
|
||||
original = mod.TRUSTED_DOMAINS
|
||||
mod.TRUSTED_DOMAINS = {"example.com"}
|
||||
try:
|
||||
assert mod._is_trusted_domain("sub.example.com") is True
|
||||
assert mod._is_trusted_domain("a.b.example.com") is True
|
||||
finally:
|
||||
mod.TRUSTED_DOMAINS = original
|
||||
|
||||
def test_is_trusted_domain_no_match(self):
|
||||
import packages.shared.url_security as mod
|
||||
|
||||
original = mod.TRUSTED_DOMAINS
|
||||
mod.TRUSTED_DOMAINS = {"example.com"}
|
||||
try:
|
||||
assert mod._is_trusted_domain("other.com") is False
|
||||
assert mod._is_trusted_domain("notexample.com") is False
|
||||
finally:
|
||||
mod.TRUSTED_DOMAINS = original
|
||||
|
||||
def test_validate_with_trusted_domains_restricted(self):
|
||||
"""白名单非空时,不在白名单中的域名被拒"""
|
||||
import packages.shared.url_security as mod
|
||||
|
||||
original = mod.TRUSTED_DOMAINS
|
||||
mod.TRUSTED_DOMAINS = {"trusted.com"}
|
||||
try:
|
||||
# 不在白名单中 - 在 _is_trusted_domain 检查时就被拒,不走 DNS
|
||||
with pytest.raises(UrlSecurityError, match="白名单"):
|
||||
validate_url_safety("https://untrusted.com/file")
|
||||
|
||||
# 在白名单中 - 需要 mock DNS 解析避免实际网络请求
|
||||
with patch("packages.shared.url_security._check_ssrf_domain"):
|
||||
result = validate_url_safety("https://trusted.com/file")
|
||||
assert result == "https://trusted.com/file"
|
||||
# 子域名
|
||||
result = validate_url_safety("https://sub.trusted.com/file")
|
||||
assert result == "https://sub.trusted.com/file"
|
||||
finally:
|
||||
mod.TRUSTED_DOMAINS = original
|
||||
|
||||
|
||||
# ── is_url_safe 便捷函数 ─────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestIsUrlSafe:
|
||||
"""is_url_safe 便捷函数测试"""
|
||||
|
||||
def test_safe_url_returns_true(self):
|
||||
assert is_url_safe("https://example.com/file") is True
|
||||
|
||||
def test_unsafe_url_returns_false(self):
|
||||
assert is_url_safe("http://localhost/file") is False
|
||||
|
||||
def test_empty_url_returns_false(self):
|
||||
assert is_url_safe("") is False
|
||||
|
||||
def test_invalid_scheme_returns_false(self):
|
||||
assert is_url_safe("ftp://example.com/file") is False
|
||||
|
||||
|
||||
# ── UrlSecurityError 异常类 ───────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestUrlSecurityError:
|
||||
"""UrlSecurityError 异常类测试"""
|
||||
|
||||
def test_is_value_error_subclass(self):
|
||||
assert issubclass(UrlSecurityError, ValueError)
|
||||
|
||||
def test_error_message(self):
|
||||
err = UrlSecurityError("test message")
|
||||
assert str(err) == "test message"
|
||||
|
||||
|
||||
# ── NoRedirectHandler ────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestNoRedirectHandler:
|
||||
"""NoRedirectHandler 测试"""
|
||||
|
||||
def test_redirect_request_returns_none(self):
|
||||
handler = NoRedirectHandler()
|
||||
result = handler.redirect_request(
|
||||
MagicMock(),
|
||||
MagicMock(),
|
||||
302,
|
||||
"Found",
|
||||
{"Location": "http://other.com"},
|
||||
"http://other.com",
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
# ── 魔数校验 ─────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestMagicNumberValidation:
|
||||
"""文件魔数校验测试"""
|
||||
|
||||
def test_valid_png(self, tmp_path):
|
||||
f = tmp_path / "test.png"
|
||||
# PNG 文件头: 89 50 4E 47 0D 0A 1A 0A
|
||||
f.write_bytes(b"\x89PNG\r\n\x1a\n" + b"\x00" * 100)
|
||||
# 不抛异常 = 通过
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_valid_jpeg(self, tmp_path):
|
||||
f = tmp_path / "test.jpg"
|
||||
# JPEG 文件头: FF D8 FF
|
||||
f.write_bytes(b"\xff\xd8\xff\xe0" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_valid_gif87a(self, tmp_path):
|
||||
f = tmp_path / "test.gif"
|
||||
f.write_bytes(b"GIF87a" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_valid_gif89a(self, tmp_path):
|
||||
f = tmp_path / "test.gif"
|
||||
f.write_bytes(b"GIF89a" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_valid_webp(self, tmp_path):
|
||||
f = tmp_path / "test.webp"
|
||||
# RIFF....WEBP
|
||||
data = bytearray(b"RIFF")
|
||||
data += b"\x00\x00\x00\x00" # size placeholder
|
||||
data += b"WEBP"
|
||||
data += b"\x00" * 100
|
||||
f.write_bytes(bytes(data))
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_valid_bmp(self, tmp_path):
|
||||
f = tmp_path / "test.bmp"
|
||||
f.write_bytes(b"BM" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_valid_wav(self, tmp_path):
|
||||
f = tmp_path / "test.wav"
|
||||
# RIFF....WAVE
|
||||
data = bytearray(b"RIFF")
|
||||
data += b"\x00\x00\x00\x00"
|
||||
data += b"WAVE"
|
||||
data += b"\x00" * 100
|
||||
f.write_bytes(bytes(data))
|
||||
_validate_magic_number(str(f), ALLOWED_AUDIO_MIME_TYPES)
|
||||
|
||||
def test_valid_mp3_id3(self, tmp_path):
|
||||
f = tmp_path / "test.mp3"
|
||||
f.write_bytes(b"ID3\x03\x00\x00\x00\x00\x00\x00" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_AUDIO_MIME_TYPES)
|
||||
|
||||
def test_valid_mp3_adts(self, tmp_path):
|
||||
f = tmp_path / "test.mp3"
|
||||
f.write_bytes(b"\xff\xfb\x90\x00" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_AUDIO_MIME_TYPES)
|
||||
|
||||
def test_valid_ogg(self, tmp_path):
|
||||
f = tmp_path / "test.ogg"
|
||||
f.write_bytes(b"OggS\x00\x02\x00\x00" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_AUDIO_MIME_TYPES)
|
||||
|
||||
def test_valid_flac(self, tmp_path):
|
||||
f = tmp_path / "test.flac"
|
||||
f.write_bytes(b"fLaC" + b"\x00" * 100)
|
||||
_validate_magic_number(str(f), ALLOWED_AUDIO_MIME_TYPES)
|
||||
|
||||
def test_invalid_file_content_raises(self, tmp_path):
|
||||
f = tmp_path / "test.bin"
|
||||
f.write_bytes(b"this is not an image file at all")
|
||||
with pytest.raises(UrlSecurityError, match="魔数"):
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_empty_file_raises(self, tmp_path):
|
||||
f = tmp_path / "empty.bin"
|
||||
f.write_bytes(b"")
|
||||
with pytest.raises(UrlSecurityError, match="为空"):
|
||||
_validate_magic_number(str(f), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_nonexistent_file_raises(self, tmp_path):
|
||||
with pytest.raises(UrlSecurityError, match="读取文件头失败"):
|
||||
_validate_magic_number(str(tmp_path / "no_such_file"), ALLOWED_IMAGE_MIME_TYPES)
|
||||
|
||||
def test_no_allowed_mime_types_skips(self, tmp_path):
|
||||
"""allowed_mime_types 为空时跳过校验"""
|
||||
f = tmp_path / "test.bin"
|
||||
f.write_bytes(b"random data here")
|
||||
# 不抛异常
|
||||
_validate_magic_number(str(f), set())
|
||||
|
||||
def test_unknown_mime_types_skips(self, tmp_path):
|
||||
"""没有已知魔数的 MIME 类型跳过校验"""
|
||||
f = tmp_path / "test.bin"
|
||||
f.write_bytes(b"random data")
|
||||
_validate_magic_number(str(f), {"application/x-unknown-type"})
|
||||
|
||||
|
||||
# ── safe_download_file (mock 网络) ───────────────────────────────────────────
|
||||
|
||||
|
||||
class TestSafeDownloadFile:
|
||||
"""safe_download_file 下载测试(mock 网络)"""
|
||||
|
||||
def test_download_success(self, tmp_path):
|
||||
test_content = b"Hello, this is test file content!"
|
||||
dest = str(tmp_path / "output.bin")
|
||||
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "application/octet-stream"}
|
||||
mock_resp.read.side_effect = [test_content, b""]
|
||||
|
||||
with patch("packages.shared.url_security.NoRedirectHandler") as mock_handler_cls:
|
||||
mock_handler = MagicMock()
|
||||
mock_handler_cls.return_value = mock_handler
|
||||
|
||||
mock_opener = MagicMock()
|
||||
mock_opener.open.return_value = mock_resp
|
||||
|
||||
with patch("urllib.request.build_opener", return_value=mock_opener):
|
||||
size = safe_download_file(
|
||||
"https://example.com/test.bin",
|
||||
dest,
|
||||
purpose="test",
|
||||
max_size=500,
|
||||
)
|
||||
|
||||
def test_safe_download_file_mime_rejected(self):
|
||||
"""不允许的 MIME 类型应该被拒绝."""
|
||||
dest = os.path.join(self.temp_dir, "test.bin")
|
||||
with unittest.mock.patch("urllib.request.build_opener") as mock_opener:
|
||||
mock_resp = unittest.mock.MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "text/html"}
|
||||
mock_resp.read.return_value = b""
|
||||
mock_opener.return_value.open.return_value = mock_resp
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
safe_download_file(
|
||||
"https://example.com/test.mp3",
|
||||
dest,
|
||||
purpose="test",
|
||||
allowed_mime_types=ALLOWED_AUDIO_MIME_TYPES,
|
||||
)
|
||||
assert size == len(test_content)
|
||||
with open(dest, "rb") as f:
|
||||
assert f.read() == test_content
|
||||
|
||||
def test_download_with_mime_check_passes(self, tmp_path):
|
||||
# PNG 文件
|
||||
test_content = b"\x89PNG\r\n\x1a\n" + b"\x00" * 200
|
||||
dest = str(tmp_path / "test.png")
|
||||
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "image/png"}
|
||||
mock_resp.read.side_effect = [test_content, b""]
|
||||
|
||||
with patch("urllib.request.build_opener") as mock_build:
|
||||
mock_opener = MagicMock()
|
||||
mock_opener.open.return_value = mock_resp
|
||||
mock_build.return_value = mock_opener
|
||||
|
||||
def test_safe_download_file_mime_allowed(self):
|
||||
"""允许的 MIME 类型应该通过."""
|
||||
dest = os.path.join(self.temp_dir, "test.mp3")
|
||||
with unittest.mock.patch("urllib.request.build_opener") as mock_opener:
|
||||
mock_resp = unittest.mock.MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "audio/mpeg"}
|
||||
mock_resp.read.side_effect = [b"ID3audio_data", b""]
|
||||
mock_resp.geturl.return_value = "https://example.com/test.mp3"
|
||||
mock_opener.return_value.open.return_value = mock_resp
|
||||
size = safe_download_file(
|
||||
"https://example.com/test.mp3",
|
||||
"https://example.com/test.png",
|
||||
dest,
|
||||
purpose="test",
|
||||
allowed_mime_types=ALLOWED_AUDIO_MIME_TYPES,
|
||||
allowed_mime_types={"image/png", "image/jpeg"},
|
||||
)
|
||||
self.assertEqual(size, 13)
|
||||
self.assertTrue(os.path.exists(dest))
|
||||
|
||||
def test_safe_download_file_stream_size_limit(self):
|
||||
"""流式下载时超过大小限制应该中断."""
|
||||
dest = os.path.join(self.temp_dir, "test.bin")
|
||||
with unittest.mock.patch("urllib.request.build_opener") as mock_opener:
|
||||
mock_resp = unittest.mock.MagicMock()
|
||||
mock_resp.headers = {}
|
||||
# 每次返回 100 字节,max_size=500,第 6 次读取就超限
|
||||
mock_resp.read.side_effect = lambda n: b"x" * n if n < 1000 else b"x" * 100
|
||||
# 改成返回固定 100 字节,直到第 N 次后返回空
|
||||
call_count = [0]
|
||||
assert size == len(test_content)
|
||||
|
||||
def mock_read(size):
|
||||
call_count[0] += 1
|
||||
if call_count[0] > 10:
|
||||
return b""
|
||||
return b"x" * 100
|
||||
def test_download_mime_type_rejected(self, tmp_path):
|
||||
test_content = b"GIF89a" + b"\x00" * 50
|
||||
dest = str(tmp_path / "test.gif")
|
||||
|
||||
mock_resp.read = mock_read
|
||||
mock_opener.return_value.open.return_value = mock_resp
|
||||
with self.assertRaises(UrlSecurityError):
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "image/gif"}
|
||||
mock_resp.read.side_effect = [test_content, b""]
|
||||
|
||||
with patch("urllib.request.build_opener") as mock_build:
|
||||
mock_opener = MagicMock()
|
||||
mock_opener.open.return_value = mock_resp
|
||||
mock_build.return_value = mock_opener
|
||||
|
||||
with pytest.raises(UrlSecurityError, match="Content-Type"):
|
||||
safe_download_file(
|
||||
"https://example.com/test",
|
||||
"https://example.com/test.gif",
|
||||
dest,
|
||||
purpose="test",
|
||||
max_size=500, # 500 字节上限
|
||||
allowed_mime_types={"image/png"},
|
||||
)
|
||||
|
||||
def test_safe_download_bytes_returns_content(self):
|
||||
"""safe_download_bytes 应该返回文件内容."""
|
||||
test_data = b"ID3hello world test audio"
|
||||
with unittest.mock.patch("urllib.request.build_opener") as mock_opener:
|
||||
mock_resp = unittest.mock.MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "audio/mpeg"}
|
||||
call_count = [0]
|
||||
def test_download_size_limit_exceeded(self, tmp_path):
|
||||
"""流式下载时超过大小限制被中断(无 Content-Length header)"""
|
||||
dest = str(tmp_path / "big.bin")
|
||||
chunk = b"x" * 1024 # 1KB chunks
|
||||
|
||||
def mock_read(size):
|
||||
call_count[0] += 1
|
||||
if call_count[0] > 1:
|
||||
return b""
|
||||
return test_data
|
||||
mock_resp = MagicMock()
|
||||
# 没有 Content-Length header,走流式检查
|
||||
mock_resp.headers = {"Content-Type": "application/octet-stream"}
|
||||
# 模拟多次读取,超过 5KB 限制(6个chunk = 6KB)
|
||||
mock_resp.read.side_effect = [chunk] * 6 + [b""]
|
||||
|
||||
with patch("urllib.request.build_opener") as mock_build:
|
||||
mock_opener = MagicMock()
|
||||
mock_opener.open.return_value = mock_resp
|
||||
mock_build.return_value = mock_opener
|
||||
|
||||
with pytest.raises(UrlSecurityError, match="超过大小限制"):
|
||||
safe_download_file(
|
||||
"https://example.com/big.bin",
|
||||
dest,
|
||||
purpose="test",
|
||||
max_size=5000, # 5KB limit
|
||||
)
|
||||
|
||||
def test_download_content_length_too_large(self, tmp_path):
|
||||
dest = str(tmp_path / "big.bin")
|
||||
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "application/octet-stream", "Content-Length": "1000000"}
|
||||
mock_resp.read.side_effect = [b"data"]
|
||||
|
||||
with patch("urllib.request.build_opener") as mock_build:
|
||||
mock_opener = MagicMock()
|
||||
mock_opener.open.return_value = mock_resp
|
||||
mock_build.return_value = mock_opener
|
||||
|
||||
with pytest.raises(UrlSecurityError, match="文件过大"):
|
||||
safe_download_file(
|
||||
"https://example.com/big.bin",
|
||||
dest,
|
||||
purpose="test",
|
||||
max_size=500000,
|
||||
)
|
||||
|
||||
def test_download_localhost_rejected(self, tmp_path):
|
||||
"""内网 URL 在下载前就被拒"""
|
||||
dest = str(tmp_path / "out.bin")
|
||||
with pytest.raises(UrlSecurityError):
|
||||
safe_download_file("http://localhost/file", dest)
|
||||
|
||||
def test_download_invalid_scheme_rejected(self, tmp_path):
|
||||
dest = str(tmp_path / "out.bin")
|
||||
with pytest.raises(UrlSecurityError, match="scheme"):
|
||||
safe_download_file("ftp://example.com/file", dest)
|
||||
|
||||
|
||||
# ── safe_download_bytes ───────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestSafeDownloadBytes:
|
||||
"""safe_download_bytes 测试"""
|
||||
|
||||
def test_download_returns_bytes(self, tmp_path):
|
||||
test_content = b"hello bytes download test"
|
||||
|
||||
mock_resp = MagicMock()
|
||||
mock_resp.headers = {"Content-Type": "application/octet-stream"}
|
||||
mock_resp.read.side_effect = [test_content, b""]
|
||||
|
||||
with patch("urllib.request.build_opener") as mock_build:
|
||||
mock_opener = MagicMock()
|
||||
mock_opener.open.return_value = mock_resp
|
||||
mock_build.return_value = mock_opener
|
||||
|
||||
mock_resp.read = mock_read
|
||||
mock_opener.return_value.open.return_value = mock_resp
|
||||
result = safe_download_bytes(
|
||||
"https://example.com/test.mp3",
|
||||
"https://example.com/test.bin",
|
||||
purpose="test",
|
||||
allowed_mime_types=ALLOWED_AUDIO_MIME_TYPES,
|
||||
)
|
||||
self.assertEqual(result, test_data)
|
||||
|
||||
assert result == test_content
|
||||
assert isinstance(result, bytes)
|
||||
|
||||
def test_download_unsafe_url_raises(self):
|
||||
with pytest.raises(UrlSecurityError):
|
||||
safe_download_bytes("http://127.0.0.1/secret")
|
||||
|
||||
|
||||
# ── 常量导出验证 ─────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
class TestConstants:
|
||||
"""模块常量验证"""
|
||||
|
||||
def test_allowed_schemes(self):
|
||||
assert "http" in ALLOWED_SCHEMES
|
||||
assert "https" in ALLOWED_SCHEMES
|
||||
assert len(ALLOWED_SCHEMES) == 2
|
||||
|
||||
def test_allowed_ports(self):
|
||||
assert 80 in ALLOWED_PORTS
|
||||
assert 443 in ALLOWED_PORTS
|
||||
assert len(ALLOWED_PORTS) == 2
|
||||
|
||||
def test_max_url_length(self):
|
||||
assert MAX_URL_LENGTH == 2048
|
||||
|
||||
Reference in New Issue
Block a user