在 Debian 上使用 Swagger 进行 API 测试
一 准备环境
二 方式一 使用 Swagger UI 进行交互式测试
openapi: "3.0.0"
info:
title: Sample API
version: "1.0.0"
servers:
- url: http://localhost:3000
paths:
/hello:
get:
summary: 返回问候语
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
message:
type: string
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');
const swaggerDocument = YAML.load('./swagger.yaml');
const app = express();
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
app.get('/hello', (req, res) => res.json({ message: 'Hello, World!' }));
app.listen(3000, () => console.log('Server on http://localhost:3000'));
docker run --name swagger-ui -p 8080:8080 \
-e SWAGGER_JSON=/spec/swagger.json \
-v $PWD/swagger.yaml:/spec/swagger.json \
swaggerapi/swagger-ui
三 方式二 自动化测试与持续集成
import unittest
from client.api.default_api import DefaultApi
from client.configuration import Configuration
class TestApi(unittest.TestCase):
def setUp(self):
config = Configuration()
config.host = "http://localhost:3000"
self.api = DefaultApi(config)
def test_hello(self):
resp = self.api.hello_get()
self.assertEqual(resp[1], 200)
self.assertIn("message", resp[0])
if __name__ == '__main__':
unittest.main()
四 常见问题与排查