
Python与Ollama的开发案例
在微服务与云原生架构日益普及的今天,API 自动化测试已成为保障服务稳定性和持续交付能力的必备环节。良好的 API 自动化测试体系,不仅能帮助团队实现快速反馈、高覆盖率与持续集成(CI/CD)集成,还能大幅降低生产事故和运维成本。本攻略将带你从 Postman 自动化测试、REST‑Assured、Mock 服务搭建、性能与安全测试,以及 Jenkins API 测试集成,到 未来无代码与 AI 辅助测试,全方位掌握 API 自动化测试实战技巧。
关键特性:
stage('Run Postman Tests') {
steps {
sh """
newman run api_tests.postman_collection.json \
-e environments/dev.json \
--reporters cli,junit,html \
--reporter-junit-export reports/junit.xml \
--reporter-html-export reports/report.html
"""
}
post {
always {
junit 'reports/junit.xml'
publishHTML(target: [reportDir: 'reports', reportFiles: 'report.html'])
}
}
}
关键特性:
mvn test
即可触发。given()
.baseUri("https://api.example.com/v1")
.auth().oauth2(token)
.when()
.get("/artists")
.then()
.statusCode(200)
.body("size()", greaterThan(0));
# Prism 启动 Mock 服务
prism mock openapi.yaml --port 4010
src/
├── config/
│ └── env.properties
├── data/
│ └── artists.csv
├── lib/
│ ├── http_client.py
│ └── assertions.py
└── tests/
├── test_get_artists.py
└── test_create_artist.py
data.json
+ --iteration-data
实现多次执行;@pytest.mark.parametrize
传入数据文件。--parallel
参数加速执行; < forkCount > 2C < /forkCount >
;pytest -n auto
实现多核并行。pipeline {
agent any
environment {
NODE_ENV = 'test'
COLLECTION = 'collections/api_tests.postman_collection.json'
ENV_FILE = 'environments/dev.json'
}
stages {
stage('Checkout') {
steps { checkout scm }
}
stage('Install Dependencies') {
steps { sh 'npm install -g newman' }
}
stage('API Mock') {
steps {
sh 'prism mock openapi.yaml --port 4010 &'
sh 'sleep 5'
}
}
stage('Run Tests') {
steps {
sh """
newman run $COLLECTION -e $ENV_FILE \
--reporters cli,junit,html \
--reporter-junit-export reports/junit.xml \
--reporter-html-export reports/report.html
"""
}
post {
always {
junit 'reports/junit.xml'
publishHTML(target: [reportDir: 'reports', reportFiles: 'report.html'])
}
failure {
mail to: 'team@example.com',
subject: "🚨 API Tests Failed (#${env.BUILD_NUMBER})",
body: "请查看 Jenkins 构建报告:${env.BUILD_URL}"
}
}
}
}
}
stages:
- mock
- test
mock_service:
stage: mock
image: stoplight/prism
script:
- prism mock openapi.yaml --port 4010
tags:
- docker
api_test:
stage: test
image: node:18
dependencies:
- mock_service
script:
- npm install -g newman
- newman run collections/api_tests.postman_collection.json \
-e environments/dev.json \
--reporters cli,junit \
--reporter-junit-export reports/junit.xml
artifacts:
paths:
- reports/*.xml
when: always
k6 run --vus 100 --duration 30s script.js
通过本篇“API 自动化测试全攻略”,你将掌握API 自动化测试、CI/CD 集成、Mock 服务、性能与安全测试的全流程方案,帮助团队实现高效持续交付与质量保障。立即动手,构建你的下一代 API 自动化测试体系!
原文引自YouTube视频:https://www.youtube.com/watch?v=Un_xNV8h51c