修改run、dockerfile、readme文件,适配流水线运行需求

This commit is contained in:
floraachy
2025-08-22 10:00:41 +08:00
parent 4c3280dc30
commit a2efab60eb
4 changed files with 122 additions and 9 deletions

View File

@@ -601,6 +601,104 @@ excel表单2名称是示例模块
- [无法安装依赖包或者安装很慢,怎么办?](https://www.gitlink.org.cn/zone/tester/newdetail/244)
## ## 🐳 Docker构建运行
前提条件:
- 宿主机已经安装docker
- 仓库根目录下已编写好`dockerfile`
### 1.构建镜像
**语法**`docker build -f Dockerfile的路径 -t 镜像的名称及标签 镜像构建的目录`
- `-f`:指定 Dockerfile 文件路径(可使用绝对/相对路径)
- `-t`:指定镜像名称及标签格式 `[name]:[tag]`
- `.`:表示当前构建上下文目录
- `--no-cache` 表示禁用缓存
**示例**
```bash
docker build -f dockerfile --no-cache -t apitest:2.0 .
```
### 2. 运行镜像
**语法**`docker run [OPTIONS] IMAGE[:TAG|@DIGEST] [COMMAND] [ARG…]`
- `-d/detach`:后台运行容器
- `p/publish`:端口映射格式 [主机IP:]主机端口:容器端口[/协议]
- `name`:指定容器名称(未指定时会自动生成随机名称)
- `-e/env`:设置环境变量
- `-v/volume`:挂载数据卷(将宿主机上的一个目录(文件夹)/文件挂载到容器内的指定目录/文件,使得容器内的该目录/文件与宿主机保持同步。)
- `restart`:设置重启策略(如 restart=always
**示例**
```bash
docker run --rm --name apitest -e NGINX="http://xxx" -v -v /data/nginx/html/apiautotest/:/apiautotest/ -v /data/chytest/env/test.yaml:/apiautotest/env/test.yaml apitest:2.0
docker run \
-v /data/nginx/html/apiautotest/:/apiautotest/ \
-v /data/chytest/env/test.yaml:/apiautotest/env/test.yaml \
-e NGINX="http://xxx" \
--name apitest \
apitest:2.0
```
- 挂载目录
将宿主机的 `/data/nginx/html/apiautotest/` 目录挂载到容器内的 `/apiautotest/` 目录:
(运行的时候,会运行宿主机目录`/apiautotest/`的文件,运行完成后,将宿主机目录`/data/nginx/html/apiautotest/`拷贝到容器内的目录`/apiautotest/`)
`-v /data/nginx/html/apiautotest/output/:/apiautotest/output/`
- 挂载单个文件
将宿主机的 `/data/chytest/env/test.yaml` 文件挂载到容器内的 `/apiautotest/env/test.yaml` 文件:
(实际运行的时候,会读取将宿主机的 `/data/chytest/env/test.yaml`的内容作为测试数据)
`-v /data/chytest/env/test.yaml:/apiautotest/env/test.yaml`
### 3. 流水线参考
```yaml
name: "接口测试-生成报告"
on:
push:
branches:
- '*'
paths-ignore:
- '.gitea/workflows/**'
- '.github/workflows/**'
jobs:
job-487fcffc:
name: "测试[job-487fcffc]"
# 运行环境,这里就是上面定义的多个 os
runs-on: 'ubuntu-latest'
steps:
- name: "克隆代码[ssh-bbc2533]"
uses: http://xxx/actions/ssh-action@v1.0.3
with:
host: 'xxx'
port: '22'
username: 'root'
password: 'xxx'
script: 'cd /data/nginx/html/ && git clone --recurse-submodules https://gitlink.org.cn/kytest/apiautotest.git>/dev/null || echo "代码已存在无需重新克隆,仅需拉取最新代码" && cd /data/nginx/html/apiautotest && git pull --force origin master:master && git log -1 '
- name: "ssh登录服务器[ssh-1bd148b]"
uses: http://xxx/actions/ssh-action@v1.0.3
with:
host: 'xxx'
port: '22'
username: 'root'
password: 'xxx'
script: 'cd /data/nginx/html/apiautotest && docker build -f dockerfile --no-cache -t apitest:2.0 .>/dev/null || echo "镜像已存在无需构建" && docker images | grep apitest'
- name: "执行测试[ssh-7cf8368e]"
uses: http://xxx/actions/ssh-action@v1.0.3
with:
host: 'xxx'
port: '22'
username: 'root'
password: 'xxx'
script: 'docker run --rm --name apitest -e NGINX="http://xxx:8001" -v /data/nginx/html/apiautotest/:/apiautotest/ apitest:2.0'
- name: "获取测试报告信息[log_match_action-7515d3d]"
uses: http://xxx/xxq250/log_match_action@master
with:
match-step: '3'
match-key: 'out: 测试报告地址:'
match-job-name: '自动化测试报告'
upload-api-domain: ''
check-contains-link: ''
show-type: 'html'
```
## 赞赏
如果这个库有帮助到你并且你很想支持库的后续开发和维护,那么你可以扫描下方二维码随意打赏我,我将不胜感激~

2
common

Submodule common updated: a6beecbbd0...404d10551d

View File

@@ -19,6 +19,7 @@ RUN git clone --recurse-submodules https://gitlink.org.cn/kytest/apiautotest.git
# 设置工作目录
WORKDIR /apiautotest
COPY . .
RUN git rev-parse HEAD
# 安装pipenv
RUN pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pipenv
@@ -29,8 +30,8 @@ RUN pipenv install
# 运行
CMD ["pipenv", "run", "python", "run.py"]
# 构建docker镜像 docker build -f dockerfile -t apitest:2.0 .
# 运行docker镜像docker run --rm --name apitest -v /data/nginx/html/apiautotest/:/apiautotest/ apitest:2.0
# 构建docker镜像 docker build -f dockerfile --no-cache -t apitest:2.0 .
# 运行docker镜像docker run --rm --name apitest -e NGINX="http://172.20.32.201:8001" -v /data/nginx/html/apiautotest/:/apiautotest/ -v /data/chytest/env/test.yaml:/apiautotest/env/test.yaml apitest:2.0
# 删除容器docker rm apitest
# 删除docker镜像docker rmi -f apitest:2.0
# 使用 Docker 原生命令仅删除不检查docker rmi your-image-name:your-tag 2>/dev/null || echo "镜像不存在"

26
run.py
View File

@@ -35,7 +35,8 @@ pytest相关参数以下也可通过pytest.ini配置
# 标准库导入
import os
import shutil
import time
from datetime import datetime
from pathlib import Path
# 第三方库导入
import pytest
from loguru import logger
@@ -44,10 +45,13 @@ import click
from common.files_utils.files_handle import load_yaml_file
from utils.case_generate_utils.case_fun_generate import generate_cases
from utils.report_utils.send_result_handle import send_result
from settings import REPORT_DIR, LOG_DIR, ENV_DIR, ALLURE_RESULTS_DIR, ALLURE_HTML_DIR, AUTO_CASE_DIR, ALLURE_CONFIG_DIR
from settings import BASE_DIR, REPORT_DIR, LOG_DIR, ENV_DIR, ALLURE_RESULTS_DIR, ALLURE_HTML_DIR, AUTO_CASE_DIR, \
ALLURE_CONFIG_DIR
from settings import LOG_LEVEL, GLOBAL_VARS, REPORT, RERUN, RERUN_DELAY, MAX_FAIL
from common.logger_utils.loguru_log import capture_logs
from utils.report_utils.allure_handle import generate_allure_report
# from utils.report_utils.push_allure_report import push_allure_report
@@ -59,16 +63,17 @@ from utils.report_utils.allure_handle import generate_allure_report
def run(env, m, report):
try:
# ------------------------ 捕获日志----------------------------
LOG_LEVEL = "INFO"
capture_logs(level=LOG_LEVEL, filename=os.path.join(LOG_DIR, "service.log"))
logger.info("""\n\n
logger.info(f"""\n\n
_ _ _ _____ _
__ _ _ __ (_) / \\ _ _| |_ __|_ _|__ ___| |_
/ _` | "_ \\| | / _ \\| | | | __/ _ \\| |/ _ \\/ __| __|
| (_| | |_) | |/ ___ \\ |_| | || (_) | | __/\\__ \\ |_
\\__,_| .__/|_/_/ \\_\\__,_|\\__\\___/|_|\\___||___/\\__|
|_|
Starting ... ... ...
Starting {datetime.now().strftime("%Y-%m-%d %H:%M:%S")} ... ... ...
""")
# ------------------------ 处理一下获取到的参数----------------------------
@@ -96,8 +101,8 @@ def run(env, m, report):
pytest.main(args=arg_list)
# ------------------------ 生成测试报告 ------------------------
if report == "yes":
_ALLURE_HTML_DIR = f"{ALLURE_HTML_DIR}_{str(int(round(time.time() * 1000)))}"
logger.debug("ALLURE HTML DIR: {}".format(_ALLURE_HTML_DIR))
_ALLURE_HTML_DIR = f"{ALLURE_HTML_DIR}_{str(int(datetime.now().timestamp()))}"
print("ALLURE HTML DIR: {}".format(_ALLURE_HTML_DIR))
report_path, attachment_path = generate_allure_report(allure_results=ALLURE_RESULTS_DIR,
allure_report=_ALLURE_HTML_DIR,
windows_title=REPORT["项目名称"],
@@ -107,6 +112,15 @@ def run(env, m, report):
allure_config_path=ALLURE_CONFIG_DIR,
attachment_path=os.path.join(REPORT_DIR,
f'{_ALLURE_HTML_DIR}.zip'))
# -----------------拼接测试报告地址,用于流水线运行,不需要的可忽略--------------------
sub_path = Path(_ALLURE_HTML_DIR).relative_to(Path(os.path.dirname(BASE_DIR)))
new_sub_path = os.path.normpath(sub_path).replace('\\', '/')
# 从系统环境变量NGINX获取其值作为nginx地址拼接allure html报告地址并输出
if os.environ.get("NGINX"):
logger.debug(f"系统环境变量NGINX={os.environ.get('NGINX'):}")
url = os.environ.get("NGINX")[0:len(os.environ.get("NGINX")) - 1] if os.environ.get("NGINX").endswith(
"/") else os.environ.get("NGINX")
print(f'测试报告地址:{url}/{new_sub_path}')
# ------------------------ 发送测试结果 ------------------------
send_result(report_info=REPORT, report_path=report_path, attachment_path=attachment_path)