You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

8.1 KiB

Docker 容器测试和迁移指南

日期: 2026-02-07
适用于: AI Prompt System v2.0 增强功能


📋 前置条件

确保 Docker 容器已启动:

cd /Users/panta/py_work/jointoai_work/Jointoai
docker compose up -d

检查容器状态:

docker compose ps

🗄️ 数据库迁移

1. 进入后端容器

docker compose exec backend bash

2. 运行迁移(如果有新的迁移文件)

# 在容器内执行
cd /app
alembic upgrade head

3. 验证迁移状态

# 查看当前迁移版本
alembic current

# 查看迁移历史
alembic history

4. 同步 AI Skills 到数据库

# 在容器内执行
python scripts/sync_ai_skills.py

# 查看已注册的技能
python scripts/sync_ai_skills.py --list

🧪 运行测试

1. 运行所有单元测试

# 在容器内执行
cd /app
pytest tests/unit/ -v

2. 运行特定模块的测试

Schema 参数验证测试

pytest tests/unit/schemas/test_screenplay_parse_request.py -v

Service 层参数传递测试

pytest tests/unit/services/test_ai_service_parse_screenplay.py -v

API 集成测试

pytest tests/integration/test_screenplay_api.py::TestScreenplayAPI::test_parse_screenplay_with_custom_requirements -v
pytest tests/integration/test_screenplay_api.py::TestScreenplayAPI::test_parse_screenplay_storyboard_count_validation -v

3. 运行所有集成测试

pytest tests/integration/ -v

4. 运行带覆盖率的测试

# 安装 pytest-cov(如果未安装)
pip install pytest-cov

# 运行测试并生成覆盖率报告
pytest tests/unit/ --cov=app --cov-report=html --cov-report=term

# 查看覆盖率报告
# 报告生成在 htmlcov/index.html

5. 运行特定测试并显示详细日志

pytest tests/unit/schemas/test_screenplay_parse_request.py -v -s --log-cli-level=INFO

🔍 快速验证脚本

一键运行所有新增功能测试

#!/bin/bash
# 在容器内执行

echo "======================================"
echo "测试 1: Schema 参数验证"
echo "======================================"
pytest tests/unit/schemas/test_screenplay_parse_request.py -v

echo ""
echo "======================================"
echo "测试 2: Service 层参数传递"
echo "======================================"
pytest tests/unit/services/test_ai_service_parse_screenplay.py -v

echo ""
echo "======================================"
echo "测试 3: API 集成测试"
echo "======================================"
pytest tests/integration/test_screenplay_api.py -k "parse_screenplay_with_custom" -v

echo ""
echo "======================================"
echo "所有测试完成!"
echo "======================================"

保存为 /app/scripts/test_new_features.sh,然后运行:

chmod +x scripts/test_new_features.sh
./scripts/test_new_features.sh

🐛 常见问题排查

1. 导入错误

问题: ModuleNotFoundError: No module named 'app'

解决:

# 确保在 /app 目录下
cd /app

# 设置 PYTHONPATH
export PYTHONPATH=/app:$PYTHONPATH

2. 数据库连接错误

问题: Connection refusedcould not connect to server

解决:

# 检查 PostgreSQL 容器状态
docker compose ps db

# 查看数据库日志
docker compose logs db

# 重启数据库
docker compose restart db

3. 测试数据库配置

确保使用测试数据库:

# conftest.py 中应该有:
@pytest.fixture(scope="session")
def database_url():
    """测试数据库 URL"""
    return os.getenv("TEST_DATABASE_URL", "postgresql+asyncpg://...")

4. Celery 任务 Mock 失败

问题: 测试中 Celery 任务未被正确 Mock

解决:

# 确保 patch 路径正确
with patch('app.services.ai_service.parse_screenplay_task') as mock_task:
    # 而不是
    # with patch('app.tasks.ai_tasks.parse_screenplay_task')

📊 测试输出示例

成功输出

