提问人:yellowhat 提问时间:11/15/2023 最后编辑:jonrsharpeyellowhat 更新时间:11/15/2023 访问量:78
从 OpenAPI 规范创建模拟服务器
Create a mock server from OpenAPI spec
问:
我正在尝试开发一个 Go 应用程序,该应用程序向 HTTP 服务器发出请求并处理响应。
我想在运行时嘲笑这个服务器。go test ./...
我感兴趣的端点接受带有 2 个参数的请求,例如:POST
/
---
openapi: 3.0.0
info:
title: User API
version: 1.0.0
paths:
/:
post:
summary: Get data
requestBody:
description: Get data
required: true
content:
application/x-www-form-urlencoded:
schema:
type: object
properties:
optType:
type: string
pwd:
type: string
required:
- optType
- pwd
responses:
'201':
description: User created successfully
content:
application/json:
example:
Data:
- 2304
Information:
- 3.0
- 4
理想情况下,在运行单元测试时,应启动 Web 服务器,并使用 JSON 响应端点,如下所示:
{
"Data": [
2304
],
"Information": [
3.0
4
]
}
目前我正在使用:
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Errorf("Expected ‘POST’ request, got ‘%s’", r.Method)
}
if path := r.URL.EscapedPath(); path != "/" {
t.Errorf("Expected request to ‘/’, got ‘%s’", path)
}
err := r.ParseForm()
if err != nil {
t.Errorf("Error in ParseForm, got `%s`", err)
}
if optType := r.Form.Get("optType"); optType != "ReadRealTimeData" {
t.Errorf("Expected `optType` with `ReadRealTimeData`, got ‘%s’", optType)
}
if pwd := r.Form.Get("pwd"); pwd != password {
t.Errorf("Wrong `pwd`, got ‘%s’", pwd)
}
response_json := `{
"Data": [2304],
"Information": [
3.0,
4
]
}`
w.WriteHeader(http.StatusOK)
w.Write([]byte(response_json))
}))
defer server.Close()
能够简单地使用 OpenAPI YAML 文件将更容易、更便携。
有什么建议吗?
答: 暂无答案
评论