Example #1
0
func (g *swaggerGenerator) generateSwaggerOperation(test IApiTest, defs spec.Definitions) (spec.Operation, error) {

	op := spec.Operation{}
	op.Responses = &spec.Responses{}
	op.Responses.StatusCodeResponses = map[int]spec.Response{}

	var description string
	processedQueryParams := map[string]interface{}{}
	processedPathParams := map[string]interface{}{}
	processedHeaderParams := map[string]interface{}{}
	for _, testCase := range test.TestCases() {
		// parameter definitions are collected from 2xx tests only
		if testCase.ExpectedHttpCode >= 200 && testCase.ExpectedHttpCode < 300 {
			description = testCase.Description

			for key, param := range testCase.Headers {
				if _, ok := processedHeaderParams[key]; ok {
					continue
				}

				specParam, err := generateSwaggerSpecParam(key, param, "header")
				if err != nil {
					return op, err
				}

				processedHeaderParams[key] = nil
				op.Parameters = append(op.Parameters, specParam)
			}

			for key, param := range testCase.PathParams {
				if _, ok := processedPathParams[key]; ok {
					continue
				}
				param.Required = true // path parameters are always required
				specParam, err := generateSwaggerSpecParam(key, param, "path")
				if err != nil {
					return op, err
				}

				processedPathParams[key] = nil
				op.Parameters = append(op.Parameters, specParam)
			}

			for key, param := range testCase.QueryParams {

				if _, ok := processedQueryParams[key]; ok {
					continue
				}

				specParam, err := generateSwaggerSpecParam(key, param, "query")
				if err != nil {
					return op, err
				}

				processedQueryParams[key] = nil
				op.Parameters = append(op.Parameters, specParam)
			}

			if testCase.RequestBody != nil {
				specParam := spec.Parameter{}
				specParam.Name = "body"
				specParam.In = "body"
				specParam.Required = true

				// TODO: right now it supports json, but should support marshaller depending on MIME type
				if content, err := json.MarshalIndent(testCase.RequestBody, "", "  "); err == nil {
					specParam.Description = string(content)
				}

				specParam.Schema = generateSpecSchema(testCase.RequestBody, defs)
				op.Parameters = append(op.Parameters, specParam)
			}
		}

		response := spec.Response{}
		response.Description = testCase.Description
		if testCase.ExpectedData != nil {
			response.Schema = generateSpecSchema(testCase.ExpectedData, defs)
			response.Examples = map[string]interface{}{
				"application/json": testCase.ExpectedData,
			}
		}

		op.Responses.StatusCodeResponses[testCase.ExpectedHttpCode] = response
	}

	op.Summary = description
	if taggable, ok := test.(ITaggable); ok {
		op.Tags = []string{taggable.Tag()}
	}

	return op, nil
}