func TestSimpleResponses(t *testing.T) { b, err := opBuilder("updateTask", "../fixtures/codegen/todolist.responses.yml") if !assert.NoError(t, err) { t.FailNow() } _, _, op, ok := b.Doc.OperationForName("updateTask") if assert.True(t, ok) && assert.NotNil(t, op) && assert.NotNil(t, op.Responses) { resolver := &typeResolver{ModelsPackage: b.ModelsPackage, Doc: b.Doc} if assert.NotNil(t, op.Responses.Default) { resp, err := spec.ResolveResponse(b.Doc.Spec(), op.Responses.Default.Ref) if assert.NoError(t, err) { defCtx := responseTestContext{ OpID: "updateTask", Name: "default", } res, err := b.MakeResponse("a", defCtx.Name, false, resolver, -1, *resp) if assert.NoError(t, err) { if defCtx.Assert(t, *resp, res) { for code, response := range op.Responses.StatusCodeResponses { sucCtx := responseTestContext{ OpID: "updateTask", Name: "success", IsSuccess: code/100 == 2, } res, err := b.MakeResponse("a", sucCtx.Name, sucCtx.IsSuccess, resolver, code, response) if assert.NoError(t, err) { if !sucCtx.Assert(t, response, res) { return } } } } } } } } }
func (b *codeGenOpBuilder) MakeResponse(receiver, name string, isSuccess bool, resolver *typeResolver, code int, resp spec.Response) (GenResponse, error) { if Debug { log.Printf("[%s %s] making id %q", b.Method, b.Path, b.Operation.ID) } if resp.Ref.String() != "" { resp2, err := spec.ResolveResponse(b.Doc.Spec(), resp.Ref) if err != nil { return GenResponse{}, err } if resp2 == nil { return GenResponse{}, fmt.Errorf("could not resolve response ref: %s", resp.Ref.String()) } resp = *resp2 } res := GenResponse{ Package: b.APIPackage, ModelsPackage: b.ModelsPackage, ReceiverName: receiver, Name: name, Description: resp.Description, DefaultImports: nil, Imports: nil, IsSuccess: isSuccess, Code: code, Method: b.Method, Path: b.Path, } for hName, header := range resp.Headers { res.Headers = append(res.Headers, b.MakeHeader(receiver, hName, header)) } sort.Sort(res.Headers) if resp.Schema != nil { sc := schemaGenContext{ Path: fmt.Sprintf("%q", name), Name: name + "Body", Receiver: receiver, ValueExpr: receiver, IndexVar: "i", Schema: *resp.Schema, Required: true, TypeResolver: resolver, Named: false, ExtraSchemas: make(map[string]GenSchema), } if err := sc.makeGenSchema(); err != nil { return GenResponse{}, err } for k, v := range sc.ExtraSchemas { if b.ExtraSchemas == nil { b.ExtraSchemas = make(map[string]GenSchema) } b.ExtraSchemas[k] = v } schema := sc.GenSchema if schema.IsAnonymous { schema.Name = swag.ToGoName(sc.Name + " Body") nm := schema.Name if b.ExtraSchemas == nil { b.ExtraSchemas = make(map[string]GenSchema) } b.ExtraSchemas[schema.Name] = schema schema = GenSchema{} schema.IsAnonymous = false schema.GoType = resolver.goTypeName(nm) schema.SwaggerType = nm } res.Schema = &schema } return res, nil }