func TestSchemaValidation_NamedNestedMap(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedNestedMap"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			if assertValidation(t, "", "m", gm.GenSchema) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("named_nested_map.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "for k := range m {", res)
						assertInCode(t, "for kk := range m[k] {", res)
						assertInCode(t, "for kkk := range m[k][kk] {", res)
						assertInCode(t, "err := validate.Minimum(k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "err := validate.Maximum(k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "err := validate.MultipleOf(k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
示例#2
0
func TestSchemaValidation_Pet(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "Pet"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, gm)
			if assert.NoError(t, err) {
				formatted, err := formatGoFile("pet.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(formatted)
					assertInCode(t, k+") Validate(formats", res)
					assertInCode(t, "swag.IsZero(m.Status)", res)
					assertInCode(t, "swag.IsZero(m.Tags)", res)
					assertInCode(t, "validate.RequiredString(\"name\", \"body\", string(m.Name))", res)
					assertInCode(t, "validate.Required(\"photoUrls\", \"body\", m.PhotoUrls)", res)
					assertInCode(t, "errors.CompositeValidationError(res...)", res)
				}
			}
		}
	}
}
示例#3
0
func TestGenerateModel_Bitbucket_Repository(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/bitbucket.json")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "repository"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			assert.True(t, genModel.IsNullable)
			for _, gm := range genModel.AllOf {
				for _, p := range gm.Properties {
					if p.Name == "parent" {
						assert.True(t, p.IsNullable)
					}
				}
			}
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				b, err := formatGoFile("repository.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(b)
					assertInCode(t, "Parent *Repository", res)
					assertNotInCode(t, "Parent Repository", res)
				}
			}
		}
	}
}
func TestSchemaValidation_ArrayAdditionalProps(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "ArrayAdditionalValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			prop := gm.Properties[0]
			if assertValidation(t, "\"args\"", "m.Args", prop) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("array_additional_validations.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "m.validateArgs(formats", res)
						assertInCode(t, "err := validate.Required(\"P0\",", res)
						assertInCode(t, "err := validate.MinLength(\"P0\",", res)
						assertInCode(t, "err := validate.MaxLength(\"P0\",", res)
						assertInCode(t, "err := validate.Pattern(\"P0\",", res)
						assertInCode(t, "err := validate.Required(\"P1\",", res)
						assertInCode(t, "err := validate.Minimum(\"P1\",", res)
						assertInCode(t, "err := validate.Maximum(\"P1\",", res)
						assertInCode(t, "err := validate.MultipleOf(\"P1\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
						assertInCode(t, "m.ArrayAdditionalValidationsArgsTuple0Items[i]", res)
					}
				}
			}
		}
	}
}
示例#5
0
func TestEnum_MapThing(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.enums.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "MapThing"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("map_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "var mapThingEnum []interface{}", res)
					assertInCode(t, k+") validateMapThingEnum(path, location string, value map[string]string)", res)
					assertInCode(t, "m.validateMapThingEnum(\"\", \"body\", m)", res)
					assertInCode(t, "var mapThingValueEnum []interface{}", res)
					assertInCode(t, k+") validateMapThingValueEnum(path, location string, value string)", res)
					assertInCode(t, "m.validateMapThingValueEnum(k, \"body\", m[k])", res)
				}
			}
		}
	}
}
func TestSchemaValidation_NamedArrayAdditional(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedArrayAdditional"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			if assertValidation(t, "", "m", gm.GenSchema) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("named_array_additional.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, k+") validateP0(formats", res)
						assertInCode(t, k+") validateP1(formats", res)
						assertInCode(t, "err := validate.Required(\"0\",", res)
						assertInCode(t, "err := validate.MinLength(\"0\",", res)
						assertInCode(t, "err := validate.MaxLength(\"0\",", res)
						assertInCode(t, "err := validate.Pattern(\"0\",", res)
						assertInCode(t, "err := validate.Required(\"1\",", res)
						assertInCode(t, "err := validate.Minimum(\"1\",", res)
						assertInCode(t, "err := validate.Maximum(\"1\",", res)
						assertInCode(t, "err := validate.MultipleOf(\"1\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
						assertInCode(t, "m.NamedArrayAdditionalItems[i]", res)

					}
				}
			}
		}
	}
}
示例#7
0
func TestEnum_SliceAndAdditionalItemsThing(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.enums.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "SliceAndAdditionalItemsThing"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("slice_and_additional_items_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "var sliceAndAdditionalItemsThingEnum []interface{}", res)
					assertInCode(t, k+") validateSliceAndAdditionalItemsThingEnum(path, location string, value SliceAndAdditionalItemsThing)", res)
					//assertInCode(t, "m.validateSliceAndAdditionalItemsThingEnum(\"\", \"body\", m)", res)
					assertInCode(t, "var sliceAndAdditionalItemsThingP0Enum []interface{}", res)
					assertInCode(t, k+") validateP0Enum(path, location string, value string)", res)
					assertInCode(t, "m.validateP0Enum(\"0\", \"body\", m.P0)", res)
					assertInCode(t, "var sliceAndAdditionalItemsThingItemsEnum []interface{}", res)
					assertInCode(t, k+") validateSliceAndAdditionalItemsThingItemsEnum(path, location string, value float32)", res)
					assertInCode(t, "m.validateSliceAndAdditionalItemsThingItemsEnum(strconv.Itoa(i+1), \"body\", m.SliceAndAdditionalItemsThingItems[i])", res)
				}
			}
		}
	}
}
func TestSchemaValidation_NamedNestedArray(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedNestedArray"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			if assertValidation(t, "", "m", gm.GenSchema) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("named_nested_array.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "iNamedNestedArraySize := int64(len(m))", res)
						assertInCode(t, "iiNamedNestedArraySize := int64(len(m[i]))", res)
						assertInCode(t, "iiiNamedNestedArraySize := int64(len(m[i][ii]))", res)
						assertInCode(t, "err := validate.MinItems(\"\"", res)
						assertInCode(t, "err := validate.MaxItems(\"\"", res)
						assertInCode(t, "err := validate.MinItems(strconv.Itoa(i),", res)
						assertInCode(t, "err := validate.MaxItems(strconv.Itoa(i),", res)
						assertInCode(t, "err := validate.MinItems(strconv.Itoa(i)+\".\"+strconv.Itoa(ii),", res)
						assertInCode(t, "err := validate.MaxItems(strconv.Itoa(i)+\".\"+strconv.Itoa(ii),", res)
						assertInCode(t, "err := validate.MinLength(strconv.Itoa(i)+\".\"+strconv.Itoa(ii)+\".\"+strconv.Itoa(iii),", res)
						assertInCode(t, "err := validate.MaxLength(strconv.Itoa(i)+\".\"+strconv.Itoa(ii)+\".\"+strconv.Itoa(iii),", res)
						assertInCode(t, "err := validate.Pattern(strconv.Itoa(i)+\".\"+strconv.Itoa(ii)+\".\"+strconv.Itoa(iii),", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
func TestSchemaValidation_RequiredProps(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "RequiredProps"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			assert.Len(t, gm.Properties, 6)
			for _, p := range gm.Properties {
				if assert.True(t, p.Required) {
					buf := bytes.NewBuffer(nil)
					err := modelTemplate.Execute(buf, gm)
					if assert.NoError(t, err) {
						formatted, err := formatGoFile("required_props.go", buf.Bytes())
						if assert.NoError(t, err) {
							res := string(formatted)
							assertInCode(t, k+") Validate(formats", res)
							assertInCode(t, "validate"+swag.ToGoName(p.Name), res)
							assertInCode(t, "err := validate.Required", res)
							assertInCode(t, "errors.CompositeValidationError(res...)", res)
						}
					}
				}
			}
		}
	}
}
示例#10
0
func TestGenerateModel_WithMapInterface(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.models.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		schema := definitions["WithMapInterface"]
		genModel, err := makeGenDefinition("WithMapInterface", "models", schema, specDoc)
		if assert.NoError(t, err) {
			assert.False(t, genModel.HasAdditionalProperties)
			prop := getDefinitionProperty(genModel, "extraInfo")
			assert.True(t, prop.HasAdditionalProperties)
			assert.True(t, prop.IsMap)
			assert.False(t, prop.IsComplexObject)
			assert.Equal(t, "map[string]interface{}", prop.GoType)
			assert.True(t, prop.Required)
			assert.True(t, prop.HasValidations)
			assert.False(t, prop.NeedsValidation)
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				res := buf.String()
				//fmt.Println(res)
				assertInCode(t, "type WithMapInterface struct {", res)
				assertInCode(t, "ExtraInfo map[string]interface{} `json:\"extraInfo,omitempty\"`", res)
				assertInCode(t, "ExtraInfo map[string]interface{} `json:\"extraInfo,omitempty\"`", res)
			}
		}
	}
}
func TestGenerateModel_DiscriminatorSlices(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.discriminators.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "Kennel"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			assert.True(t, genModel.HasBaseType)
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				b, err := formatGoFile("has_discriminator.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(b)
					fmt.Println(res)
					assertInCode(t, "type Kennel struct {", res)
					assertInCode(t, "ID int64 `json:\"id,omitempty\"`", res)
					assertInCode(t, "Pets []Pet `json:\"pets,omitempty\"`", res)
					assertInCode(t, "if err := m.Pets[i].Validate(formats); err != nil {", res)
					assertInCode(t, "m.validatePet", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}
func TestGenerateServer_Parameters(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.discriminators.yml")
	if assert.NoError(t, err) {
		method, path, op, ok := specDoc.OperationForName("modelOp")
		if assert.True(t, ok) {
			bldr := codeGenOpBuilder{
				Name:          "modelOp",
				Method:        method,
				Path:          path,
				APIPackage:    "restapi",
				ModelsPackage: "models",
				Principal:     "",
				Target:        ".",
				Doc:           specDoc,
				Operation:     *op,
				Authed:        false,
				DefaultScheme: "http",
				ExtraSchemas:  make(map[string]GenSchema),
			}
			genOp, err := bldr.MakeOperation()
			if assert.NoError(t, err) {
				assert.True(t, genOp.Responses[200].Schema.IsBaseType)
				var buf bytes.Buffer
				err := parameterTemplate.Execute(&buf, genOp)
				if assert.NoError(t, err) {
					res := buf.String()
					assertInCode(t, "Pet models.Pet", res)
					assertInCode(t, "body, err := models.UnmarshalPet(r.Body, route.Consumer)", res)
					assertInCode(t, "o.Pet = body", res)
				}
			}
		}
	}
}
示例#13
0
func TestSchemaValidation_Strings(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedString"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			if assertValidation(t, "", "m", gm.GenSchema) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("named_string.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "err := validate.MinLength", res)
						assertInCode(t, "err := validate.MaxLength", res)
						assertInCode(t, "err := validate.Pattern", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
示例#14
0
func TestSchemaValidation_UpdateOrg(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "UpdateOrg"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, gm)
			if assert.NoError(t, err) {
				formatted, err := formatGoFile("pet.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(formatted)
					assertInCode(t, k+") Validate(formats", res)
					assertInCode(t, "swag.IsZero(m.TagExpiration)", res)
					assertInCode(t, "validate.MinimumInt(\"tag_expiration\", \"body\", int64(*m.TagExpiration)", res)
					assertInCode(t, "validate.MaximumInt(\"tag_expiration\", \"body\", int64(*m.TagExpiration)", res)
					assertInCode(t, "errors.CompositeValidationError(res...)", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}
示例#15
0
func TestSchemaValidation_NestedMapPropsComplex(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NestedMapComplexValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			prop := gm.Properties[0]
			if assertValidation(t, "\"meta\"", "m.Meta", prop) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("nested_map_complex_validations.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "m.validateMeta(formats", res)
						assertInCode(t, "for k := range m.Meta {", res)
						assertInCode(t, "for kk := range m.Meta[k] {", res)
						assertInCode(t, "for kkk := range m.Meta[k][kk] {", res)
						assertInCode(t, "m.Meta[k][kk][kkk].Validate(formats)", res)
						assertInCode(t, "err := validate.MinLength(\"name\",", res)
						assertInCode(t, "err := validate.MaxLength(\"name\",", res)
						assertInCode(t, "err := validate.Pattern(\"name\",", res)
						assertInCode(t, "err := validate.Minimum(\"age\",", res)
						assertInCode(t, "err := validate.Maximum(\"age\",", res)
						assertInCode(t, "err := validate.MultipleOf(\"age\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
示例#16
0
func TestGenerateModel_WithItemsAndAdditional2(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.models.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "WithItemsAndAdditional2"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			assert.Nil(t, genModel.Items)
			assert.True(t, genModel.IsComplexObject)
			prop := getDefinitionProperty(genModel, "tags")
			assert.True(t, prop.IsComplexObject)
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				b, err := formatGoFile("with_complex_items.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(b)
					assertInCode(t, "type "+k+" struct {", res)
					assertInCode(t, "type "+k+"TagsTuple0 struct {", res)
					// this would fail if it accepts additionalItems because it would come out as []interface{}
					assertInCode(t, "P0 string `json:\"-\"`", res)
					assertInCode(t, "Tags *"+k+"TagsTuple0 `json:\"tags,omitempty\"`", res)
					assertInCode(t, k+"TagsTuple0Items []int32 `json:\"-\"`", res)

				}
			}
		}
	}
}
示例#17
0
func TestGenerateModel_WithComplexAdditional(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.models.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "WithComplexAdditional"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			assert.Nil(t, genModel.Items)
			assert.True(t, genModel.IsComplexObject)
			prop := getDefinitionProperty(genModel, "tags")
			assert.True(t, prop.IsComplexObject)
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				b, err := formatGoFile("with_complex_additional.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(b)
					assertInCode(t, "type WithComplexAdditional struct {", res)
					assertInCode(t, "type WithComplexAdditionalTagsTuple0 struct {", res)
					assertInCode(t, "Tags *WithComplexAdditionalTagsTuple0 `json:\"tags,omitempty\"`", res)
					assertInCode(t, "P0 string `json:\"-\"`", res)
					assertInCode(t, "WithComplexAdditionalTagsTuple0Items []*WithComplexAdditionalTagsItems `json:\"-\"`", res)
				}
			}
		}
	}
}
示例#18
0
func opBuilder(name, fname string) (codeGenOpBuilder, error) {
	if fname == "" {
		fname = "../fixtures/codegen/todolist.simple.yml"
	}

	specDoc, err := spec.Load(fname)
	if err != nil {
		return codeGenOpBuilder{}, err
	}

	method, path, op, ok := specDoc.OperationForName(name)
	if !ok {
		return codeGenOpBuilder{}, errors.New("No operation could be found for " + name)
	}

	return codeGenOpBuilder{
		Name:          name,
		Method:        method,
		Path:          path,
		APIPackage:    "restapi",
		ModelsPackage: "models",
		Principal:     "models.User",
		Target:        ".",
		Operation:     *op,
		Doc:           specDoc,
		Authed:        false,
		ExtraSchemas:  make(map[string]GenSchema),
	}, nil
}
示例#19
0
func TestEnum_NewPrototype(t *testing.T) {
	// ensure that the enum validation for the anonymous object under the delegate property
	// is rendered.
	specDoc, err := spec.Load("../fixtures/codegen/todolist.enums.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "NewPrototype"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("object_thing.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "ActivatingUser NewPrototypeActivatingUser `json:\"activating_user,omitempty\"`", res)
					assertInCode(t, "Delegate NewPrototypeDelegate `json:\"delegate\"`", res)
					assertInCode(t, "Role string `json:\"role\"`", res)
					assertInCode(t, "var newPrototypeRoleEnum []interface{}", res)
					assertInCode(t, "var newPrototypeDelegateKindEnum []interface{}", res)
					assertInCode(t, "m.validateDelegate(formats)", res)
					assertInCode(t, "m.validateRole(formats)", res)
					assertInCode(t, "m.validateActivatingUser(formats)", res)
					assertInCode(t, "m.Delegate.Validate(formats)", res)
					assertInCode(t, "m.ActivatingUser.Validate(formats)", res)
				}
			}
		}
	}
}
示例#20
0
func TestSchemaValidation_AllOfProps(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "AllOfValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			prop := gm.Properties[0]
			if assertValidation(t, "\"meta\"", "m.Meta", prop) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("all_of_validations.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "m.validateMeta(formats", res)
						assertInCode(t, "validate.MinLength(\"meta\"+\".\"+\"name\",", res)
						assertInCode(t, "validate.Minimum(\"meta\"+\".\"+\"age\",", res)
						assertInCode(t, "validate.MinItems(\"meta\"+\".\"+\"args\",", res)
						assertInCode(t, "validate.MinItems(\"meta\"+\".\"+\"assoc\",", res)
						assertInCode(t, "validate.MinItems(\"meta\"+\".\"+\"assoc\"+\".\"+strconv.Itoa(i),", res)
						assertInCode(t, "validate.MinItems(\"meta\"+\".\"+\"assoc\"+\".\"+strconv.Itoa(i)+\".\"+strconv.Itoa(ii),", res)
						assertInCode(t, "validate.MinLength(\"meta\"+\".\"+\"assoc\"+\".\"+strconv.Itoa(i)+\".\"+strconv.Itoa(ii)+\".\"+strconv.Itoa(iii),", res)
						assertInCode(t, "validate.Minimum(\"meta\"+\".\"+\"opts\"+\".\"+k,", res)
						assertInCode(t, "validate.Minimum(\"meta\"+\".\"+\"extOpts\"+\".\"+k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "validate.MinLength(\"meta\"+\".\"+\"coords\"+\".\"+\"name\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
示例#21
0
func TestSchemaValidation_StringProps(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "StringValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) {
			prop := gm.Properties[0]
			if assertValidation(t, "\"name\"", "m.Name", prop) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("string_validations.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "m.validateName(formats", res)
						assertInCode(t, "err := validate.MinLength(\"name\",", res)
						assertInCode(t, "err := validate.MaxLength(\"name\",", res)
						assertInCode(t, "err := validate.Pattern(\"name\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
func TestSchemaValidation_RefedAllOf(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "RefedAllOfValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) && assert.Len(t, gm.AllOf, 2) {
			//prop := gm.AllOf[0]
			//if assertValidation(t, "\"meta\"", "m.Meta", prop) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, gm)
			if assert.NoError(t, err) {
				formatted, err := formatGoFile("all_of_validations.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(formatted)
					assertInCode(t, k+") Validate(formats", res)
					assertInCode(t, "m.NamedString.Validate(formats)", res)
					assertInCode(t, "m.NamedNumber.Validate(formats)", res)
					assertInCode(t, "errors.CompositeValidationError(res...)", res)
				}
			}
			//}
		}
	}
}
示例#23
0
func TestGenerateModel_WithTuple(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.models.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "WithTuple"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) && assert.NotEmpty(t, genModel.ExtraSchemas) && assert.NotEmpty(t, genModel.Properties) {
			assert.False(t, genModel.IsTuple)
			assert.True(t, genModel.IsComplexObject)
			assert.False(t, genModel.IsArray)
			assert.False(t, genModel.IsAnonymous)

			sch := genModel.ExtraSchemas[0]
			assert.True(t, sch.IsTuple)
			assert.False(t, sch.IsComplexObject)
			assert.False(t, sch.IsArray)
			assert.False(t, sch.IsAnonymous)
			assert.Equal(t, k+"FlagsTuple0", sch.Name)
			assert.False(t, sch.HasAdditionalItems)
			assert.Nil(t, sch.AdditionalItems)

			prop := genModel.Properties[0]
			assert.False(t, genModel.IsTuple)
			assert.True(t, genModel.IsComplexObject)
			assert.False(t, prop.IsArray)
			assert.False(t, prop.IsAnonymous)
			assert.Equal(t, k+"FlagsTuple0", prop.GoType)
			assert.Equal(t, "flags", prop.Name)
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("with_tuple.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "swagger:model "+k+"Flags", res)
					assertInCode(t, "type "+k+"FlagsTuple0 struct {", res)
					assertInCode(t, "P0 int64 `json:\"-\"`", res)
					assertInCode(t, "P1 string `json:\"-\"`", res)
					assertInCode(t, k+"FlagsTuple0) UnmarshalJSON", res)
					assertInCode(t, k+"FlagsTuple0) MarshalJSON", res)
					assertInCode(t, "json.Marshal(data)", res)
					assert.NotRegexp(t, regexp.MustCompile("lastIndex"), res)

					for i, p := range sch.Properties {
						r := "m.P" + strconv.Itoa(i)
						if !p.IsNullable {
							r = "&" + r
						}
						assertInCode(t, "json.Unmarshal(stage1["+strconv.Itoa(i)+"], "+r+")", res)
						assertInCode(t, "P"+strconv.Itoa(i)+",", res)
					}
				}
			}
		}
	}
}
func TestBuildDiscriminatorMap(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.discriminators.yml")
	if assert.NoError(t, err) {
		di := discriminatorInfo(specDoc)
		assert.Len(t, di.Discriminators, 1)
		assert.Len(t, di.Discriminators["#/definitions/Pet"].Children, 2)
		assert.Len(t, di.Discriminated, 2)
	}
}
示例#25
0
func specResolver(t testing.TB, path string) (*spec.Document, *typeResolver, error) {
	tlb, err := spec.Load(path)
	if err != nil {
		return nil, nil, err
	}
	return tlb, &typeResolver{
		Doc:           tlb,
		ModelsPackage: "models",
	}, nil
}
示例#26
0
func TestRuntime_ChunkedResponse(t *testing.T) {
	// test that it can make a simple request
	// and get the response for it.
	// defaults all the way down
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}
	server := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
		if req.Header.Get("Authorization") != "Bearer the-super-secret-token" {
			rw.WriteHeader(400)
			return
		}
		rw.Header().Add(httpkit.HeaderTransferEncoding, "chunked")
		rw.Header().Add(httpkit.HeaderContentType, httpkit.JSONMime+";charset=utf-8")
		rw.WriteHeader(http.StatusOK)
		jsongen := json.NewEncoder(rw)
		jsongen.Encode(result)
	}))

	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})

	specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml")
	hu, _ := url.Parse(server.URL)
	specDoc.Spec().Host = hu.Host
	specDoc.Spec().BasePath = "/"
	if assert.NoError(t, err) {

		runtime := New(specDoc)
		res, err := runtime.Submit(&client.Operation{
			ID:     "getTasks",
			Params: rwrtr,
			Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
				if response.Code() == 200 {
					var result []task
					if err := consumer.Consume(response.Body(), &result); err != nil {
						return nil, err
					}
					return result, nil
				}
				return nil, errors.New("Generic error")
			}),
			AuthInfo: BearerToken("the-super-secret-token"),
		})

		if assert.NoError(t, err) {
			assert.IsType(t, []task{}, res)
			actual := res.([]task)
			assert.EqualValues(t, result, actual)
		}
	}
}
示例#27
0
func TestRuntime_CustomTransport(t *testing.T) {
	rwrtr := client.RequestWriterFunc(func(req client.Request, _ strfmt.Registry) error {
		return nil
	})
	result := []task{
		{false, "task 1 content", 1},
		{false, "task 2 content", 2},
	}

	specDoc, err := spec.Load("../../fixtures/codegen/todolist.simple.yml")
	specDoc.Spec().BasePath = "/"
	specDoc.Spec().Host = "localhost:3245"
	specDoc.Spec().Schemes = []string{"ws", "wss", "https"}

	if assert.NoError(t, err) {
		runtime := New(specDoc)
		runtime.Transport = roundTripperFunc(func(req *http.Request) (*http.Response, error) {
			if req.URL.Scheme != "https" {
				return nil, errors.New("this was not a https request")
			}
			var resp http.Response
			resp.StatusCode = 200
			resp.Header = make(http.Header)
			resp.Header.Set("content-type", "application/json")
			buf := bytes.NewBuffer(nil)
			enc := json.NewEncoder(buf)
			enc.Encode(result)
			resp.Body = ioutil.NopCloser(buf)
			return &resp, nil
		})

		res, err := runtime.Submit(&client.Operation{
			ID:     "getTasks",
			Params: rwrtr,
			Reader: client.ResponseReaderFunc(func(response client.Response, consumer httpkit.Consumer) (interface{}, error) {
				if response.Code() == 200 {
					var result []task
					if err := consumer.Consume(response.Body(), &result); err != nil {
						return nil, err
					}
					return result, nil
				}
				return nil, errors.New("Generic error")
			}),
		})

		if assert.NoError(t, err) {
			assert.IsType(t, []task{}, res)
			actual := res.([]task)
			assert.EqualValues(t, result, actual)
		}
	}
}
示例#28
0
func TestGenerateModel_TupleWithExtra(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.models.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "TupleWithExtra"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) && assert.Empty(t, genModel.ExtraSchemas) {
			assert.True(t, genModel.IsTuple)
			assert.False(t, genModel.IsComplexObject)
			assert.False(t, genModel.IsArray)
			assert.False(t, genModel.IsAnonymous)
			assert.True(t, genModel.HasAdditionalItems)
			assert.NotNil(t, genModel.AdditionalItems)
			assert.Equal(t, k, genModel.Name)
			assert.Equal(t, k, genModel.GoType)
			assert.Len(t, genModel.Properties, 4)
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, genModel)
			if assert.NoError(t, err) {
				ff, err := formatGoFile("tuple_with_extra.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(ff)
					assertInCode(t, "swagger:model "+k, res)
					assertInCode(t, "type "+k+" struct {", res)
					assertInCode(t, "P0 int64 `json:\"-\"`", res)
					assertInCode(t, "P1 string `json:\"-\"`", res)
					assertInCode(t, "P2 strfmt.DateTime `json:\"-\"`", res)
					assertInCode(t, "P3 *Notable `json:\"-\"`", res)
					assertInCode(t, k+"Items []float64 `json:\"-\"`", res)
					assertInCode(t, k+") UnmarshalJSON", res)
					assertInCode(t, k+") MarshalJSON", res)

					for i, p := range genModel.Properties {
						r := "m.P" + strconv.Itoa(i)
						if !p.IsNullable {
							r = "&" + r
						}
						assertInCode(t, "lastIndex = "+strconv.Itoa(i), res)
						assertInCode(t, "json.Unmarshal(stage1["+strconv.Itoa(i)+"], "+r+")", res)
						assertInCode(t, "P"+strconv.Itoa(i)+",", res)
					}
					assertInCode(t, "var lastIndex int", res)
					assertInCode(t, "var toadd float64", res)
					assertInCode(t, "for _, val := range stage1[lastIndex+1:]", res)
					assertInCode(t, "json.Unmarshal(val, &toadd)", res)
					assertInCode(t, "json.Marshal(data)", res)
					assertInCode(t, "for _, v := range m."+k+"Items", res)
				}
			}
		}
	}
}
示例#29
0
文件: spec.go 项目: vmware/vic
func loadSpec(input string) (*spec.Swagger, error) {
	if fi, err := os.Stat(input); err == nil {
		if fi.IsDir() {
			return nil, fmt.Errorf("expected %q to be a file not a directory", input)
		}
		sp, err := spec.Load(input)
		if err != nil {
			return nil, err
		}
		return sp.Spec(), nil
	}
	return nil, nil
}
示例#30
0
func TestGenerateModel_WithAdditional(t *testing.T) {
	specDoc, err := spec.Load("../fixtures/codegen/todolist.models.yml")
	if assert.NoError(t, err) {
		definitions := specDoc.Spec().Definitions
		k := "WithAdditional"
		schema := definitions[k]
		genModel, err := makeGenDefinition(k, "models", schema, specDoc)
		if assert.NoError(t, err) && assert.NotEmpty(t, genModel.ExtraSchemas) {
			assert.False(t, genModel.HasAdditionalProperties)
			assert.False(t, genModel.IsMap)
			assert.False(t, genModel.IsAdditionalProperties)
			assert.True(t, genModel.IsComplexObject)

			sch := genModel.ExtraSchemas[0]
			assert.True(t, sch.HasAdditionalProperties)
			assert.False(t, sch.IsMap)
			assert.True(t, sch.IsAdditionalProperties)
			assert.False(t, sch.IsComplexObject)

			if assert.NotNil(t, sch.AdditionalProperties) {
				prop := findProperty(genModel.Properties, "data")
				assert.False(t, prop.HasAdditionalProperties)
				assert.False(t, prop.IsMap)
				assert.False(t, prop.IsAdditionalProperties)
				assert.True(t, prop.IsComplexObject)
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, genModel)
				if assert.NoError(t, err) {
					res := buf.String()
					assertInCode(t, "type "+k+" struct {", res)
					assertInCode(t, "Data *"+k+"Data `json:\"data,omitempty\"`", res)
					assertInCode(t, "type "+k+"Data struct {", res)
					assertInCode(t, k+"Data map[string]string `json:\"-\"`", res)
					assertInCode(t, "Name string `json:\"name,omitempty\"`", res)
					assertInCode(t, k+"Data) UnmarshalJSON", res)
					assertInCode(t, k+"Data) MarshalJSON", res)
					assertInCode(t, "json.Marshal(m)", res)
					assertInCode(t, "json.Marshal(m."+k+"Data)", res)
					assertInCode(t, "json.Unmarshal(data, &stage1)", res)
					assertInCode(t, "json.Unmarshal(data, &stage2)", res)
					assertInCode(t, "json.Unmarshal(v, &toadd)", res)
					assertInCode(t, "result[k] = toadd", res)
					assertInCode(t, "m."+k+"Data = result", res)
					for _, p := range sch.Properties {
						assertInCode(t, "delete(stage2, \""+p.Name+"\")", res)
					}
				}
			}
		}
	}
}