tests/unit/schemas/test_screenplay_parse_request.py::TestScreenplayParseRequest::test_default_values PASSED [ 10%]
tests/unit/schemas/test_screenplay_parse_request.py::TestScreenplayParseRequest::test_custom_requirements_valid PASSED [ 20%]
tests/unit/schemas/test_screenplay_parse_request.py::TestScreenplayParseRequest::test_storyboard_count_valid PASSED [ 30%]
...

========== 15 passed in 2.34s ==========

失败输出(需要修复)

tests/unit/schemas/test_screenplay_parse_request.py::TestScreenplayParseRequest::test_storyboard_count_below_minimum FAILED [ 40%]

E   ValidationError: 1 validation error for ScreenplayParseRequest
E   storyboard_count
E     Input should be greater than or equal to 3 [type=greater_than_equal, input_value=2, input_type=int]

🚀 完整工作流

开发流程

# 1. 启动容器
docker compose up -d

# 2. 进入后端容器
docker compose exec backend bash

# 3. 运行迁移
alembic upgrade head

# 4. 同步 AI Skills
python scripts/sync_ai_skills.py

# 5. 运行测试
pytest tests/unit/ -v
pytest tests/integration/ -v -k "parse_screenplay"

# 6. 检查代码质量
flake8 app/schemas/screenplay.py
mypy app/services/ai_service.py

# 7. 查看日志
exit  # 退出容器
docker compose logs -f backend

CI/CD 流程

# .github/workflows/test.yml
name: Test

on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    
    steps:
      - uses: actions/checkout@v3
      
      - name: Start containers
        run: docker compose up -d
      
      - name: Run migrations
        run: docker compose exec -T backend alembic upgrade head
      
      - name: Sync AI Skills
        run: docker compose exec -T backend python scripts/sync_ai_skills.py
      
      - name: Run tests
        run: |
          docker compose exec -T backend pytest tests/unit/ -v
          docker compose exec -T backend pytest tests/integration/ -v          
      
      - name: Cleanup
        run: docker compose down -v

📝 手动测试 API

使用 cURL

# 1. 获取 Token(在宿主机执行)
TOKEN=$(curl -X POST "http://localhost:6170/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"phone":"13800138000","password":"test123"}' \
  | jq -r '.data.token')

# 2. 创建测试剧本
SCREENPLAY_ID=$(curl -X POST "http://localhost:6170/api/v1/screenplays" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "projectId": "your-project-id",
    "name": "测试剧本",
    "content": "这是一个测试剧本内容..."
  }' | jq -r '.data.screenplayId')

# 3. 测试新参数的解析接口
curl -X POST "http://localhost:6170/api/v1/screenplays/$SCREENPLAY_ID/parse" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "customRequirements": "增加人物特写镜头,注重情感表达",
    "storyboardCount": 8,
    "model": "gpt-4"
  }' | jq '.'

# 4. 查询任务状态
JOB_ID="返回的jobId"
curl "http://localhost:6170/api/v1/ai/jobs/$JOB_ID" \
  -H "Authorization: Bearer $TOKEN" | jq '.'

🔧 调试技巧

1. 进入容器调试

# 进入容器
docker compose exec backend bash

# 使用 IPython 交互式调试
pip install ipython
ipython

# 在 IPython 中
from app.services.ai_service import AIService
from app.core.database import get_session

# 测试代码...

2. 查看实时日志

# 宿主机执行
docker compose logs -f backend

# 过滤特定关键词
docker compose logs -f backend | grep "剧本解析"

3. 数据库查询

# 进入 PostgreSQL 容器
docker compose exec db psql -U jointo -d jointo

# 查询 AI Skills
SELECT skill_id, name, version, is_active FROM ai_skills_registry;

# 查询 AI Jobs
SELECT ai_job_id, job_type, status, created_at 
FROM ai_jobs 
ORDER BY created_at DESC 
LIMIT 10;

验收检查清单

  • 所有单元测试通过
  • 所有集成测试通过
  • AI Skills 同步成功
  • API 接口返回正确
  • 日志输出正常
  • 无 Lint 错误
  • 数据库迁移成功
  • Docker 容器运行正常

维护人员: AI Agent
最后更新: 2026-02-07