Verify / verify (push) Canceled after 0s
从已注册 Controller 的 Form、返回类型及字段声明生成请求、 响应和校验约束,补充显式安全方案与操作级覆盖。 复用 kin-openapi 原生类型与校验,保留合并绑定语义, 为原生路由和无法等价映射的声明提供补充入口。 同步接入指南、迁移边界和可独立运行的契约导出示例。 验证:make verify、make race-check 及实际示例导出通过。
322 lines
13 KiB
Go
322 lines
13 KiB
Go
package http
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"mime/multipart"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/getkin/kin-openapi/openapi3"
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type contractInput struct {
|
|
ID int64 `json:"-" uri:"id" binding:"required,min=1"`
|
|
Email string `json:"email" form:"email" binding:"required,email" dc:"联系邮箱"`
|
|
State string `json:"state" form:"state" binding:"oneof='in progress' done"`
|
|
Names []string `json:"names" form:"names" binding:"min=1,max=3,dive,min=2"`
|
|
OwnerID int64 `json:"owner_id" form:"owner_id" binding:"required"`
|
|
}
|
|
type contractForm struct {
|
|
Meta `path:"/items/:id" method:"POST" summary:"更新条目" tag:"items" security:"bearer"`
|
|
contractInput
|
|
}
|
|
type contractNode struct {
|
|
Name string `json:"name" binding:"min=99"`
|
|
Next *contractNode `json:"next,omitempty"`
|
|
}
|
|
type contractController struct{ calls int }
|
|
|
|
func (c *contractController) Save(_ *gin.Context, form *contractForm) (*contractNode, error) {
|
|
c.calls++
|
|
return &contractNode{Name: form.Email}, nil
|
|
}
|
|
|
|
func TestOpenAPICoversMergedRequestResponseAndSecurity(t *testing.T) {
|
|
server, err := NewServer(Config{SuccessCode: 10}, Options{TrustedFields: map[string]TrustedField{"OwnerID": func(*gin.Context) (any, error) { return int64(1), nil }}})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
controller := &contractController{}
|
|
if err = server.Group("/api", nil, controller); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
schemes := openapi3.SecuritySchemes{"bearer": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "http", Scheme: "bearer", BearerFormat: "JWT"}}}
|
|
options := OpenAPIOptions{Title: "Example", Version: "1.0", SecuritySchemes: schemes}
|
|
doc, err := server.OpenAPI(options)
|
|
if err != nil {
|
|
t.Fatal(err, errors.Unwrap(err))
|
|
}
|
|
if controller.calls != 0 {
|
|
t.Fatal("generation executed controller")
|
|
}
|
|
operation := doc.Paths.Value("/api/items/{id}").Post
|
|
if operation.Summary != "更新条目" || operation.Tags[0] != "items" {
|
|
t.Fatal("metadata lost")
|
|
}
|
|
if operation.Security == nil || len(*operation.Security) != 1 {
|
|
t.Fatal("security declaration missing")
|
|
}
|
|
if _, ok := (*operation.Security)[0]["bearer"]; !ok {
|
|
t.Fatal("bearer requirement lost")
|
|
}
|
|
for _, parameter := range operation.Parameters {
|
|
if parameter.Value.Name == "owner_id" {
|
|
t.Fatal("trusted identity exposed as client input")
|
|
}
|
|
if parameter.Value.In == "path" && (!parameter.Value.Required || !parameter.Value.Schema.Value.Type.Is("integer") || *parameter.Value.Schema.Value.Min != 1) {
|
|
t.Fatal("path schema lost")
|
|
}
|
|
if parameter.Value.In == "query" && parameter.Value.Required {
|
|
t.Fatal("query cannot be independently required when body can supply it")
|
|
}
|
|
}
|
|
body := operation.RequestBody.Value.Content["application/json"].Schema.Value
|
|
if body.Properties["Meta"] != nil || body.Properties["owner_id"] != nil {
|
|
t.Fatal("framework/trusted fields leaked into body")
|
|
}
|
|
if len(body.Required) != 0 || body.Extensions["x-gin-required-after-merge"] == nil {
|
|
t.Fatal("merged-source presence was misrepresented")
|
|
}
|
|
if body.Properties["email"].Value.Format != "email" || body.Properties["email"].Value.Description != "联系邮箱" {
|
|
t.Fatal("field contract missing")
|
|
}
|
|
if body.Properties["state"].Value.Enum[0] != "in progress" {
|
|
t.Fatal("quoted enum split incorrectly")
|
|
}
|
|
array := body.Properties["names"].Value
|
|
if array.MinItems != 1 || *array.MaxItems != 3 || array.Items.Value.MinLength != 2 || array.Items.Value.MaxLength != nil {
|
|
t.Fatal("collection constraints applied to wrong level")
|
|
}
|
|
if err = doc.Validate(context.Background()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
recorder := httptest.NewRecorder()
|
|
request := httptest.NewRequest("POST", "/api/items/1", strings.NewReader(`{"email":"a@example.test","state":"done","names":["ok"]}`))
|
|
request.Header.Set("Content-Type", "application/json")
|
|
server.Handler().ServeHTTP(recorder, request)
|
|
if recorder.Code != 200 {
|
|
t.Fatalf("unexpected actual response %d: %s", recorder.Code, recorder.Body.String())
|
|
}
|
|
var (
|
|
actual any
|
|
)
|
|
if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
response := operation.Responses.Status(200).Value.Content["application/json"].Schema.Value
|
|
if response.Properties["data"].Value.Properties["name"].Value.MinLength != 0 {
|
|
t.Fatal("input rules incorrectly constrain unvalidated output")
|
|
}
|
|
if err = response.VisitJSON(actual); err != nil {
|
|
t.Fatalf("generated response disagrees with actual wire JSON: %v", err)
|
|
}
|
|
if response.Properties["data"].Value.Properties["next"].Ref == "" && response.Properties["data"].Value.Properties["next"].Value == nil {
|
|
t.Fatal("recursive response lost")
|
|
}
|
|
// 返回的文档和选项均不共享到 Server;冻结后也能再次生成。
|
|
doc.Components.SecuritySchemes["bearer"].Value.Scheme = "basic"
|
|
delete(body.Properties, "email")
|
|
next, err := server.OpenAPI(options)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if schemes["bearer"].Value.Scheme != "bearer" || next.Paths.Value("/api/items/{id}").Post.RequestBody.Value.Content["application/json"].Schema.Value.Properties["email"] == nil {
|
|
t.Fatal("document mutation escaped snapshot")
|
|
}
|
|
}
|
|
|
|
type contractQueryForm struct {
|
|
Meta `path:"/search" method:"GET" security:"-"`
|
|
Term string `json:"term" form:"q" binding:"required,min=2"`
|
|
Page int `json:"page" form:"page" binding:"required,min=1" default:"1"`
|
|
Maybe string `json:"maybe" form:"maybe" binding:"omitempty,min=3"`
|
|
Bytes []byte `json:"bytes" form:"bytes" binding:"min=1"`
|
|
Filter struct {
|
|
Active bool `json:"active"`
|
|
} `json:"filter" form:"filter"`
|
|
}
|
|
type contractUploadForm struct {
|
|
Meta `path:"/files" method:"POST"`
|
|
File *multipart.FileHeader `json:"-" form:"file" binding:"required"`
|
|
}
|
|
type contractOtherController struct{}
|
|
|
|
func (*contractOtherController) Search(*gin.Context, *contractQueryForm) (map[string]any, error) {
|
|
return nil, nil
|
|
}
|
|
func (*contractOtherController) Upload(*gin.Context, *contractUploadForm) (any, error) {
|
|
return nil, nil
|
|
}
|
|
|
|
func TestOpenAPIQueryFilesNativeOverridesAndNoImplicitPublication(t *testing.T) {
|
|
server, _ := NewServer(Config{}, Options{})
|
|
if err := server.Group("", nil, &contractOtherController{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := server.Handle("GET", "/stream/*tail", func(*gin.Context) {}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
opts := OpenAPIOptions{Title: "Contract", Version: "v1", SecuritySchemes: openapi3.SecuritySchemes{"key": &openapi3.SecuritySchemeRef{Value: &openapi3.SecurityScheme{Type: "apiKey", In: "header", Name: "X-API-Key"}}}, Security: openapi3.SecurityRequirements{{"key": []string{}}}, Customize: func(meta Metadata, op *openapi3.Operation) error {
|
|
if meta.Path == "/stream/*tail" {
|
|
op.Responses = openapi3.NewResponses(openapi3.WithName("200", openapi3.NewResponse().WithDescription("SSE stream").WithContent(openapi3.Content{"text/event-stream": &openapi3.MediaType{Schema: openapi3.NewStringSchema().NewRef()}})))
|
|
}
|
|
return nil
|
|
}}
|
|
doc, err := server.OpenAPI(opts)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
search := doc.Paths.Value("/search").Get
|
|
if search.RequestBody != nil || search.Security == nil || len(*search.Security) != 0 {
|
|
t.Fatal("GET body or public security override incorrect")
|
|
}
|
|
for _, ref := range search.Parameters {
|
|
parameter := ref.Value
|
|
switch parameter.Name {
|
|
case "q":
|
|
if !parameter.Required || parameter.Schema.Value.MinLength != 2 {
|
|
t.Fatal("required query constraint missing")
|
|
}
|
|
case "page":
|
|
if parameter.Required || parameter.Schema.Value.Default != float64(1) {
|
|
t.Fatal("default incorrectly requires query input")
|
|
}
|
|
case "maybe":
|
|
if parameter.Schema.Value.MinLength != 0 || parameter.Schema.Value.Extensions["x-gin-binding"] == nil {
|
|
t.Fatal("conditional rule falsely strengthened")
|
|
}
|
|
case "filter":
|
|
if parameter.Schema != nil || parameter.Content["application/json"] == nil {
|
|
t.Fatal("structured query JSON representation lost")
|
|
}
|
|
case "bytes":
|
|
if !parameter.Schema.Value.Type.Is("array") || parameter.Schema.Value.MinItems != 1 || !parameter.Schema.Value.Items.Value.Type.Is("integer") {
|
|
t.Fatal("URL byte slice incorrectly described as base64 JSON string")
|
|
}
|
|
}
|
|
}
|
|
file := doc.Paths.Value("/files").Post.RequestBody.Value.Content["multipart/form-data"].Schema.Value.Properties["file"].Value
|
|
if file.Format != "binary" {
|
|
t.Fatal("multipart upload described as internal FileHeader")
|
|
}
|
|
stream := doc.Paths.Value("/stream/{tail}").Get
|
|
if stream.Extensions["x-gin-native"] != true || stream.Parameters[0].Value.Extensions["x-gin-catch-all"] != true || stream.Responses.Status(200).Value.Content["text/event-stream"] == nil {
|
|
t.Fatal("native contract override lost")
|
|
}
|
|
if err = server.Handle("GET", "/after-generation", func(*gin.Context) {}); err != nil {
|
|
t.Fatal("document generation froze registration", err)
|
|
}
|
|
recorder := httptest.NewRecorder()
|
|
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/openapi.json", nil))
|
|
if recorder.Code != 404 {
|
|
t.Fatal("documentation was implicitly published")
|
|
}
|
|
}
|
|
|
|
func TestOpenAPIRejectsInvalidOrIncompleteDeclarations(t *testing.T) {
|
|
server, _ := NewServer(Config{}, Options{})
|
|
if _, err := server.OpenAPI(OpenAPIOptions{}); err == nil {
|
|
t.Fatal("missing info accepted")
|
|
}
|
|
if err := server.Group("", nil, &contractController{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
options := OpenAPIOptions{Title: "Contract", Version: "v1"}
|
|
if doc, err := server.OpenAPI(options); err == nil || doc != nil {
|
|
t.Fatal("undefined bearer scheme accepted")
|
|
}
|
|
options.Customize = func(_ Metadata, op *openapi3.Operation) error {
|
|
requirements := openapi3.SecurityRequirements{}
|
|
op.Security = &requirements
|
|
return nil
|
|
}
|
|
if _, err := server.OpenAPI(options); err != nil {
|
|
t.Fatal("explicit native security override rejected", err, errors.Unwrap(err))
|
|
}
|
|
sentinel := errors.New("contract customization failed")
|
|
options.Customize = func(Metadata, *openapi3.Operation) error { return sentinel }
|
|
if _, err := server.OpenAPI(options); !errors.Is(err, sentinel) {
|
|
t.Fatal("customizer cause lost")
|
|
}
|
|
options.Customize = func(_ Metadata, op *openapi3.Operation) error { op.Responses = openapi3.NewResponses(); return nil }
|
|
if doc, err := server.OpenAPI(options); err == nil || doc != nil {
|
|
t.Fatal("invalid final document accepted")
|
|
}
|
|
native, _ := NewServer(Config{}, Options{})
|
|
if err := native.Handle("GET", "/raw", func(*gin.Context) {}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
doc, err := native.OpenAPI(OpenAPIOptions{Title: "Native", Version: "1"})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(doc.Paths.Value("/raw").Get.Responses.Default().Value.Content) != 0 {
|
|
t.Fatal("native response schema invented")
|
|
}
|
|
}
|
|
|
|
type recursiveValue struct {
|
|
Age *int `json:"age,string"`
|
|
Object struct {
|
|
Enabled bool `json:"enabled"`
|
|
} `json:"object"`
|
|
Next *recursiveValue `json:"next"`
|
|
Children []*recursiveValue `json:"children"`
|
|
Values map[string]*recursiveValue `json:"values"`
|
|
}
|
|
type recursiveForm struct {
|
|
Meta `path:"/recursive" method:"GET"`
|
|
}
|
|
type recursiveController struct{}
|
|
|
|
func (*recursiveController) Get(*gin.Context, *recursiveForm) (recursiveValue, error) {
|
|
return recursiveValue{Children: []*recursiveValue{nil, {}}, Values: map[string]*recursiveValue{"none": nil}}, nil
|
|
}
|
|
|
|
func TestOpenAPIRecursiveValueKeepsNullableFieldsAndCollectionItems(t *testing.T) {
|
|
server, _ := NewServer(Config{}, Options{})
|
|
if err := server.Group("", nil, &recursiveController{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
doc, err := server.OpenAPI(OpenAPIOptions{Title: "Recursive", Version: "1"})
|
|
if err != nil {
|
|
t.Fatal(err, errors.Unwrap(err))
|
|
}
|
|
recorder := httptest.NewRecorder()
|
|
server.Handler().ServeHTTP(recorder, httptest.NewRequest("GET", "/recursive", nil))
|
|
var (
|
|
actual any
|
|
)
|
|
if err = json.Unmarshal(recorder.Body.Bytes(), &actual); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
schema := doc.Paths.Value("/recursive").Get.Responses.Status(200).Value.Content["application/json"].Schema.Value
|
|
if err = schema.VisitJSON(actual); err != nil {
|
|
t.Fatalf("recursive nulls disagree with wire JSON: %v", err)
|
|
}
|
|
}
|
|
|
|
type contractScalarRef string
|
|
type unsupportedReferenceOutput struct {
|
|
Reference contractScalarRef `json:"reference"`
|
|
}
|
|
type unsupportedReferenceController struct{}
|
|
|
|
func (*unsupportedReferenceController) Search(*gin.Context, *contractQueryForm) (unsupportedReferenceOutput, error) {
|
|
return unsupportedReferenceOutput{}, nil
|
|
}
|
|
|
|
func TestOpenAPIUnsupportedReferenceAliasReturnsError(t *testing.T) {
|
|
server, _ := NewServer(Config{}, Options{})
|
|
if err := server.Group("", nil, &unsupportedReferenceController{}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if doc, err := server.OpenAPI(OpenAPIOptions{Title: "Reference", Version: "1"}); err == nil || doc != nil {
|
|
t.Fatal("unsupported scalar Ref alias did not return an error")
|
|
}
|
|
}
|