Ejemplo n.º 1
0
        public static bool HasSchemaTypeOfHttpStatusCodeUsingSystemNet(this OpenApiResponses responses)
        {
            if (responses == null)
            {
                throw new ArgumentNullException(nameof(responses));
            }

            var httpStatusCodes = responses.GetHttpStatusCodes();

            foreach (var httpStatusCode in httpStatusCodes)
            {
                switch (httpStatusCode)
                {
                case HttpStatusCode.BadRequest:
                case HttpStatusCode.InternalServerError:
                case HttpStatusCode.NotImplemented:
                case HttpStatusCode.BadGateway:
                case HttpStatusCode.ServiceUnavailable:
                case HttpStatusCode.GatewayTimeout:
                    return(true);
                }
            }

            return(false);
        }
        private List <Tuple <HttpStatusCode, string> > GetResponseTypeNames(OpenApiResponses openApiResponses, string segmentName, string operationName)
        {
            var list = new List <Tuple <HttpStatusCode, string> >();

            var httpStatusCodes = openApiResponses.GetHttpStatusCodes();
            var producesResponseAttributeParts = openApiResponses.GetProducesResponseAttributeParts(
                operationName + NameConstants.ContractResult,
                false,
                segmentName,
                OperationSchemaMappings,
                ApiProjectOptions.ProjectName);

            foreach (var producesResponseAttributePart in producesResponseAttributeParts)
            {
                var s = producesResponseAttributePart
                        .Replace("ProducesResponseType(", string.Empty, StringComparison.Ordinal)
                        .Replace("typeof(", string.Empty, StringComparison.Ordinal)
                        .Replace("StatusCodes.Status", string.Empty, StringComparison.Ordinal)
                        .Replace(")", string.Empty, StringComparison.Ordinal)
                        .Replace(" ", string.Empty, StringComparison.Ordinal);
                var sa = s.Split(',');

                switch (sa.Length)
                {
                case 1:
                {
                    foreach (var httpStatusCode in httpStatusCodes)
                    {
                        if (sa[0].IndexOf(((int)httpStatusCode).ToString(GlobalizationConstants.EnglishCultureInfo), StringComparison.Ordinal) != -1)
                        {
                            list.Add(
                                new Tuple <HttpStatusCode, string>(
                                    httpStatusCode,
                                    string.Empty));
                        }
                    }

                    break;
                }

                case 2:
                {
                    foreach (var httpStatusCode in httpStatusCodes)
                    {
                        if (sa[1].IndexOf(((int)httpStatusCode).ToString(GlobalizationConstants.EnglishCultureInfo), StringComparison.Ordinal) != -1)
                        {
                            list.Add(
                                new Tuple <HttpStatusCode, string>(
                                    httpStatusCode,
                                    sa[0]));
                        }
                    }

                    break;
                }
                }
            }

            return(list);
        }
Ejemplo n.º 3
0
 public static KeyValuePair <OperationType, OpenApiOperation> PostOperation(
     string operationId,
     string schemaName,
     IList <OpenApiSecurityRequirement> security,
     IList <OpenApiServer> servers,
     IList <OpenApiTag> tags,
     IList <OpenApiParameter> parameters,
     OpenApiResponses responses,
     OpenApiRequestBody body
     )
 {
     return(new KeyValuePair <OperationType, OpenApiOperation>(
                OperationType.Get,
                new OpenApiOperation
     {
         Deprecated = false,
         Summary = string.Format(ApiStrings.PostOperationSummary, operationId),
         Description = string.Format(ApiStrings.PostOperationDescription, schemaName),
         OperationId = operationId,
         Parameters = parameters ?? new List <OpenApiParameter>(),
         Responses = responses ?? new OpenApiResponses(),
         Tags = tags ?? new List <OpenApiTag>(),
         Servers = servers ?? new List <OpenApiServer>(),
         Security = security ?? new List <OpenApiSecurityRequirement>(),
         RequestBody = body ?? new OpenApiRequestBody()
     }));
 }
Ejemplo n.º 4
0
        public ChangedAPIResponseBO Diff(OpenApiResponses left, OpenApiResponses right, DiffContextBO context)
        {
            var responseMapKeyDiff = MapKeyDiff <string, OpenApiResponse> .Diff(left, right);

            var sharedResponseCodes = responseMapKeyDiff.SharedKey;
            var responses           = new Dictionary <string, ChangedResponseBO>();

            foreach (var responseCode in sharedResponseCodes)
            {
                var diff = _openApiDiff
                           .ResponseDiff
                           .Diff(left[responseCode], right[responseCode], context);

                if (diff != null)
                {
                    responses.Add(responseCode, diff);
                }
            }

            var changedApiResponse =
                new ChangedAPIResponseBO(left, right, context)
            {
                Increased  = responseMapKeyDiff.Increased,
                Missing    = responseMapKeyDiff.Missing,
                Changed    = responses,
                Extensions = _openApiDiff
                             .ExtensionsDiff
                             .Diff(left.Extensions, right.Extensions, context)
            };

            return(ChangedUtils.IsChanged(changedApiResponse));
        }
