Ejemplo n.º 1
0
func TestValidatesExamplesAgainstSchema(t *testing.T) {
	tests := []string{
		"response",
		"response-ref",
	}

	for _, tt := range tests {
		doc, err := loads.Spec(filepath.Join("fixtures", "validation", "valid-example-"+tt+".json"))
		if assert.NoError(t, err) {
			validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
			validator.spec = doc
			validator.analyzer = analysis.New(doc.Spec())
			res := validator.validateExamplesValidAgainstSchema()
			assert.Empty(t, res.Errors, tt+" should not have errors")
		}

		doc, err = loads.Spec(filepath.Join("fixtures", "validation", "invalid-example-"+tt+".json"))
		if assert.NoError(t, err) {
			validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
			validator.spec = doc
			validator.analyzer = analysis.New(doc.Spec())
			res := validator.validateExamplesValidAgainstSchema()
			assert.NotEmpty(t, res.Errors, tt+" should have errors")
			assert.Len(t, res.Errors, 1, tt+" should have 1 error")
		}
	}
}
Ejemplo n.º 2
0
func TestValidateCircularAncestry(t *testing.T) {
	doc, err := loads.Spec(filepath.Join("fixtures", "validation", "direct-circular-ancestor.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		res := validator.validateDuplicatePropertyNames()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}

	doc, err = loads.Spec(filepath.Join("fixtures", "validation", "indirect-circular-ancestor.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		res := validator.validateDuplicatePropertyNames()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}

	doc, err = loads.Spec(filepath.Join("fixtures", "validation", "recursive-circular-ancestor.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		res := validator.validateDuplicatePropertyNames()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}

}
Ejemplo n.º 3
0
func TestSchemaValidation_AllOfProps(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "AllOfValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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.MinimumInt(\"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.MinimumInt(\"meta\"+\".\"+\"opts\"+\".\"+k,", res)
						assertInCode(t, "validate.MinimumInt(\"meta\"+\".\"+\"extOpts\"+\".\"+k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "validate.MinLength(\"meta\"+\".\"+\"coords\"+\".\"+\"name\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
Ejemplo n.º 4
0
func TestSchemaValidation_RefedAllOf(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "RefedAllOfValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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)
				}
			}
			//}
		}
	}
}
Ejemplo n.º 5
0
func TestGenerateServer_Parameters(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.discriminators.yml")
	if assert.NoError(t, err) {
		method, path, op, ok := analysis.New(specDoc.Spec()).OperationForName("modelOp")
		if assert.True(t, ok) {
			bldr := codeGenOpBuilder{
				Name:          "modelOp",
				Method:        method,
				Path:          path,
				APIPackage:    "restapi",
				ModelsPackage: "models",
				Principal:     "",
				Target:        ".",
				Doc:           specDoc,
				Analyzed:      analysis.New(specDoc.Spec()),
				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)
				}
			}
		}
	}
}
Ejemplo n.º 6
0
func TestSchemaValidation_NamedNestedMap(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedNestedMap"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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.MinimumInt(k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "err := validate.MaximumInt(k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "err := validate.MultipleOf(k+\".\"+kk+\".\"+kkk,", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
Ejemplo n.º 7
0
func TestEnum_MapThing(t *testing.T) {
	specDoc, err := loads.Spec("../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, true, true)
		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 MapThing)", 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)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}
Ejemplo n.º 8
0
func TestEnum_NewPrototype(t *testing.T) {
	// ensure that the enum validation for the anonymous object under the delegate property
	// is rendered.
	specDoc, err := loads.Spec("../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, true, true)
		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 newPrototypeTypeRolePropEnum []interface{}", res)
					assertInCode(t, "var newPrototypeDelegateTypeKindPropEnum []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)
				}
			}
		}
	}
}
Ejemplo n.º 9
0
func TestEnum_SliceAndAdditionalItemsThing(t *testing.T) {
	specDoc, err := loads.Spec("../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, true, true)
		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 sliceAndAdditionalItemsThingTypeP0PropEnum []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)
				}
			}
		}
	}
}
Ejemplo n.º 10
0
func TestSchemaValidation_NestedMapPropsComplex(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NestedMapComplexValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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, "val.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.MinimumInt(\"age\",", res)
						assertInCode(t, "err := validate.MaximumInt(\"age\",", res)
						assertInCode(t, "err := validate.MultipleOf(\"age\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
Ejemplo n.º 11
0
func TestSchemaValidation_SimpleZeroAllowed(t *testing.T) {

	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "SimpleZeroAllowed"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		if assert.NoError(t, err) {
			buf := bytes.NewBuffer(nil)
			err := modelTemplate.Execute(buf, gm)
			if assert.NoError(t, err) {
				formatted, err := formatGoFile("simple_zero_allowed.go", buf.Bytes())
				if assert.NoError(t, err) {
					res := string(formatted)
					assertInCode(t, k+") Validate(formats", res)
					assertInCode(t, "swag.IsZero(m.ID)", res)
					assertInCode(t, "validate.Required(\"name\", \"body\", m.Name)", res)
					assertInCode(t, "validate.MinLength(\"id\", \"body\", string(m.ID), 2)", res)
					assertInCode(t, "validate.Required(\"urls\", \"body\", m.Urls)", res)
					assertInCode(t, "errors.CompositeValidationError(res...)", res)
				}
			}
		}
	}
}
Ejemplo n.º 12
0
func TestSchemaValidation_ArrayAdditionalProps(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "ArrayAdditionalValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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)
					}
				}
			}
		}
	}
}
Ejemplo n.º 13
0
func TestSchemaValidation_RequiredProps(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "RequiredProps"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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)
						}
					}
				}
			}
		}
	}
}
Ejemplo n.º 14
0
func TestSchemaValidation_NamedNestedArray(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedNestedArray"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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)
					}
				}
			}
		}
	}
}
Ejemplo n.º 15
0
func TestSchemaValidation_NamedArrayAdditional(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedArrayAdditional"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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)

					}
				}
			}
		}
	}
}
Ejemplo n.º 16
0
func TestSchemaValidation_NumberProps(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NumberValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		if assert.NoError(t, err) {
			prop := gm.Properties[0]
			if assertValidation(t, "\"age\"", "m.Age", prop) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("number_validations.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "m.validateAge(formats", res)
						assertInCode(t, "err := validate.MinimumInt(\"age\",", res)
						assertInCode(t, "err := validate.MaximumInt(\"age\",", res)
						assertInCode(t, "err := validate.MultipleOf(\"age\",", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
Ejemplo n.º 17
0
func TestSchemaValidation_ArrayProps(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "ArrayValidations"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		if assert.NoError(t, err) {
			prop := gm.Properties[0]
			if assertValidation(t, "\"tags\"", "m.Tags", prop) {
				buf := bytes.NewBuffer(nil)
				err := modelTemplate.Execute(buf, gm)
				if assert.NoError(t, err) {
					formatted, err := formatGoFile("array_validations.go", buf.Bytes())
					if assert.NoError(t, err) {
						res := string(formatted)
						assertInCode(t, k+") Validate(formats", res)
						assertInCode(t, "m.validateTags(formats", res)
						assertInCode(t, "err := validate.MinItems(\"tags\"", res)
						assertInCode(t, "err := validate.MaxItems(\"tags\"", res)
						assertInCode(t, "err := validate.MinLength(\"tags\"+\".\"+strconv.Itoa(i),", res)
						assertInCode(t, "err := validate.MaxLength(\"tags\"+\".\"+strconv.Itoa(i),", res)
						assertInCode(t, "err := validate.Pattern(\"tags\"+\".\"+strconv.Itoa(i),", res)
						assertInCode(t, "errors.CompositeValidationError(res...)", res)
					}
				}
			}
		}
	}
}
Ejemplo n.º 18
0
func TestSchemaValidation_Pet(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "Pet"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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.Required(\"name\", \"body\", m.Name)", res)
					assertInCode(t, "validate.Required(\"photoUrls\", \"body\", m.PhotoUrls)", res)
					assertInCode(t, "errors.CompositeValidationError(res...)", res)
				}
			}
		}
	}
}
Ejemplo n.º 19
0
func TestSchemaValidation_UpdateOrg(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "UpdateOrg"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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())
				}
			}
		}
	}
}
Ejemplo n.º 20
0
func opBuilder(name, fname string) (codeGenOpBuilder, error) {
	if fname == "" {
		fname = "../fixtures/codegen/todolist.simple.yml"
	}

	specDoc, err := loads.Spec(fname)
	if err != nil {
		return codeGenOpBuilder{}, err
	}
	analyzed := analysis.New(specDoc.Spec())

	method, path, op, ok := analyzed.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,
		Analyzed:      analyzed,
		Authed:        false,
		ExtraSchemas:  make(map[string]GenSchema),
	}, nil
}
Ejemplo n.º 21
0
func TestGenerateModel_DiscriminatorSlices(t *testing.T) {
	specDoc, err := loads.Spec("../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, true, true)
		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)
					assertInCode(t, "type Kennel struct {", res)
					assertInCode(t, "ID int64 `json:\"id,omitempty\"`", res)
					assertInCode(t, "Pets []Pet `json:\"pets\"`", res)
					assertInCode(t, "if err := m.Pets[i].Validate(formats); err != nil {", res)
					assertInCode(t, "m.validatePet", res)
				} else {
					fmt.Println(buf.String())
				}
			}
		}
	}
}
Ejemplo n.º 22
0
func TestGenerateModel_Bitbucket_Repository(t *testing.T) {
	specDoc, err := loads.Spec("../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, true, true)
		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)
				}
			}
		}
	}
}
Ejemplo n.º 23
0
func TestSchemaValidation_Strings(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.schemavalidation.yml")
	if assert.NoError(t, err) {
		k := "NamedString"
		schema := specDoc.Spec().Definitions[k]

		gm, err := makeGenDefinition(k, "models", schema, specDoc, true, true)
		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)
					}
				}
			}
		}
	}
}
Ejemplo n.º 24
0
func TestBuildDiscriminatorMap(t *testing.T) {
	specDoc, err := loads.Spec("../fixtures/codegen/todolist.discriminators.yml")
	if assert.NoError(t, err) {
		di := discriminatorInfo(analysis.New(specDoc.Spec()))
		assert.Len(t, di.Discriminators, 1)
		assert.Len(t, di.Discriminators["#/definitions/Pet"].Children, 2)
		assert.Len(t, di.Discriminated, 2)
	}
}
Ejemplo n.º 25
0
func TestValidateDefaultValueAgainstSchema(t *testing.T) {
	doc, _ := loads.Analyzed(PetStoreJSONMessage, "")
	validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
	validator.spec = doc
	validator.analyzer = analysis.New(doc.Spec())
	res := validator.validateDefaultValueValidAgainstSchema()
	assert.Empty(t, res.Errors)

	tests := []string{
		"parameter",
		"parameter-ref",
		"parameter-items",
		"header",
		"header-items",
		"schema",
		"schema-ref",
		"schema-additionalProperties",
		"schema-patternProperties",
		"schema-items",
		"schema-allOf",
	}

	for _, tt := range tests {
		doc, err := loads.Spec(filepath.Join("fixtures", "validation", "valid-default-value-"+tt+".json"))
		if assert.NoError(t, err) {
			validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
			validator.spec = doc
			validator.analyzer = analysis.New(doc.Spec())
			res := validator.validateDefaultValueValidAgainstSchema()
			assert.Empty(t, res.Errors, tt+" should not have errors")
		}

		doc, err = loads.Spec(filepath.Join("fixtures", "validation", "invalid-default-value-"+tt+".json"))
		if assert.NoError(t, err) {
			validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
			validator.spec = doc
			validator.analyzer = analysis.New(doc.Spec())
			res := validator.validateDefaultValueValidAgainstSchema()
			assert.NotEmpty(t, res.Errors, tt+" should have errors")
			assert.Len(t, res.Errors, 1, tt+" should have 1 error")
		}
	}
}
Ejemplo n.º 26
0
// TestValidOpenAPISpec verifies that the open api is added
// at the proper endpoint and the spec is valid.
func TestValidOpenAPISpec(t *testing.T) {
	_, etcdserver, config, assert := setUp(t)
	defer etcdserver.Terminate(t)

	config.GenericConfig.EnableIndex = true
	config.GenericConfig.OpenAPIConfig = genericapiserver.DefaultOpenAPIConfig(openapigen.OpenAPIDefinitions)
	config.GenericConfig.OpenAPIConfig.Info = &spec.Info{
		InfoProps: spec.InfoProps{
			Title:   "Kubernetes",
			Version: "unversioned",
		},
	}
	config.GenericConfig.SwaggerConfig = genericapiserver.DefaultSwaggerConfig()

	master, err := config.Complete().New()
	if err != nil {
		t.Fatalf("Error in bringing up the master: %v", err)
	}

	// make sure swagger.json is not registered before calling PrepareRun.
	server := httptest.NewServer(master.GenericAPIServer.HandlerContainer.ServeMux)
	defer server.Close()
	resp, err := http.Get(server.URL + "/swagger.json")
	if !assert.NoError(err) {
		t.Errorf("unexpected error: %v", err)
	}
	assert.Equal(http.StatusNotFound, resp.StatusCode)

	master.GenericAPIServer.PrepareRun()

	resp, err = http.Get(server.URL + "/swagger.json")
	if !assert.NoError(err) {
		t.Errorf("unexpected error: %v", err)
	}
	assert.Equal(http.StatusOK, resp.StatusCode)

	// as json schema
	var sch spec.Schema
	if assert.NoError(decodeResponse(resp, &sch)) {
		validator := validate.NewSchemaValidator(spec.MustLoadSwagger20Schema(), nil, "", strfmt.Default)
		res := validator.Validate(&sch)
		assert.NoError(res.AsError())
	}

	// Validate OpenApi spec
	doc, err := loads.Spec(server.URL + "/swagger.json")
	if assert.NoError(err) {
		validator := validate.NewSpecValidator(doc.Schema(), strfmt.Default)
		res, warns := validator.Validate(doc)
		assert.NoError(res.AsError())
		if !warns.IsValid() {
			t.Logf("Open API spec on root has some warnings : %v", warns)
		}
	}
}
Ejemplo n.º 27
0
func TestIssue63(t *testing.T) {
	fp := filepath.Join("fixtures", "bugs", "63", "swagger.json")

	// as swagger spec
	doc, err := loads.Spec(fp)
	if assert.NoError(t, err) {
		validator := NewSpecValidator(doc.Schema(), strfmt.Default)
		res, _ := validator.Validate(doc)
		assert.True(t, res.IsValid())
	}
}
Ejemplo n.º 28
0
func TestValidateReferencesValid(t *testing.T) {
	doc, err := loads.Spec(filepath.Join("fixtures", "validation", "valid-ref.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		validator.analyzer = analysis.New(doc.Spec())
		res := validator.validateReferencesValid()
		assert.Empty(t, res.Errors)
	}

	doc, err = loads.Spec(filepath.Join("fixtures", "validation", "invalid-ref.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		validator.analyzer = analysis.New(doc.Spec())
		res := validator.validateReferencesValid()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}
}
Ejemplo n.º 29
0
func TestValidateBodyFormDataParams(t *testing.T) {
	doc, err := loads.Spec(filepath.Join("fixtures", "validation", "invalid-formdata-body-params.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		validator.analyzer = analysis.New(doc.Spec())
		res := validator.validateDefaultValueValidAgainstSchema()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)
	}
}
Ejemplo n.º 30
0
func TestValidateNonEmptyPathParameterNames(t *testing.T) {
	doc, err := loads.Spec(filepath.Join("fixtures", "validation", "empty-path-param-name.json"))
	if assert.NoError(t, err) {
		validator := NewSpecValidator(spec.MustLoadSwagger20Schema(), strfmt.Default)
		validator.spec = doc
		res := validator.validateNonEmptyPathParamNames()
		assert.NotEmpty(t, res.Errors)
		assert.Len(t, res.Errors, 1)

	}
}