Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Upgrade to Microsoft.OpenApi v2 #3252

Draft
wants to merge 3 commits into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,14 @@
<PackageVersion Include="Microsoft.AspNetCore.TestHost" Version="6.0.32" />
<PackageVersion Include="Microsoft.CodeAnalysis.PublicApiAnalyzers" Version="3.3.4" />
<PackageVersion Include="Microsoft.Extensions.FileProviders.Embedded" Version="2.1.0" />
<PackageVersion Include="Microsoft.OpenApi" Version="1.6.22" />
<PackageVersion Include="Microsoft.OpenApi.Readers" Version="1.6.22" />
<PackageVersion Include="Microsoft.OpenApi" Version="2.0.0-preview5" />
<PackageVersion Include="Microsoft.OpenApi.Readers" Version="2.0.0-preview5" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="17.12.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.3" />
<PackageVersion Include="NSubstitute" Version="5.3.0" />
<PackageVersion Include="NSwag.MSBuild" Version="14.2.0" />
<PackageVersion Include="ReportGenerator" Version="5.4.1" />
<PackageVersion Include="System.Text.Json" Version="4.6.0" />
<PackageVersion Include="System.Text.Json" Version="8.0.5" />
<PackageVersion Include="Verify.Xunit" Version="28.3.2" />
<PackageVersion Include="xunit" Version="2.9.2" />
<PackageVersion Include="xunit.core" Version="2.9.2" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ public void Setup()
{
Schema = new()
{
Type = "string",
Type = JsonSchemaType.String,
Description = "schema-level description",
},
};
Expand All @@ -120,7 +120,7 @@ public void Setup()
{
Schema = new()
{
Type = "string",
Type = JsonSchemaType.String,
},
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ public class AnnotationsOperationFilter : IOperationFilter
{
public void Apply(OpenApiOperation operation, OperationFilterContext context)
{
IEnumerable<object> controllerAttributes = Array.Empty<object>();
IEnumerable<object> actionAttributes = Array.Empty<object>();
IEnumerable<object> metadataAttributes = Array.Empty<object>();
IEnumerable<object> controllerAttributes = [];
IEnumerable<object> actionAttributes = [];
IEnumerable<object> metadataAttributes = [];

if (context.MethodInfo != null)
{
Expand Down Expand Up @@ -63,12 +63,13 @@ private static void ApplySwaggerOperationAttribute(
if (swaggerOperationAttribute.OperationId != null)
operation.OperationId = swaggerOperationAttribute.OperationId;

if (swaggerOperationAttribute.Tags != null)
{
operation.Tags = swaggerOperationAttribute.Tags
.Select(tagName => new OpenApiTag { Name = tagName })
.ToList();
}
// TODO Fix this
////if (swaggerOperationAttribute.Tags != null)
////{
//// operation.Tags = swaggerOperationAttribute.Tags
//// .Select(tagName => new OpenApiTag { Name = tagName })
//// .ToList();
////}
}

public static void ApplySwaggerOperationFilterAttributes(
Expand All @@ -86,7 +87,7 @@ public static void ApplySwaggerOperationFilterAttributes(
}
}

private void ApplySwaggerResponseAttributes(
private static void ApplySwaggerResponseAttributes(
OpenApiOperation operation,
OperationFilterContext context,
IEnumerable<object> controllerAndActionAttributes)
Expand All @@ -97,10 +98,7 @@ private void ApplySwaggerResponseAttributes(
{
var statusCode = swaggerResponseAttribute.StatusCode.ToString();

if (operation.Responses == null)
{
operation.Responses = new OpenApiResponses();
}
operation.Responses ??= [];

if (!operation.Responses.TryGetValue(statusCode, out OpenApiResponse response))
{
Expand Down
10 changes: 9 additions & 1 deletion src/Swashbuckle.AspNetCore.ApiTesting/ApiTestRunnerBase.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,20 @@
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Reader;
using Microsoft.OpenApi.Readers;
using Microsoft.OpenApi.Writers;

namespace Swashbuckle.AspNetCore.ApiTesting
{
public abstract class ApiTestRunnerBase : IDisposable
{
static ApiTestRunnerBase()
{
// TODO Make an assembly fixture
OpenApiReaderRegistry.RegisterReader(OpenApiConstants.Yaml, new OpenApiYamlReader());
}

private readonly ApiTestRunnerOptions _options;
private readonly RequestValidator _requestValidator;
private readonly ResponseValidator _responseValidator;
Expand Down Expand Up @@ -85,4 +93,4 @@ public void Dispose()
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,25 +1,29 @@
using Microsoft.OpenApi.Models;
using Microsoft.OpenApi.Readers;
using System;
using System;
using System.IO;
using Microsoft.OpenApi.Models;

namespace Swashbuckle.AspNetCore.ApiTesting
{
public static class ApiTestRunnerOptionsExtensions
{
public static void AddOpenApiFile(this ApiTestRunnerOptions options, string documentName, string filePath)
{
using (var fileStream = File.OpenRead(filePath))
{
var openApiDocument = new OpenApiStreamReader().Read(fileStream, out OpenApiDiagnostic diagnostic);
options.OpenApiDocs.Add(documentName, openApiDocument);
}
using var fileStream = File.OpenRead(filePath);
using var memoryStream = new MemoryStream();

fileStream.CopyTo(memoryStream);
memoryStream.Seek(0, SeekOrigin.Begin);

var result = OpenApiDocument.Load(memoryStream);
options.OpenApiDocs.Add(documentName, result.Document);
}

public static OpenApiDocument GetOpenApiDocument(this ApiTestRunnerOptions options, string documentName)
{
if (!options.OpenApiDocs.TryGetValue(documentName, out OpenApiDocument document))
{
throw new InvalidOperationException($"Document with name '{documentName}' not found");
}

return document;
}
Expand Down
21 changes: 9 additions & 12 deletions src/Swashbuckle.AspNetCore.ApiTesting/JsonContentValidator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,24 @@

namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonContentValidator : IContentValidator
public sealed class JsonContentValidator : IContentValidator
{
private readonly JsonValidator _jsonValidator;
private readonly JsonValidator _jsonValidator = new();

public JsonContentValidator()
{
_jsonValidator = new JsonValidator();
}

public bool CanValidate(string mediaType)
{
return mediaType.Contains("json");
}
public bool CanValidate(string mediaType) => mediaType.Contains("json");

public void Validate(OpenApiMediaType mediaTypeSpec, OpenApiDocument openApiDocument, HttpContent content)
{
if (mediaTypeSpec?.Schema == null) return;
if (mediaTypeSpec?.Schema == null)
{
return;
}

var instance = JToken.Parse(content.ReadAsStringAsync().Result);
if (!_jsonValidator.Validate(mediaTypeSpec.Schema, openApiDocument, instance, out IEnumerable<string> errorMessages))
{
throw new ContentDoesNotMatchSpecException(string.Join(Environment.NewLine, errorMessages));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,9 @@

namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonAllOfValidator : IJsonValidator
public sealed class JsonAllOfValidator(JsonValidator jsonValidator) : IJsonValidator
{
private JsonValidator _jsonValidator;

public JsonAllOfValidator(JsonValidator jsonValidator)
{
_jsonValidator = jsonValidator;
}
private readonly JsonValidator _jsonValidator = jsonValidator;

public bool CanValidate(OpenApiSchema schema) => schema.AllOf != null && schema.AllOf.Any();

Expand All @@ -26,14 +21,16 @@ public bool Validate(

var allOfArray = schema.AllOf.ToArray();

for (int i=0;i<allOfArray.Length;i++)
for (int i = 0; i < allOfArray.Length; i++)
{
if (!_jsonValidator.Validate(allOfArray[i], openApiDocument, instance, out IEnumerable<string> subErrorMessages))
{
errorMessagesList.AddRange(subErrorMessages.Select(msg => $"{msg} (allOf[{i}])"));
}
}

errorMessages = errorMessagesList;
return !errorMessages.Any();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,13 @@
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;

namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonAnyOfValidator : IJsonValidator
public sealed class JsonAnyOfValidator(JsonValidator jsonValidator) : IJsonValidator
{
private JsonValidator _jsonValidator;

public JsonAnyOfValidator(JsonValidator jsonValidator)
{
_jsonValidator = jsonValidator;
}
private readonly JsonValidator _jsonValidator = jsonValidator;

public bool CanValidate(OpenApiSchema schema) => schema.AnyOf != null && schema.AnyOf.Any();

Expand All @@ -26,11 +21,11 @@ public bool Validate(

var anyOfArray = schema.AnyOf.ToArray();

for (int i=0;i<anyOfArray.Length;i++)
for (int i = 0; i < anyOfArray.Length; i++)
{
if (_jsonValidator.Validate(anyOfArray[i], openApiDocument, instance, out IEnumerable<string> subErrorMessages))
{
errorMessages = Enumerable.Empty<string>();
errorMessages = [];
return true;
}

Expand All @@ -41,4 +36,4 @@ public bool Validate(
return !errorMessages.Any();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
using System;
using System.Linq;
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;

namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonArrayValidator : IJsonValidator
public class JsonArrayValidator(IJsonValidator jsonValidator) : IJsonValidator
{
private readonly IJsonValidator _jsonValidator;

public JsonArrayValidator(IJsonValidator jsonValidator)
{
_jsonValidator = jsonValidator;
}
private readonly IJsonValidator _jsonValidator = jsonValidator;

public bool CanValidate(OpenApiSchema schema) => schema.Type == "array";
public bool CanValidate(OpenApiSchema schema) => schema.Type is JsonSchemaType.Array;

public bool Validate(
OpenApiSchema schema,
Expand All @@ -25,7 +19,7 @@ public bool Validate(
{
if (instance.Type != JTokenType.Array)
{
errorMessages = new[] { $"Path: {instance.Path}. Instance is not of type 'array'" };
errorMessages = [$"Path: {instance.Path}. Instance is not of type 'array'"];
return false;
}

Expand All @@ -38,24 +32,32 @@ public bool Validate(
foreach (var itemInstance in arrayInstance)
{
if (!_jsonValidator.Validate(schema.Items, openApiDocument, itemInstance, out IEnumerable<string> itemErrorMessages))
{
errorMessagesList.AddRange(itemErrorMessages);
}
}
}

// maxItems
if (schema.MaxItems.HasValue && (arrayInstance.Count() > schema.MaxItems.Value))
if (schema.MaxItems.HasValue && (arrayInstance.Count > schema.MaxItems.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. Array size is greater than maxItems");
}

// minItems
if (schema.MinItems.HasValue && (arrayInstance.Count() < schema.MinItems.Value))
if (schema.MinItems.HasValue && (arrayInstance.Count < schema.MinItems.Value))
{
errorMessagesList.Add($"Path: {instance.Path}. Array size is less than minItems");
}

// uniqueItems
if (schema.UniqueItems.HasValue && (arrayInstance.Count() != arrayInstance.Distinct().Count()))
if (schema.UniqueItems.HasValue && (arrayInstance.Count != arrayInstance.Distinct().Count()))
{
errorMessagesList.Add($"Path: {instance.Path}. Array does not contain uniqueItems");
}

errorMessages = errorMessagesList;
return !errorMessages.Any();
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Linq;

namespace Swashbuckle.AspNetCore.ApiTesting
{
public class JsonBooleanValidator : IJsonValidator
public sealed class JsonBooleanValidator : IJsonValidator
{
public bool CanValidate(OpenApiSchema schema) => schema.Type == "boolean";
public bool CanValidate(OpenApiSchema schema) => schema.Type is JsonSchemaType.Boolean;

public bool Validate(
OpenApiSchema schema,
Expand All @@ -17,12 +16,12 @@ public bool Validate(
{
if (instance.Type != JTokenType.Boolean)
{
errorMessages = new[] { $"Path: {instance.Path}. Instance is not of type 'boolean'" };
errorMessages = [$"Path: {instance.Path}. Instance is not of type 'boolean'"];
return false;
}

errorMessages = Enumerable.Empty<string>();
errorMessages = [];
return true;
}
}
}
}
Loading
Loading