public void ShouldEmitSystemTextJsonPropertyName() { // Arrange var mvcOutputFormatter = new MvcOutputFormatter(FormatterOptions.WithSystemTextJsonFormatter, new FakeLoggerFactory()); var responseExample = new ResponseExample(mvcOutputFormatter); var sut = new ServiceProviderExamplesOperationFilter(serviceProvider, null, responseExample); var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerResponseAttribute)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert string jsonExample = ((OpenApiString)response.Content["application/json"].Example).Value; var expectedExample = new PersonResponseAutoExample().GetExamples(); jsonExample.ShouldContain($"\"lastagain\": \"{expectedExample.LastName}\"", Case.Sensitive); }
public void SetsResponseExamples_FromControllerAttributes() { // Arrange var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeControllers.SwaggerResponseExampleController), nameof(FakeControllers.SwaggerResponseExampleController.None)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert var actualExample = JsonConvert.DeserializeObject <PersonResponse>(((OpenApiRawString)response.Content["application/json"].Example).Value); var expectedExample = new PersonResponseExample().GetExamples(); actualExample.Id.ShouldBe(expectedExample.Id); actualExample.FirstName.ShouldBe(expectedExample.FirstName); }
public void Apply_SetsResponseExamples_FromMethodAttributesPascalCase() { // Arrange var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerResponseExampleAttributePascalCase)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert string jsonExample = ((OpenApiRawString)response.Content["application/json"].Example).Value; var expectedExample = (PersonResponse) new PersonResponseExample().GetExamples(); jsonExample.ShouldContain($"\"Id\": {expectedExample.Id}", Case.Sensitive); }
public void Traverse(OpenApiResponse response) { if (response == null) { return; } Visitor.Visit(response); if (response.Headers != null) { foreach (var header in response.Headers) { Traverse(header.Value); } } if (response.Content != null) { foreach (var mediaType in response.Content) { Traverse(mediaType.Value); } } if (response.Links != null) { foreach (var link in response.Links) { Traverse(link.Value); } } }
public void SetsMultipleResponseExamples_FromMethodAttributes() { // Arrange var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerResponseMultipleExamplesAttribute)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert var actualExamples = response.Content["application/json"].Examples; var expectedExamples = new PersonResponseMultipleExamples().GetExamples(); actualExamples.ShouldAllMatch(expectedExamples, ExampleAssertExtensions.ShouldMatch); }
public void Apply(OpenApiOperation operation, OperationFilterContext context) { EnsureArg.IsNotNull(operation, nameof(operation)); EnsureArg.IsNotNull(context, nameof(context)); if (operation.OperationId != null && operation.OperationId.Contains("retrieve", StringComparison.OrdinalIgnoreCase)) { foreach (ApiResponseType responseType in context.ApiDescription.SupportedResponseTypes) { if (responseType.StatusCode == 200) { string responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString(); OpenApiResponse response = operation.Responses[responseKey]; response.Content.Clear(); if (operation.OperationId.EndsWith("Instance", StringComparison.OrdinalIgnoreCase)) { response.Content.Add("application/dicom", new OpenApiMediaType()); } response.Content.Add("multipart/related", new OpenApiMediaType()); } } } }
public async Task GetSwaggerDocs_ReturnsDocsWithHealthEndpointResponseExample() { // Arrange var options = new WebApiProjectOptions(); using (var project = await WebApiProject.StartNewAsync(options, _outputWriter)) // Act using (HttpResponseMessage response = await project.Swagger.GetSwaggerDocsAsync()) { // Assert Assert.Equal(HttpStatusCode.OK, response.StatusCode); string json = await response.Content.ReadAsStringAsync(); OpenApiDocument document = LoadOpenApiDocument(json); OpenApiOperation healthOperation = SelectGetHealthEndpoint(document); OpenApiResponse okResponse = healthOperation.Responses .Single(r => r.Key == "200").Value; OpenApiObject example = SelectHealthPointOkExample(okResponse); Assert.Contains("entries", example.Keys); var entriesCollection = (OpenApiObject)example["entries"]; Assert.Contains("api", entriesCollection.Keys); Assert.Contains("database", entriesCollection.Keys); } }
private static void LoadExample(OpenApiResponse response, string mediaType, ParseNode node) { var exampleNode = node.CreateAny(); if (response.Content == null) { response.Content = new Dictionary <string, OpenApiMediaType>(); } OpenApiMediaType mediaTypeObject; if (response.Content.ContainsKey(mediaType)) { mediaTypeObject = response.Content[mediaType]; } else { mediaTypeObject = new OpenApiMediaType { Schema = node.Context.GetFromTempStorage <OpenApiSchema>(TempStorageKeys.ResponseSchema, response) }; response.Content.Add(mediaType, mediaTypeObject); } mediaTypeObject.Example = exampleNode; }
public static OpenApiResponse LoadResponse(ParseNode node) { var mapNode = node.CheckMapNode("response"); var pointer = mapNode.GetReferencePointer(); if (pointer != null) { return(mapNode.GetReferencedObject <OpenApiResponse>(ReferenceType.Response, pointer)); } var response = new OpenApiResponse(); foreach (var property in mapNode) { property.ParseField(response, _responseFixedFields, _responsePatternFields); } foreach (var mediaType in response.Content.Values) { if (mediaType.Schema != null) { ProcessAnyFields(mapNode, mediaType, _mediaTypeAnyFields); } } return(response); }
public async Task When_yaml_OpenAPI_spec_has_external_schema_refs_they_are_resolved(string relativePath, string docPath, string header) { var path = GetTestDirectory() + relativePath; //// Act OpenApiDocument doc = await OpenApiYamlDocument.FromFileAsync(path); IDictionary <string, OpenApiPathItem> docPaths = doc.Paths; OpenApiPathItem pathItem = docPaths[docPath]; OpenApiOperation operation = pathItem["get"]; IDictionary <string, OpenApiResponse> responses = operation.Responses; OpenApiResponse OK = responses["200"].ActualResponse; OpenApiHeaders OKheaders = OK.Headers; OpenApiResponse Unauthorized = responses["401"].ActualResponse; ////Assert // Header schema loaded correctly from headers.yaml Assert.True(OKheaders.ContainsKey(header)); Assert.NotNull(OKheaders[header]); //Response data loaded correctly from responses.yaml string problemType = "application/problem+json"; Assert.True(Unauthorized.Content.ContainsKey(problemType)); Assert.NotNull(Unauthorized.Content[problemType]); Assert.NotNull(Unauthorized.Schema); }
public async Task When_yaml_OpenAPI_spec_has__relative_external_schema_refs_in_subdirs__they_are_resolved(string relativePath) { var path = GetTestDirectory() + relativePath; OpenApiDocument doc = await OpenApiYamlDocument.FromFileAsync(path); IDictionary <string, OpenApiPathItem> docPaths = doc.Paths; OpenApiPathItem pathItem = docPaths["/life-cycles"]; OpenApiOperation operation = pathItem["get"]; IDictionary <string, OpenApiResponse> responses = operation.Responses; OpenApiResponse OK = responses["200"].ActualResponse; var schema = OK.Content["application/json"]; JsonSchemaProperty items = schema.Schema.ActualSchema.ActualProperties["items"]; var innerProperties = items.Item.ActualSchema.ActualProperties; string[] expectedProperties = new string[] { "id", "systemName", "name", "smallImageID", "helpText" }; foreach (string property in expectedProperties) { Assert.True(innerProperties.ContainsKey(property)); } pathItem = docPaths["/ad-hoc-tasks/{adhocTaskId}/execute"]; operation = pathItem["post"]; responses = operation.Responses; OK = responses["200"].ActualResponse; schema = OK.Content["application/json"]; Assert.Equal("status", schema.Schema.ActualDiscriminator); Assert.Equal("Completed", schema.Schema.ActualDiscriminatorObject.Mapping.Keys.First()); Assert.Equal(2, schema.Schema.ActualSchema.ActualProperties["status"].ActualSchema.Enumeration.Count); }
private void GenerateNoContentResponse(IEndPointMethodHandler endPointMethodHandler, OpenApiResponses responses, bool success) { if (endPointMethodHandler.RouteInformation.HasBody) { if (!responses.ContainsKey("204")) { var response = new OpenApiResponse { Description = "No content" }; if (success) { response.Description += " - successful"; } responses.Add("204", response); } } else { if (!responses.ContainsKey("404")) { responses.Add("404", new OpenApiResponse { Description = "No resource found" }); } } }
private void ApplySwaggerResponseAttributes( OpenApiOperation operation, IEnumerable <object> controllerAndActionAttributes) { var swaggerResponseAttributes = controllerAndActionAttributes .OfType <SwaggerResponseAttribute>(); foreach (var swaggerResponseAttribute in swaggerResponseAttributes) { var statusCode = swaggerResponseAttribute.StatusCode.ToString(); if (operation.Responses == null) { operation.Responses = new OpenApiResponses(); } if (!operation.Responses.TryGetValue(statusCode, out OpenApiResponse response)) { response = new OpenApiResponse(); } if (swaggerResponseAttribute.Description != null) { response.Description = swaggerResponseAttribute.Description; } operation.Responses[statusCode] = response; } }
private static void ProcessProduces(MapNode mapNode, OpenApiResponse response, ParsingContext context) { var produces = context.GetFromTempStorage <List <string> >(TempStorageKeys.OperationProduces) ?? context.GetFromTempStorage <List <string> >(TempStorageKeys.GlobalProduces) ?? new List <string>(); if (response.Content == null) { response.Content = new Dictionary <string, OpenApiMediaType>(); } foreach (var produce in produces) { var schema = context.GetFromTempStorage <OpenApiSchema>(TempStorageKeys.ResponseSchema, response); context.SetTempStorage(TempStorageKeys.ResponseSchema, null, response); if (response.Content.ContainsKey(produce) && response.Content[produce] != null) { if (schema != null) { response.Content[produce].Schema = schema; ProcessAnyFields(mapNode, response.Content[produce], _mediaTypeAnyFields); } } else { var mediaType = new OpenApiMediaType { Schema = schema }; response.Content.Add(produce, mediaType); } } }
public void Apply_ShouldNotEmitObsoleteProperties() { // Arrange schemaGeneratorOptions.IgnoreObsoleteProperties = true; var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerResponseAttribute)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert var actualExample = JsonConvert.DeserializeObject <PersonResponse>(((OpenApiRawString)response.Content["application/json"].Example).Value); var expectedExample = (PersonResponse) new PersonResponseAutoExample().GetExamples(); actualExample.Id.ShouldBe(expectedExample.Id); actualExample.FirstName.ShouldBe(expectedExample.FirstName); actualExample.Age.ShouldBe(0); }
/// <inheritdoc/> protected override void SetResponses(OpenApiOperation operation) { if (EdmOperation.IsAction() && EdmOperation.ReturnType == null) { operation.Responses.Add(Constants.StatusCode204, Constants.StatusCode204.GetResponse()); operation.Responses.Add(Constants.StatusCode200, Constants.StatusCode204.GetResponse()); } else { // function should have a return type. OpenApiResponse response = new OpenApiResponse { Description = "Success", Content = new Dictionary <string, OpenApiMediaType> { { Constants.ApplicationJsonMediaType, new OpenApiMediaType { Schema = Context.CreateEdmTypeSchema(EdmOperation.ReturnType) } } } }; operation.Responses.Add(Constants.StatusCode200, response); } // both action & function has the default response. operation.Responses.Add(Constants.StatusCodeDefault, Constants.StatusCodeDefault.GetResponse()); base.SetResponses(operation); }
public void Apply_SetsResponseExamples_WhenMethodNotAnnotated() { // Arrange var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var supportedResponseTypes = new List <ApiResponseType> { new ApiResponseType { StatusCode = 200, Type = typeof(PersonResponse) } }; var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.PersonResponseNotAnnotated), supportedResponseTypes: supportedResponseTypes); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert var actualExample = JsonConvert.DeserializeObject <PersonResponse>(((OpenApiRawString)response.Content["application/json"].Example).Value); var expectedExample = (PersonResponse) new PersonResponseAutoExample().GetExamples(); actualExample.Id.ShouldBe(expectedExample.Id); actualExample.FirstName.ShouldBe(expectedExample.FirstName); }
/// <summary> /// Converts <see cref="OpenApiResponseWithBodyAttribute"/> to <see cref="OpenApiResponse"/>. /// </summary> /// <param name="attribute"><see cref="OpenApiResponseWithBodyAttribute"/> instance.</param> /// <param name="namingStrategy"><see cref="NamingStrategy"/> instance to create the JSON schema from .NET Types.</param> /// <param name="collection"><see cref="VisitorCollection"/> instance.</param> /// <returns><see cref="OpenApiResponse"/> instance.</returns> public static OpenApiResponse ToOpenApiResponse(this OpenApiResponseWithBodyAttribute attribute, NamingStrategy namingStrategy = null, VisitorCollection collection = null) { attribute.ThrowIfNullOrDefault(); var description = string.IsNullOrWhiteSpace(attribute.Description) ? $"Payload of {attribute.BodyType.GetOpenApiDescription()}" : attribute.Description; var mediaType = attribute.ToOpenApiMediaType <OpenApiResponseWithBodyAttribute>(namingStrategy, collection); var content = new Dictionary <string, OpenApiMediaType>() { { attribute.ContentType, mediaType } }; var response = new OpenApiResponse() { Description = description, Content = content, }; if (attribute.CustomHeaderType.HasInterface <IOpenApiCustomResponseHeader>()) { var header = Activator.CreateInstance(attribute.CustomHeaderType) as IOpenApiCustomResponseHeader; response.Headers = header.Headers; } if (!string.IsNullOrWhiteSpace(attribute.Summary)) { var summary = new OpenApiString(attribute.Summary); response.Extensions.Add("x-ms-summary", summary); } return(response); }
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 void Apply(OpenApiOperation operation, OperationFilterContext context) { if (IsFileResponse(context)) { var key = ((int)HttpStatusCode.OK).ToString(); // Attention! // Accordingly to: https://swagger.io/docs/specification/describing-responses/#response-that-returns-a-file // the type of response should have Format = "binary", Type = "string". var responseSchema = new OpenApiSchema { Format = "binary", Type = "string" }; if (operation.Responses == null) { operation.Responses = new OpenApiResponses(); } if (!operation.Responses.TryGetValue(key, out var response)) { response = new OpenApiResponse(); } response.Description = "OK"; response.Content = new Dictionary <string, OpenApiMediaType> { // TODO: (AK) ? Consider to correct content key depending on real MIME { "multipart/form-data", new OpenApiMediaType() { Schema = responseSchema } } }; } }
public IList <Link> AnalyzeResponse(string statusCode, OpenApiResponse response, PathParameter pathParameter, HttpMethod method) { if (String.IsNullOrWhiteSpace(ResponseCodeFilter) || statusCode.StartsWith(ResponseCodeFilter)) { if (method == HttpMethod.GET && response.Content.Count == 0) { MissingMediaCounter++; } IList <Link> links = new List <Link>(); //iterate over all media types foreach (KeyValuePair <string, OpenApiMediaType> mediaType in response.Content) { IList <Link> linksOfIteration = AnalyzeMediaType(mediaType.Key, mediaType.Value, pathParameter); foreach (Link link in linksOfIteration) { link.StatusCode = statusCode; links.Add(link); } } return(links); } return(new List <Link>()); }
/// <summary> /// Converts <see cref="OpenApiResponseBodyAttribute"/> to <see cref="OpenApiResponse"/>. /// </summary> /// <param name="attribute"><see cref="OpenApiResponseBodyAttribute"/> instance.</param> /// <returns><see cref="OpenApiResponse"/> instance.</returns> public static OpenApiResponse ToOpenApiResponse(this OpenApiResponseBodyAttribute attribute) { attribute.ThrowIfNullOrDefault(); var description = string.IsNullOrWhiteSpace(attribute.Description) ? $"Payload of {attribute.BodyType.GetOpenApiDescription()}" : attribute.Description; var mediaType = attribute.ToOpenApiMediaType <OpenApiResponseBodyAttribute>(); var content = new Dictionary <string, OpenApiMediaType>() { { attribute.ContentType, mediaType } }; var response = new OpenApiResponse() { Description = description, Content = content }; if (!string.IsNullOrWhiteSpace(attribute.Summary)) { var summary = new OpenApiString(attribute.Summary); response.Extensions.Add("x-ms-summary", summary); } return(response); }
public void Apply(OpenApiOperation operation, OperationFilterContext context) { EnsureArg.IsNotNull(operation, nameof(operation)); EnsureArg.IsNotNull(context, nameof(context)); foreach (ApiResponseType responseType in context.ApiDescription.SupportedResponseTypes) { if (responseType.StatusCode == 400 || responseType.StatusCode == 404 || responseType.StatusCode == 406 || responseType.StatusCode == 415) { string responseKey = responseType.IsDefaultResponse ? "default" : responseType.StatusCode.ToString(); OpenApiResponse response = operation.Responses[responseKey]; foreach (string contentType in response.Content.Keys) { if (response.Content.Count == 1) { OpenApiMediaType value = response.Content[contentType]; response.Content.Remove(contentType); response.Content.Add("application/json", value); break; } response.Content.Remove(contentType); } operation.Responses[responseKey] = response; } } }
/// <summary> /// Constructs an OpenApi document that will mapper the /swagger endpoint to the operation. /// </summary> /// <returns> /// The <see cref="OpenApiDocument"/>. /// </returns> public static OpenApiDocument BuildSwaggerDocument() { var jsonMediaType = new OpenApiMediaType { Schema = new OpenApiSchema { Type = "object" } }; var response = new OpenApiResponse(); response.Content.Add("application/json", jsonMediaType); response.Description = "OK"; var operation = new OpenApiOperation { OperationId = SwaggerOperationId, Summary = "View swagger definition for this API", Description = "View swagger definition for this API", }; operation.Responses.Add("200", response); var pathItem = new OpenApiPathItem(); pathItem.Operations.Add(OperationType.Get, operation); return(new OpenApiDocument { Paths = new OpenApiPaths { { "/swagger", pathItem }, }, }); }
public void ShouldNotEmitObsoleteProperties() { // Arrange schemaGeneratorOptions.IgnoreObsoleteProperties = true; var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerResponseExampleAttribute)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert string jsonExample = ((OpenApiRawString)response.Content["application/json"].Example).Value; var expectedExample = new PersonResponseExample().GetExamples(); jsonExample.ShouldNotContain($"\"age\": {expectedExample.Age}", Case.Sensitive); jsonExample.ShouldContain($"\"id\": {expectedExample.Id}", Case.Sensitive); }
public void Apply_DoesNotSetResponseExamples_FromMethodAttributes_WhenSwaggerResponseExampleAttributePresent() { // Arrange var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerResponseExampleAttribute)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert var example = response.Content["application/json"].Example; example.ShouldBeNull(); }
public bool Process(OperationProcessorContext context) { var operation = context.OperationDescription.Operation; var returnsDescription = context.MethodInfo.GetXmlDocsTag("returns"); if (!string.IsNullOrWhiteSpace(returnsDescription)) { foreach (var match in ResponseRegex.Matches(returnsDescription).OfType <Match>()) { var statusCode = match.Groups["Code"].Value; if (!operation.Responses.TryGetValue(statusCode, out var response)) { response = new OpenApiResponse(); operation.Responses[statusCode] = response; } var description = match.Groups["Description"].Value; if (description.Contains("=>")) { throw new InvalidOperationException("Description not formatted correcly."); } response.Description = description; } } return(true); }
public void Apply_SetsResponseExamples_FromMethodAttributes_WithGenericType() { // Arrange var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.GenericAnnotatedWithSwaggerResponseAttribute)); SetSwaggerResponses(operation, filterContext); serviceProvider.GetService(typeof(IExamplesProvider <IEnumerable <string> >)).Returns(new ListStringExample()); // Act sut.Apply(operation, filterContext); // Assert var actualExample = JsonConvert.DeserializeObject <List <string> >(((OpenApiRawString)response.Content["application/json"].Example).Value); actualExample[0].ShouldBe("Hello"); actualExample[1].ShouldBe("there"); }
public void Apply_SetsResponseExamples_CorrectlyFormatsJsonExample() { // Arrange var response = new OpenApiResponse { Content = new Dictionary <string, OpenApiMediaType> { { "application/json", new OpenApiMediaType() } } }; var operation = new OpenApiOperation { OperationId = "foobar", Responses = new OpenApiResponses() }; operation.Responses.Add("200", response); var filterContext = FilterContextFor(typeof(FakeActions), nameof(FakeActions.AnnotatedWithSwaggerResponseExampleAttribute)); SetSwaggerResponses(operation, filterContext); // Act sut.Apply(operation, filterContext); // Assert var example = response.Content["application/json"].Example; var formatedExample = RenderOpenApiObject(example); formatedExample.EndsWith('"').ShouldBeFalse(); formatedExample.StartsWith('"').ShouldBeFalse(); }
public static void AddResponse(OpenApiDocument document, OpenApiOperation operation, ResponseTypeAttribute responseTypeAttr) { OpenApiResponse response = new OpenApiResponse(); response.Description = responseTypeAttr.Description; OpenApiSchema schema = new OpenApiSchema(); schema.Properties = new Dictionary <string, OpenApiSchema>(); schema.Type = "object"; schema.Properties = GetOpenApiProperties(responseTypeAttr.Type); var name = responseTypeAttr.Type.GetName(); if (!document.Components.Schemas.ContainsKey(name)) { document.Components.Schemas.Add(new KeyValuePair <string, OpenApiSchema>(name, schema)); } var mediaType = GetOpenApiMediaType(responseTypeAttr.Type); response.Content.Add(new KeyValuePair <string, OpenApiMediaType>(name, mediaType)); string statusCode = ((int)responseTypeAttr.StatusCode).ToString(); operation.Responses.Add(statusCode, response); }