Skip to content

Generated code fails to call the Validate function on embedded structs resulting in incorrect validation #2604

@a-h

Description

@a-h

Problem statement

Referencing schemas doesn't enforce validation of fields.

When a post operation defines that its body is PostRequest, but PostRequest is a reference to PostFields, the validation function is empty.

Swagger specification

swagger: '2.0'
info:
  version: 1.0.0
  title: API

paths:
  /test:
    post:
      operationId: testPost
      parameters:
      - in: body
        required: true
        name: postRequest
        schema:
          $ref: '#/definitions/PostRequest'
      responses:
        201:
          description: Test
          schema:
            type: object
            properties:
              msg:
                type: string
                x-isnullable: false
definitions:
  PostRequest:
    $ref: '#/definitions/PostFields'
  PostFields:
    type: object
    required:
    - a
    - b
    properties:
      a:
        type: string
        x-isnullable: false
      b:
        type: string

Steps to reproduce

Assuming the above file is named swagger.yaml:

swagger generate model -f ./swagger.yaml

In the generated code, I'd expect the Validate function of the PostRequest to validate the PostFields struct, but it isn't.

The PostFields struct is embedded in the PostRequest struct, but the Validate method of the PostFields is not called by the Validate method of the PostRequest struct.

This results in the a and b fields of PostRequest not being validated as required.

What I got

type PostRequest struct {
	PostFields
}

// snip...

// Validate validates this post request
func (m *PostRequest) Validate(formats strfmt.Registry) error {
	return nil
}

What I expected

type PostRequest struct {
	PostFields
}

// snip...

// Validate validates this post request
func (m *PostRequest) Validate(formats strfmt.Registry) error {
        if err := m.PostFields.Validate(formats); err != nil {
		return err
        }
	return nil
}

Environment

version: v0.27.0
commit: 43c2774
go version go1.16 darwin/amd64

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmodelRelated to swagger generate model commandpending PRvalidatorRelated to codegen generation of validations

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions