Swagger(OpenAPI)自动化测试可以通过多种方式在Linux系统中实现。以下是几种主要方法和工具:
# 安装Swagger Codegen
wget https://repo1.maven.org/maven2/io/swagger/swagger-codegen-cli/2.4.19/swagger-codegen-cli-2.4.19.jar -O swagger-codegen-cli.jar
# 生成测试代码(例如生成Java测试代码)
java -jar swagger-codegen-cli.jar generate \
-i http://petstore.swagger.io/v2/swagger.json \
-l java \
-o /tmp/swagger-test
# 安装Node.js和Newman
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
npm install -g newman
# 从Swagger生成Postman集合
npm install -g openapi-to-postmanv2
openapi2postmanv2 -s swagger.json -o postman_collection.json
# 运行测试
newman run postman_collection.json
# 安装Dredd
npm install -g dredd
# 创建配置文件
dredd init
# 运行测试
dredd swagger.json http://localhost:3000
# 安装依赖
pip install pytest requests openapi-spec-validator
# 示例测试代码
import requests
import pytest
from openapi_spec_validator import validate_spec_url
def test_swagger_spec():
validate_spec_url('http://localhost:3000/swagger.json')
def test_api_endpoints():
response = requests.get('http://localhost:3000/api/users')
assert response.status_code == 200
assert isinstance(response.json(), list)
在Jenkins、GitLab CI或GitHub Actions中集成上述测试方法:
# 示例GitHub Actions配置
name: API Tests
on: [push]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Set up Node.js
uses: actions/setup-node@v1
with:
node-version: '14'
- name: Install dependencies
run: |
npm install -g newman
npm install -g openapi-to-postmanv2
- name: Convert Swagger to Postman
run: openapi2postmanv2 -s swagger.json -o postman_collection.json
- name: Run API tests
run: newman run postman_collection.json
# 安装Karate
mvn archetype:generate \
-DarchetypeGroupId=com.intuit.karate \
-DarchetypeArtifactId=karate-archetype \
-DarchetypeVersion=1.2.0 \
-DgroupId=com.mycompany \
-DartifactId=myproject
Karate测试示例:
Feature: User API Tests
Scenario: Get all users
Given url 'http://localhost:3000/api/users'
When method get
Then status 200
And match response == '#[]'
以上方法可以根据项目需求和技术栈选择最适合的方案进行Swagger API的自动化测试。