Ejemplo n.º 5
0
        private void GenerateException(OpenApiResponses ret, ContractMethod method)
        {
            //merge Faults
            var allFaults = method.FaultExceptionAttributes;

            if (!allFaults.Any())
            {
                return;
            }

            foreach (var grouping in allFaults.GroupBy(i => i.StatusCode))
            {
                var des = "[ErrorCode] : <b>[FaultName]</b> [Description]<br>";
                foreach (var item in grouping)
                {
                    des += $"{item.ErrorCode} : <b>{item.DetailType.Name}</b> {item.Description}<br/>";
                }
                des = des.TrimEndString("<br/>");
                var resFault = new OpenApiResponse();
                resFault.Description = des;
                resFault.Content.Add("application/json", new OpenApiMediaType
                {
                    Schema = GenerateSchema(typeof(FaultExceptionJsonObj))
                });

                ret.Add(grouping.Key.ToString(), resFault);
            }
        }
        public async Task OAuthAuthorizeOperationFilter_ShouldNotIncludeSecurityDefinitionResponses_OnNonAuthorizedOperations()
        {
            // Arrange
            using (var client = _testServer.CreateClient())
                // Act
                using (HttpResponseMessage response = await client.GetAsync("swagger/v1/swagger.json"))
                {
                    // Assert
                    Assert.Equal(HttpStatusCode.OK, response.StatusCode);

                    var reader = new OpenApiStreamReader();
                    using (var responseStream = await response.Content.ReadAsStreamAsync())
                    {
                        OpenApiDocument swagger = reader.Read(responseStream, out OpenApiDiagnostic diagnostic);
                        _outputWriter.WriteLine(diagnostic.Errors.Count == 0 ? String.Empty : String.Join(", ", diagnostic.Errors.Select(e => e.Message + ": " + e.Pointer)));

                        Assert.True(
                            swagger.Paths.TryGetValue("/oauth/none", out OpenApiPathItem oauthPath),
                            "Cannot find OAuth none authorized path in Open API spec file");

                        Assert.True(
                            oauthPath.Operations.TryGetValue(OperationType.Get, out OpenApiOperation oauthOperation),
                            "Cannot find OAuth GET operation in Open API spec file");

                        OpenApiResponses oauthResponses = oauthOperation.Responses;
                        Assert.DoesNotContain(oauthResponses, r => r.Key == "401");
                        Assert.DoesNotContain(oauthResponses, r => r.Key == "403");
                    }
                }
        }
Ejemplo n.º 7
0
        private static OpenApiResponses BuildResponses(Responses descriptorResponses)
        {
            var responses = new OpenApiResponses();

            if (descriptorResponses == null)
            {
                return(responses);
            }

            foreach (var(key, value) in descriptorResponses)
            {
                responses.Add(key, new OpenApiResponse
                {
                    Description = value.Description,
                    Reference   = BuildReference(value.Reference),
                    Content     = value.Content?.ToDictionary(
                        x => x.Key,
                        x => new OpenApiMediaType
                    {
                        Schema = BuildSchema(x.Value.Schema),
                    })
                });
            }

            return(responses);
        }
