Beispiel #1
0
func TestGenerateSwaggerYAML(t *testing.T) {
	seed := spec.Swagger{}
	seed.Host = "testapi.my"
	seed.Produces = []string{"application/json"}
	seed.Consumes = []string{"application/json"}
	seed.Schemes = []string{"http"}
	seed.Info = &spec.Info{}
	seed.Info.Description = "Our very little example API with 2 endpoints"
	seed.Info.Title = "Example API"
	seed.Info.Version = "0.1"
	seed.BasePath = "/"

	generator := NewSwaggerGeneratorYAML(seed)
	tests := getTests()

	doc, err := generator.Generate(tests)
	assert.NoError(t, err, "could not generate docs")

	// checking validity of generated swagger doc
	yamlMap := map[interface{}]interface{}{}
	err = yaml.Unmarshal(doc, &yamlMap)
	assert.NoError(t, err, "could not unmarshal generated doc into map")

	rawJSON, err := fmts.YAMLToJSON(yamlMap)
	assert.NoError(t, err)

	swaggerDoc, err := loads.Analyzed(rawJSON, "")
	assert.NoError(t, err)

	err = validate.Spec(swaggerDoc, strfmt.Default)
	assert.NoError(t, err)

	// checking equality of generated and expected doc
	actual := map[interface{}]interface{}{}
	err = yaml.Unmarshal(doc, &actual)
	assert.NoError(t, err, "could not unmarshal generated doc into map")

	fixture, err := ioutil.ReadFile("fixtures/swagger/swagger.yml")
	assert.NoError(t, err, "could not read fixture file")

	expected := map[interface{}]interface{}{}
	err = yaml.Unmarshal(fixture, &expected)
	assert.NoError(t, err, "could not unmarshal fixture into map")

	assert.Equal(t, expected, actual)
}
Beispiel #2
0
// Analyzed creates a new analyzed spec document
func Analyzed(data json.RawMessage, version string) (*Document, error) {
	if version == "" {
		version = "2.0"
	}
	if version != "2.0" {
		return nil, fmt.Errorf("spec version %q is not supported", version)
	}

	raw := data
	trimmed := bytes.TrimSpace(data)
	if len(trimmed) > 0 {
		if trimmed[0] != '{' && trimmed[0] != '[' {
			yml, err := fmts.BytesToYAMLDoc(trimmed)
			if err != nil {
				return nil, fmt.Errorf("analyzed: %v", err)
			}
			d, err := fmts.YAMLToJSON(yml)
			if err != nil {
				return nil, fmt.Errorf("analyzed: %v", err)
			}
			raw = d
		}
	}

	swspec := new(spec.Swagger)
	if err := json.Unmarshal(raw, swspec); err != nil {
		return nil, err
	}

	origsqspec := new(spec.Swagger)
	if err := json.Unmarshal(raw, origsqspec); err != nil {
		return nil, err
	}

	d := &Document{
		Analyzer: analysis.New(swspec),
		schema:   spec.MustLoadSwagger20Schema(),
		spec:     swspec,
		raw:      raw,
		origSpec: origsqspec,
	}
	return d, nil
}