在Linux環境下進行Swagger接口測試,可以通過以下幾種方法和工具來實現:
http://localhost:38081/swagger-ui.html
,查看并測試Swagger UI提供的接口。pytest
運行測試用例。示例代碼如下:import requests
def test_get_users():
response = requests.get('http://localhost:5000/api/users')
assert response.status_code == 200, "Expected status code 200"
assert response.json() is not None, "Expected JSON response"
def test_create_user():
user_data = {
"name": "John Doe",
"email": "johndoe@example.com"
}
response = requests.post('http://localhost:5000/api/users', json=user_data)
assert response.status_code == 201, "Expected status code 201 (Created)"
assert response.json()['name'] == "John Doe", "Expected name to be 'John Doe'"
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 -jar swagger-codegen-cli.jar generate -i https://petstore.swagger.io/v2/swagger.json -l python -o /tmp/python-api-client
npm install -g newman
newman run my_api_collection.json --environment=test_environment.json --reporters cli,html
pip install schemathesis
schemathesis run https://petstore.swagger.io/v2/swagger.json --checks all --base-url http://localhost:8080 --hypothesis-max-examples=100
npm install -g dredd
echo '{
"language": "python",
"server": "python -m SimpleHTTPServer 8080",
"blueprint": "apiary.apib",
"endpoint": "http://localhost:8080"
}' > dredd.yml
dredd
given()
.contentType("application/json")
.body("{ \"id\": 1, \"name\": \"Fido\" }")
.when()
.post("/v2/pet")
.then()
.statusCode(200)
.body("name", equalTo("Fido"));
將上述自動化測試步驟集成到CI/CD流水線中,例如使用Jenkins或GitLab CI,設置質量門禁如代碼覆蓋率80%,以確保測試的質量。
通過上述方法和工具,您可以在Linux環境下有效地測試Swagger接口,確保其功能正常且安全可靠。