Ejemplo n.º 8
0
    public static List <string> GetProducesResponseAttributeParts(
        this OpenApiResponses responses,
        List <ApiOperationSchemaMap> apiOperationSchemaMappings,
        string contractArea,
        string projectName,
        bool useProblemDetailsAsDefaultResponseBody,
        bool includeIfNotDefinedValidation,
        bool includeIfNotDefinedAuthorization,
        bool includeIfNotDefinedInternalServerError)
    {
        var responseTypes = GetResponseTypes(
            responses,
            apiOperationSchemaMappings,
            contractArea,
            projectName,
            useProblemDetailsAsDefaultResponseBody,
            includeEmptyResponseTypes: true,
            includeIfNotDefinedValidation,
            includeIfNotDefinedAuthorization,
            includeIfNotDefinedInternalServerError,
            isClient: false);

        return(responseTypes
               .OrderBy(x => x.Item1)
               .Select(x => string.IsNullOrEmpty(x.Item2)
                ? $"ProducesResponseType(StatusCodes.Status{(int)x.Item1}{x.Item1})"
                : $"ProducesResponseType(typeof({x.Item2}), StatusCodes.Status{(int)x.Item1}{x.Item1})")
               .ToList());
    }
 public OpenApiResponses ModifyResponses(OpenApiResponses responses, OperationResponseContext context)
 {
     // TODO: Implement Output Parameters
     responses.Remove("200");
     responses.Add("200", new OpenApiResponse()
     {
         Description = "A binary file",
         Content     = new Dictionary <string, OpenApiMediaType>()
         {
             {
                 DefaultContentType,
                 new OpenApiMediaType()
                 {
                     Schema = new OpenApiSchema()
                     {
                         // Actually in v3, type string would be correct, but I don't think this describes it correctly
                         // https://swagger.io/docs/specification/describing-responses/
                         Type   = "file",
                         Format = "binary"
                     }
                 }
             }
         }
     });
     return(responses);
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Create the <see cref="OpenApiResponses"/> for a <see cref="IEdmOperation"/>
        /// </summary>
        /// <param name="context">The OData context.</param>
        /// <param name="operation">The Edm operation.</param>
        /// <returns>The created <see cref="OpenApiResponses"/>.</returns>
        public static OpenApiResponses CreateResponses(this ODataContext context, IEdmOperation operation)
        {
            Utils.CheckArgumentNull(context, nameof(context));
            Utils.CheckArgumentNull(operation, nameof(operation));

            OpenApiResponses responses = new OpenApiResponses();

            if (operation.IsAction())
            {
                responses.Add(Constants.StatusCode204, Constants.StatusCode204.GetResponse());
            }
            else
            {
                OpenApiResponse response = new OpenApiResponse
                {
                    Description = "Success",
                    Content     = new Dictionary <string, OpenApiMediaType>
                    {
                        {
                            Constants.ApplicationJsonMediaType,
                            new OpenApiMediaType
                            {
                                Schema = context.CreateEdmTypeSchema(operation.ReturnType)
                            }
                        }
                    }
                };
                responses.Add(Constants.StatusCode200, response);
            }

            // both action & function has the default response.
            responses.Add(Constants.StatusCodeDefault, Constants.StatusCodeDefault.GetResponse());

            return(responses);
        }
Ejemplo n.º 11
0
        public void HasSchemaTypeOfHttpStatusCodeUsingAspNetCoreHttp(bool expected, OpenApiResponses openApiResponses)
        {
            // Act
            var actual = openApiResponses.HasSchemaTypeOfHttpStatusCodeUsingAspNetCoreHttp();

            // Assert
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 12
0
        public void HasSchemaTypeOfArray(bool expected, OpenApiResponses openApiResponses)
        {
            // Act
            var actual = openApiResponses.HasSchemaTypeOfArray();

            // Assert
            Assert.Equal(expected, actual);
        }
Ejemplo n.º 13
0
        public void GetHttpStatusCodes(List <HttpStatusCode> expected, OpenApiResponses openApiResponses)
        {
            // Act
            var actual = openApiResponses.GetHttpStatusCodes();

            // Assert
            actual.Should().BeEquivalentTo(expected);
        }
Ejemplo n.º 14
0
        public void IsSchemaTypeProblemDetailsForStatusCode(bool expected, OpenApiResponses openApiResponses, HttpStatusCode httpStatusCode)
        {
            // Act
            var actual = openApiResponses.IsSchemaTypeProblemDetailsForStatusCode(httpStatusCode);

            // Assert
            Assert.Equal(expected, actual);
        }
 public static OpenApiResponses WithForbiddenErrorResponse(this OpenApiResponses responses)
 {
     responses.Add("403", new OpenApiResponse()
     {
         Description = "request is forbidden, check your grants."
     });
     return(responses);
 }
 public static OpenApiResponses WithUnchangedResponse(this OpenApiResponses responses, Collection collection)
 {
     responses.Add("304", new OpenApiResponse()
     {
         Description = collection.membername + " has not changed at all."
     });
     return(responses);
 }
 public static OpenApiResponses WithInternalServerErrorResponse(this OpenApiResponses responses)
 {
     responses.Add("500", new OpenApiResponse()
     {
         Description = "an internal server error has been encountered. contact support."
     });
     return(responses);
 }
 public static OpenApiResponses WithDeletedSuccessResponse(this OpenApiResponses responses, Collection collection)
 {
     responses.Add("204", new OpenApiResponse()
     {
         Description = collection.membername + " successfully deleted."
     });
     return(responses);
 }
 public static OpenApiResponses WithCreatedSuccessResponse(this OpenApiResponses responses, Collection collection)
 {
     responses.Add("201", new OpenApiResponse()
     {
         Description = collection.membername + " created."
     });
     return(responses);
 }
Ejemplo n.º 20
0
        public void GetDataTypeForStatusCode(string expected, OpenApiResponses openApiResponses, HttpStatusCode httpStatusCode)
        {
            // Act
            var actual = openApiResponses.GetDataTypeForStatusCode(httpStatusCode);

            // Assert
            Assert.Equal(expected, actual);
        }
 public static OpenApiResponses WithConstraintErrorResponse(this OpenApiResponses responses, Collection collection)
 {
     responses.Add("409", new OpenApiResponse()
     {
         Description = collection.membername + " has not been created because of a constraint that couldn't be validated."
     });
     return(responses);
 }
Ejemplo n.º 22
0
        public static OpenApiResponses CKAN_Responses(string successSchemaName, string successSchemaDescription)
        {
            OpenApiResponses responses = new OpenApiResponses();

            responses[ApiStrings.Response200Key]     = Response200(successSchemaName, successSchemaDescription);
            responses[ApiStrings.ResponseDefaultKey] = ResponseDefault();
            return(responses);
        }
 public static OpenApiResponses WithUnprocessableEntityErrorResponse(this OpenApiResponses responses)
 {
     responses.Add("422", new OpenApiResponse()
     {
         Description = "request is well-formed but given data can't be processed correctly."
     });
     return(responses);
 }
Ejemplo n.º 24
0
        public static OpenApiResponses CKAN_Responses()
        {
            OpenApiResponses responses = new OpenApiResponses();

            responses[ApiStrings.Response200Key]     = Response200("ApiResult");
            responses[ApiStrings.ResponseDefaultKey] = ResponseDefault();
            return(responses);
        }
 public static OpenApiResponses WithNotFoundErrorResponse(this OpenApiResponses responses, Collection collection)
 {
     responses.Add("404", new OpenApiResponse()
     {
         Description = collection.membername + " not found."
     });
     return(responses);
 }
Ejemplo n.º 26
0
        public static OpenApiResponses Responses(OpenApiResponse successResponse, OpenApiResponse errorResponse)
        {
            OpenApiResponses api_responses = new OpenApiResponses();

            api_responses.Add("200", successResponse);
            api_responses.Add("default", errorResponse);
            return(api_responses);
        }
Ejemplo n.º 27
0
        public static string GetModelNameForStatusCode(this OpenApiResponses responses, HttpStatusCode httpStatusCode)
        {
            var responseSchema = responses.GetSchemaForStatusCode(httpStatusCode);

            return(responseSchema == null
                ? string.Empty
                : responseSchema.GetModelName());
        }
Ejemplo n.º 28
0
        public static OpenApiResponse WithCode(this OpenApiResponses responses, HttpStatusCode code)
        {
            var response = new OpenApiResponse();

            responses.Remove(((int)code).ToString());
            responses.Add(((int)code).ToString(), response);
            return(response);
        }
 public static OpenApiResponses WithUnauthorizedErrorResponse(this OpenApiResponses responses)
 {
     responses.Add("401", new OpenApiResponse()
     {
         Description = "request is not authorized, check your credentials."
     });
     return(responses);
 }
    public static string[] CreateUsingListForContractResult(
        OpenApiResponses responses,
        bool useProblemDetailsAsDefaultResponseBody,
        bool hasCreateContentResult)
    {
        ArgumentNullException.ThrowIfNull(responses);

        var list = new List <string>
        {
            "System.CodeDom.Compiler",
            "Microsoft.AspNetCore.Mvc",
        };

        var schemaForStatusCode = responses.GetSchemaForStatusCode(HttpStatusCode.OK);

        if (schemaForStatusCode is not null &&
            schemaForStatusCode.IsFormatTypeUuid())
        {
            list.Add("System");
        }

        if (responses.HasSchemaTypeArray())
        {
            list.Add("System.Linq");
            list.Add("System.Collections.Generic");
        }

        if (hasCreateContentResult)
        {
            if (responses.GetHttpStatusCodes().Any())
            {
                list.Add("System.Net");
            }
        }
        else
        {
            if (responses.GetHttpStatusCodes().Any(x => x != HttpStatusCode.OK))
            {
                list.Add("System.Net");
            }
        }

        if (useProblemDetailsAsDefaultResponseBody)
        {
            list.Add("Atc.Rest.Results");
        }
        else
        {
            list.Add("Atc.Rest.Results");

            if (responses.HasSchemaHttpStatusCodeUsingAspNetCoreHttp())
            {
                list.Add("Microsoft.AspNetCore.Http");
            }
        }

        return(list.ToArray());
    }