使用Docker容器化Python测试Pytest项目并配置GitHub Actions CI/CD流程
先看实现效果!!!
前言
在软件开发过程中,自动化测试和持续集成/持续部署(CI/CD)已经成为现代开发流程中不可或缺的部分。本文将详细介绍如何将一个Python测试项目容器化,并配置GitHub Actions实现自动化测试流程。
项目准备
首先,我们需要创建一个基本的Python测试项目结构:
text
. ├── src/ # 源代码目录 │ └── calculator.py # 计算器实现 ├── tests/ # 测试代码目录 │ └── test_calculator.py # 单元测试 ├── .gitignore # Git忽略规则 └── README.md # 项目说明文档
1. 创建.gitignore文件
为了避免将不必要的文件提交到版本控制系统,我们首先创建.gitignore文件:
powershell
@" # Python __pycache__/ *.pyc .venv/ venv/# IDE .vscode/ .idea/# 其他 .DS_Store "@ > .gitignore
2. 添加项目说明文档
创建README.md文件描述项目结构和使用说明:
powershell
@" # 计算器测试项目## 项目结构 . ├── src/ # 源代码 │ └── calculator.py # 计算器实现 └── tests/ # 测试代码 └── test_calculator.py # 单元测试## 使用说明 ```bash # 运行测试 pytest tests/ -v
"@ > README.md
text
## 配置GitHub Actions自动化测试在项目中创建`.github/workflows/ci.yml`文件,配置自动化测试流程:```yaml name: CI Pipeline on: [push]jobs:test:runs-on: ubuntu-lateststeps:- uses: actions/checkout@v3- uses: actions/setup-python@v4with:python-version: "3.11"- run: pip install pytest- run: python -m pytest tests/ -v
Docker化Python测试项目
1. 创建Dockerfile
dockerfile
FROM python:3.9-slim# 设置工作目录 WORKDIR /app# 复制项目文件到容器中 COPY . .# 安装依赖 RUN pip install -r requirements.txt# 运行pytest测试 RUN pytest tests/# 设置容器启动时运行的命令(根据你的项目需求修改) CMD ["python", "src/main.py"]
2. 创建requirements.txt
bash
echo "pytest" > requirements.txt
3. 配置Docker镜像加速
为了提高Docker镜像构建速度,我们可以配置镜像加速器:
bash
sudo mkdir -p /etc/docker sudo tee /etc/docker/daemon.json <<-'EOF' {"registry-mirrors": ["https://","https://docker.m.daocloud.io"],"dns": ["8.8.8.8", "114.114.114.114"] } EOF sudo systemctl daemon-reload sudo systemctl restart docker
4. 构建并运行Docker容器
bash
docker build -t my-pytest-app . docker run -it --rm my-pytest-app /bin/bash
在容器内运行测试:
bash
pytest tests/
常见问题解决
Git推送失败:
text
error: failed to push some refs to 'https://github.com/...' hint: Updates were rejected because the remote contains work that you do not hint: have locally.
解决方法:先执行
git pull origin master
拉取远程更改,再推送。Docker构建时找不到requirements.txt:
text
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt'
解决方法:确保项目根目录下有requirements.txt文件。
网络连接问题:
text
fatal: unable to access 'https://github.com/...': Failed to connect to github.com port 443
解决方法:检查网络连接,或配置代理。
总结
通过本文的介绍,我们完成了以下工作:
创建了一个基本的Python测试项目结构
配置了.gitignore和README.md
设置了GitHub Actions自动化测试流程
将项目Docker化并配置了镜像加速
解决了常见的Git和Docker相关问题
这套流程可以帮助开发者实现:
代码版本控制
自动化测试
环境一致性保证
持续集成/持续部署