diff --git a/src/Microsoft.OpenApi.Hidi/Extensions/StringExtensions.cs b/src/Microsoft.OpenApi.Hidi/Extensions/StringExtensions.cs index 99208a1d4..3d6362084 100644 --- a/src/Microsoft.OpenApi.Hidi/Extensions/StringExtensions.cs +++ b/src/Microsoft.OpenApi.Hidi/Extensions/StringExtensions.cs @@ -40,7 +40,7 @@ public static IList SplitByChar(this string target, char separator) { return new List(); } - return target.Split(new char[] { separator }, StringSplitOptions.RemoveEmptyEntries).ToList(); + return target.Split(new[] { separator }, StringSplitOptions.RemoveEmptyEntries).ToList(); } } } diff --git a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs index d473fcd58..96d3cc17d 100644 --- a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs +++ b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs @@ -122,7 +122,7 @@ private static string SingularizeAndDeduplicateOperationId(IList operati var lastSegmentIndex = segmentsCount - 1; var singularizedSegments = new List(); - for (int x = 0; x < segmentsCount; x++) + for (var x = 0; x < segmentsCount; x++) { var segment = operationIdSegments[x].Singularize(inputIsKnownToBePlural: false); diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs index 2c7e921bb..bd240f00e 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/PluginCommandHandler.cs @@ -24,8 +24,8 @@ public int Invoke(InvocationContext context) } public async Task InvokeAsync(InvocationContext context) { - HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); - CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); + var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); + var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel); var logger = loggerFactory.CreateLogger(); diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs index 054912302..dc2f6d8c8 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ShowCommandHandler.cs @@ -24,8 +24,8 @@ public int Invoke(InvocationContext context) } public async Task InvokeAsync(InvocationContext context) { - HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); - CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); + var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); + var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel); var logger = loggerFactory.CreateLogger(); diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs index 293fefec9..c9f46b7ee 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/TransformCommandHandler.cs @@ -24,8 +24,8 @@ public int Invoke(InvocationContext context) } public async Task InvokeAsync(InvocationContext context) { - HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); - CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); + var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); + var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel); var logger = loggerFactory.CreateLogger(); diff --git a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs index 4351a04cb..e0bfbf6b3 100644 --- a/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs +++ b/src/Microsoft.OpenApi.Hidi/Handlers/ValidateCommandHandler.cs @@ -26,8 +26,8 @@ public int Invoke(InvocationContext context) } public async Task InvokeAsync(InvocationContext context) { - HidiOptions hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); - CancellationToken cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); + var hidiOptions = new HidiOptions(context.ParseResult, CommandOptions); + var cancellationToken = (CancellationToken)context.BindingContext.GetRequiredService(typeof(CancellationToken)); using var loggerFactory = Logger.ConfigureLogger(hidiOptions.LogLevel); var logger = loggerFactory.CreateLogger(); try diff --git a/src/Microsoft.OpenApi.Hidi/Logger.cs b/src/Microsoft.OpenApi.Hidi/Logger.cs index dec4a5f8e..2dd1a4ee3 100644 --- a/src/Microsoft.OpenApi.Hidi/Logger.cs +++ b/src/Microsoft.OpenApi.Hidi/Logger.cs @@ -17,10 +17,7 @@ public static ILoggerFactory ConfigureLogger(LogLevel logLevel) return LoggerFactory.Create((builder) => { builder - .AddSimpleConsole(c => - { - c.IncludeScopes = true; - }) + .AddSimpleConsole(c => c.IncludeScopes = true) #if DEBUG .AddDebug() #endif diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs index 22cf230a5..841dd5f20 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiService.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiService.cs @@ -66,8 +66,8 @@ public static async Task TransformOpenApiDocument(HidiOptions options, ILogger l } // Default to yaml and OpenApiVersion 3 during csdl to OpenApi conversion - OpenApiFormat openApiFormat = options.OpenApiFormat ?? (!string.IsNullOrEmpty(options.OpenApi) ? GetOpenApiFormat(options.OpenApi, logger) : OpenApiFormat.Yaml); - OpenApiSpecVersion openApiVersion = options.Version != null ? TryParseOpenApiSpecVersion(options.Version) : OpenApiSpecVersion.OpenApi3_0; + var openApiFormat = options.OpenApiFormat ?? (!string.IsNullOrEmpty(options.OpenApi) ? GetOpenApiFormat(options.OpenApi, logger) : OpenApiFormat.Yaml); + var openApiVersion = options.Version != null ? TryParseOpenApiSpecVersion(options.Version) : OpenApiSpecVersion.OpenApi3_0; // If ApiManifest is provided, set the referenced OpenAPI document var apiDependency = await FindApiDependency(options.FilterOptions.FilterByApiManifest, logger, cancellationToken).ConfigureAwait(false); @@ -85,7 +85,7 @@ public static async Task TransformOpenApiDocument(HidiOptions options, ILogger l } // Load OpenAPI document - OpenApiDocument document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); + var document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); if (options.FilterOptions != null) { @@ -227,7 +227,7 @@ private static async Task GetOpenApi(HidiOptions options, ILogg Stream? filteredStream = null; if (!string.IsNullOrEmpty(options.CsdlFilter)) { - XslCompiledTransform transform = GetFilterTransform(); + var transform = GetFilterTransform(); filteredStream = ApplyFilterToCsdl(stream, options.CsdlFilter, transform); filteredStream.Position = 0; await stream.DisposeAsync().ConfigureAwait(false); @@ -299,7 +299,7 @@ private static Dictionary> GetRequestUrlsFromManifest(ApiDe private static XslCompiledTransform GetFilterTransform() { XslCompiledTransform transform = new(); - Assembly assembly = typeof(OpenApiService).GetTypeInfo().Assembly; + var assembly = typeof(OpenApiService).GetTypeInfo().Assembly; using var xslt = assembly.GetManifestResourceStream("Microsoft.OpenApi.Hidi.CsdlFilter.xslt") ?? throw new InvalidOperationException("Could not find the Microsoft.OpenApi.Hidi.CsdlFilter.xslt file in the assembly. Check build configuration."); using var streamReader = new StreamReader(xslt); using var textReader = new XmlTextReader(streamReader); @@ -310,7 +310,7 @@ private static XslCompiledTransform GetFilterTransform() private static Stream ApplyFilterToCsdl(Stream csdlStream, string entitySetOrSingleton, XslCompiledTransform transform) { using StreamReader inputReader = new(csdlStream, leaveOpen: true); - using XmlReader inputXmlReader = XmlReader.Create(inputReader); + using var inputXmlReader = XmlReader.Create(inputReader); MemoryStream filteredStream = new(); using StreamWriter writer = new(filteredStream, leaveOpen: true); XsltArgumentList args = new(); @@ -363,7 +363,7 @@ public static async Task ValidateOpenApiDocument( private static async Task ParseOpenApi(string openApiFile, bool inlineExternal, ILogger logger, Stream stream, CancellationToken cancellationToken = default) { ReadResult result; - Stopwatch stopwatch = Stopwatch.StartNew(); + var stopwatch = Stopwatch.StartNew(); using (logger.BeginScope("Parsing OpenAPI: {OpenApiFile}", openApiFile)) { stopwatch.Start(); @@ -398,7 +398,7 @@ public static async Task ConvertCsdlToOpenApi(Stream csdl, stri var edmModel = CsdlReader.Parse(XElement.Parse(csdlText).CreateReader()); settings ??= SettingsUtilities.GetConfiguration(); - OpenApiDocument document = edmModel.ConvertToOpenApi(SettingsUtilities.GetOpenApiConvertSettings(settings, metadataVersion)); + var document = edmModel.ConvertToOpenApi(SettingsUtilities.GetOpenApiConvertSettings(settings, metadataVersion)); document = FixReferences(document); return document; @@ -725,7 +725,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C } // Load OpenAPI document - OpenApiDocument document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); + var document = await GetOpenApi(options, logger, options.MetadataVersion, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs b/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs index 95ffceeaa..e7250fb82 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs @@ -16,7 +16,7 @@ public static OpenApiSpecVersion TryParseOpenApiSpecVersion(string value) } var res = value.Split('.', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); - if (int.TryParse(res, out int result)) + if (int.TryParse(res, out var result)) { if (result >= 2 && result < 3) { diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index c0626aa17..1e1973d37 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -152,7 +152,7 @@ private Task LoadExternalRefs(OpenApiDocument document, Cance private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument document) { - List errors = new List(); + var errors = new List(); // Resolve References if requested switch (_settings.ReferenceResolution) diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index eb7459d10..6227514b8 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -89,7 +89,7 @@ internal T ParseFragment(YamlDocument yamlDocument, OpenApiSpecVersion versio { var node = ParseNode.Create(this, yamlDocument.RootNode); - T element = default(T); + var element = default(T); switch (version) { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs index 43824c244..c1cab19f0 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs @@ -17,22 +17,16 @@ internal static partial class OpenApiV2Deserializer private static FixedFieldMap _contactFixedFields = new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { - "url", (o, n) => - { - o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "url", + (o, n) => o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "email", (o, n) => - { - o.Email = n.GetScalarValue(); - } + "email", + (o, n) => o.Email = n.GetScalarValue() }, }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 92643cb92..07bdcb301 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -21,22 +21,21 @@ internal static partial class OpenApiV2Deserializer private static FixedFieldMap _openApiFixedFields = new() { { - "swagger", (o, n) => - { - } /* Version is valid field but we already parsed it */ + "swagger", (_, _) => {} + /* Version is valid field but we already parsed it */ }, {"info", (o, n) => o.Info = LoadInfo(n)}, - {"host", (o, n) => n.Context.SetTempStorage("host", n.GetScalarValue())}, - {"basePath", (o, n) => n.Context.SetTempStorage("basePath", n.GetScalarValue())}, + {"host", (_, n) => n.Context.SetTempStorage("host", n.GetScalarValue())}, + {"basePath", (_, n) => n.Context.SetTempStorage("basePath", n.GetScalarValue())}, { - "schemes", (o, n) => n.Context.SetTempStorage( + "schemes", (_, n) => n.Context.SetTempStorage( "schemes", n.CreateSimpleList( s => s.GetScalarValue())) }, { "consumes", - (o, n) => + (_, n) => { var consumes = n.CreateSimpleList(s => s.GetScalarValue()); if (consumes.Count > 0) @@ -46,7 +45,7 @@ internal static partial class OpenApiV2Deserializer } }, { - "produces", (o, n) => { + "produces", (_, n) => { var produces = n.CreateSimpleList(s => s.GetScalarValue()); if (produces.Count > 0) { @@ -138,7 +137,7 @@ private static void MakeServers(IList servers, ParsingContext con var host = context.GetFromTempStorage("host"); var basePath = context.GetFromTempStorage("basePath"); var schemes = context.GetFromTempStorage>("schemes"); - Uri defaultUrl = rootNode.Context.BaseUrl; + var defaultUrl = rootNode.Context.BaseUrl; // so we don't default to the document path when a host is provided if (string.IsNullOrEmpty(basePath) && !string.IsNullOrEmpty(host)) @@ -172,7 +171,7 @@ private static void MakeServers(IList servers, ParsingContext con } // Create the Server objects - if (schemes != null && schemes.Count > 0) + if (schemes is {Count: > 0}) { foreach (var scheme in schemes) { @@ -295,7 +294,7 @@ private static void FixRequestBodyReferences(OpenApiDocument doc) { // Walk all unresolved parameter references // if id matches with request body Id, change type - if (doc.Components?.RequestBodies != null && doc.Components?.RequestBodies.Count > 0) + if (doc.Components?.RequestBodies is {Count: > 0}) { var fixer = new RequestBodyReferenceFixer(doc.Components?.RequestBodies); var walker = new OpenApiWalker(fixer); diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs index fd2a8f07d..5297a3a72 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs @@ -18,16 +18,12 @@ internal static partial class OpenApiV2Deserializer new() { { - OpenApiConstants.Description, (o, n) => - { - o.Description = n.GetScalarValue(); - } + OpenApiConstants.Description, + (o, n) => o.Description = n.GetScalarValue() }, { - OpenApiConstants.Url, (o, n) => - { - o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + OpenApiConstants.Url, + (o, n) => o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs index d1d6dab0b..a6c99a2d9 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs @@ -19,112 +19,76 @@ internal static partial class OpenApiV2Deserializer private static readonly FixedFieldMap _headerFixedFields = new() { { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "type", (o, n) => - { - GetOrCreateSchema(o).Type = n.GetScalarValue(); - } + "type", + (o, n) => GetOrCreateSchema(o).Type = n.GetScalarValue() }, { - "format", (o, n) => - { - GetOrCreateSchema(o).Format = n.GetScalarValue(); - } + "format", + (o, n) => GetOrCreateSchema(o).Format = n.GetScalarValue() }, { - "items", (o, n) => - { - GetOrCreateSchema(o).Items = LoadSchema(n); - } + "items", + (o, n) => GetOrCreateSchema(o).Items = LoadSchema(n) }, { - "collectionFormat", (o, n) => - { - LoadStyle(o, n.GetScalarValue()); - } + "collectionFormat", + (o, n) => LoadStyle(o, n.GetScalarValue()) }, { - "default", (o, n) => - { - GetOrCreateSchema(o).Default = n.CreateAny(); - } + "default", + (o, n) => GetOrCreateSchema(o).Default = n.CreateAny() }, { - "maximum", (o, n) => - { - GetOrCreateSchema(o).Maximum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maximum", + (o, n) => GetOrCreateSchema(o).Maximum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "exclusiveMaximum", (o, n) => - { - GetOrCreateSchema(o).ExclusiveMaximum = bool.Parse(n.GetScalarValue()); - } + "exclusiveMaximum", + (o, n) => GetOrCreateSchema(o).ExclusiveMaximum = bool.Parse(n.GetScalarValue()) }, { - "minimum", (o, n) => - { - GetOrCreateSchema(o).Minimum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minimum", + (o, n) => GetOrCreateSchema(o).Minimum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "exclusiveMinimum", (o, n) => - { - GetOrCreateSchema(o).ExclusiveMinimum = bool.Parse(n.GetScalarValue()); - } + "exclusiveMinimum", + (o, n) => GetOrCreateSchema(o).ExclusiveMinimum = bool.Parse(n.GetScalarValue()) }, { - "maxLength", (o, n) => - { - GetOrCreateSchema(o).MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxLength", + (o, n) => GetOrCreateSchema(o).MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minLength", (o, n) => - { - GetOrCreateSchema(o).MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minLength", + (o, n) => GetOrCreateSchema(o).MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "pattern", (o, n) => - { - GetOrCreateSchema(o).Pattern = n.GetScalarValue(); - } + "pattern", + (o, n) => GetOrCreateSchema(o).Pattern = n.GetScalarValue() }, { - "maxItems", (o, n) => - { - GetOrCreateSchema(o).MaxItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxItems", + (o, n) => GetOrCreateSchema(o).MaxItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minItems", (o, n) => - { - GetOrCreateSchema(o).MinItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minItems", + (o, n) => GetOrCreateSchema(o).MinItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "uniqueItems", (o, n) => - { - GetOrCreateSchema(o).UniqueItems = bool.Parse(n.GetScalarValue()); - } + "uniqueItems", + (o, n) => GetOrCreateSchema(o).UniqueItems = bool.Parse(n.GetScalarValue()) }, { - "multipleOf", (o, n) => - { - GetOrCreateSchema(o).MultipleOf = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "multipleOf", + (o, n) => GetOrCreateSchema(o).MultipleOf = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "enum", (o, n) => - { - GetOrCreateSchema(o).Enum = n.CreateListOfAny(); - } + "enum", + (o, n) => GetOrCreateSchema(o).Enum = n.CreateListOfAny() } }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs index ffe9045d3..479eaa5c8 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs @@ -17,40 +17,28 @@ internal static partial class OpenApiV2Deserializer private static FixedFieldMap _infoFixedFields = new() { { - "title", (o, n) => - { - o.Title = n.GetScalarValue(); - } + "title", + (o, n) => o.Title = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "termsOfService", (o, n) => - { - o.TermsOfService = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "termsOfService", + (o, n) => o.TermsOfService = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "contact", (o, n) => - { - o.Contact = LoadContact(n); - } + "contact", + (o, n) => o.Contact = LoadContact(n) }, { - "license", (o, n) => - { - o.License = LoadLicense(n); - } + "license", + (o, n) => o.License = LoadLicense(n) }, { - "version", (o, n) => - { - o.Version = n.GetScalarValue(); - } + "version", + (o, n) => o.Version = n.GetScalarValue() } }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs index 965675143..db394087f 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs @@ -17,16 +17,12 @@ internal static partial class OpenApiV2Deserializer private static FixedFieldMap _licenseFixedFields = new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { - "url", (o, n) => - { - o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "url", + (o, n) => o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index c7a7d723b..098222299 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -27,37 +27,27 @@ internal static partial class OpenApiV2Deserializer valueNode.GetScalarValue())) }, { - "summary", (o, n) => - { - o.Summary = n.GetScalarValue(); - } + "summary", + (o, n) => o.Summary = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "externalDocs", (o, n) => - { - o.ExternalDocs = LoadExternalDocs(n); - } + "externalDocs", + (o, n) => o.ExternalDocs = LoadExternalDocs(n) }, { - "operationId", (o, n) => - { - o.OperationId = n.GetScalarValue(); - } + "operationId", + (o, n) => o.OperationId = n.GetScalarValue() }, { - "parameters", (o, n) => - { - o.Parameters = n.CreateList(LoadParameter); - } + "parameters", + (o, n) => o.Parameters = n.CreateList(LoadParameter) }, { - "consumes", (o, n) => { + "consumes", (_, n) => { var consumes = n.CreateSimpleList(s => s.GetScalarValue()); if (consumes.Count > 0) { n.Context.SetTempStorage(TempStorageKeys.OperationConsumes,consumes); @@ -65,7 +55,7 @@ internal static partial class OpenApiV2Deserializer } }, { - "produces", (o, n) => { + "produces", (_, n) => { var produces = n.CreateSimpleList(s => s.GetScalarValue()); if (produces.Count > 0) { n.Context.SetTempStorage(TempStorageKeys.OperationProduces, produces); @@ -73,22 +63,16 @@ internal static partial class OpenApiV2Deserializer } }, { - "responses", (o, n) => - { - o.Responses = LoadResponses(n); - } + "responses", + (o, n) => o.Responses = LoadResponses(n) }, { - "deprecated", (o, n) => - { - o.Deprecated = bool.Parse(n.GetScalarValue()); - } + "deprecated", + (o, n) => o.Deprecated = bool.Parse(n.GetScalarValue()) }, { - "security", (o, n) => - { - o.Security = n.CreateList(LoadSecurityRequirement); - } + "security", + (o, n) => o.Security = n.CreateList(LoadSecurityRequirement) }, }; @@ -185,7 +169,7 @@ private static OpenApiRequestBody CreateFormBody(ParsingContext context, List k, - v => mediaType) + _ => mediaType) }; return formBody; @@ -205,7 +189,7 @@ internal static OpenApiRequestBody CreateRequestBody( Required = bodyParameter.Required, Content = consumes.ToDictionary( k => k, - v => new OpenApiMediaType + _ => new OpenApiMediaType { Schema = bodyParameter.Schema }), diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs index b0013d9ae..1c47a340a 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs @@ -20,118 +20,80 @@ internal static partial class OpenApiV2Deserializer new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { - "in", (o, n) => - { - ProcessIn(o, n); - } + "in", + ProcessIn }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "required", (o, n) => - { - o.Required = bool.Parse(n.GetScalarValue()); - } + "required", + (o, n) => o.Required = bool.Parse(n.GetScalarValue()) }, { - "deprecated", (o, n) => - { - o.Deprecated = bool.Parse(n.GetScalarValue()); - } + "deprecated", + (o, n) => o.Deprecated = bool.Parse(n.GetScalarValue()) }, { - "allowEmptyValue", (o, n) => - { - o.AllowEmptyValue = bool.Parse(n.GetScalarValue()); - } + "allowEmptyValue", + (o, n) => o.AllowEmptyValue = bool.Parse(n.GetScalarValue()) }, { - "type", (o, n) => - { - GetOrCreateSchema(o).Type = n.GetScalarValue(); - } + "type", + (o, n) => GetOrCreateSchema(o).Type = n.GetScalarValue() }, { - "items", (o, n) => - { - GetOrCreateSchema(o).Items = LoadSchema(n); - } + "items", + (o, n) => GetOrCreateSchema(o).Items = LoadSchema(n) }, { - "collectionFormat", (o, n) => - { - LoadStyle(o, n.GetScalarValue()); - } + "collectionFormat", + (o, n) => LoadStyle(o, n.GetScalarValue()) }, { - "format", (o, n) => - { - GetOrCreateSchema(o).Format = n.GetScalarValue(); - } + "format", + (o, n) => GetOrCreateSchema(o).Format = n.GetScalarValue() }, { - "minimum", (o, n) => - { - GetOrCreateSchema(o).Minimum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minimum", + (o, n) => GetOrCreateSchema(o).Minimum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "maximum", (o, n) => - { - GetOrCreateSchema(o).Maximum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maximum", + (o, n) => GetOrCreateSchema(o).Maximum = decimal.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "maxLength", (o, n) => - { - GetOrCreateSchema(o).MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxLength", + (o, n) => GetOrCreateSchema(o).MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minLength", (o, n) => - { - GetOrCreateSchema(o).MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minLength", + (o, n) => GetOrCreateSchema(o).MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "readOnly", (o, n) => - { - GetOrCreateSchema(o).ReadOnly = bool.Parse(n.GetScalarValue()); - } + "readOnly", + (o, n) => GetOrCreateSchema(o).ReadOnly = bool.Parse(n.GetScalarValue()) }, { - "default", (o, n) => - { - GetOrCreateSchema(o).Default = n.CreateAny(); - } + "default", + (o, n) => GetOrCreateSchema(o).Default = n.CreateAny() }, { - "pattern", (o, n) => - { - GetOrCreateSchema(o).Pattern = n.GetScalarValue(); - } + "pattern", + (o, n) => GetOrCreateSchema(o).Pattern = n.GetScalarValue() }, { - "enum", (o, n) => - { - GetOrCreateSchema(o).Enum = n.CreateListOfAny(); - } + "enum", + (o, n) => GetOrCreateSchema(o).Enum = n.CreateListOfAny() }, { - "schema", (o, n) => - { - o.Schema = LoadSchema(n); - } + "schema", + (o, n) => o.Schema = LoadSchema(n) }, }; @@ -288,7 +250,7 @@ public static OpenApiParameter LoadParameter(ParseNode node, bool loadRequestBod node.Context.SetTempStorage("schema", null); } - bool isBodyOrFormData = (bool)node.Context.GetFromTempStorage(TempStorageKeys.ParameterIsBodyOrFormData); + var isBodyOrFormData = (bool)node.Context.GetFromTempStorage(TempStorageKeys.ParameterIsBodyOrFormData); if (isBodyOrFormData && !loadRequestBody) { return null; // Don't include Form or Body parameters when normal parameters are loaded. diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index d0dd4af8c..afafe425a 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -32,10 +32,8 @@ internal static partial class OpenApiV2Deserializer {"head", (o, n) => o.AddOperation(OperationType.Head, LoadOperation(n))}, {"patch", (o, n) => o.AddOperation(OperationType.Patch, LoadOperation(n))}, { - "parameters", (o, n) => - { - LoadPathParameters(o,n); - } + "parameters", + LoadPathParameters }, }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs index 5c6a4ebb7..2fef353ea 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs @@ -17,28 +17,20 @@ internal static partial class OpenApiV2Deserializer private static readonly FixedFieldMap _responseFixedFields = new() { { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "headers", (o, n) => - { - o.Headers = n.CreateMap(LoadHeader); - } + "headers", + (o, n) => o.Headers = n.CreateMap(LoadHeader) }, { - "examples", (o, n) => - { - LoadExamples(o, n); - } + "examples", + LoadExamples }, { - "schema", (o, n) => - { - n.Context.SetTempStorage(TempStorageKeys.ResponseSchema, LoadSchema(n), o); - } + "schema", + (o, n) => n.Context.SetTempStorage(TempStorageKeys.ResponseSchema, LoadSchema(n), o) }, }; @@ -122,9 +114,9 @@ private static void LoadExample(OpenApiResponse response, string mediaType, Pars } OpenApiMediaType mediaTypeObject; - if (response.Content.ContainsKey(mediaType)) + if (response.Content.TryGetValue(mediaType, out var value)) { - mediaTypeObject = response.Content[mediaType]; + mediaTypeObject = value; } else { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs index f1b787c2d..5fd3ba5c8 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs @@ -18,125 +18,85 @@ internal static partial class OpenApiV2Deserializer private static readonly FixedFieldMap _schemaFixedFields = new() { { - "title", (o, n) => - { - o.Title = n.GetScalarValue(); - } + "title", + (o, n) => o.Title = n.GetScalarValue() }, { - "multipleOf", (o, n) => - { - o.MultipleOf = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); - } + "multipleOf", + (o, n) => o.MultipleOf = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture) }, { - "maximum", (o, n) => - { - o.Maximum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); - } + "maximum", + (o, n) => o.Maximum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture) }, { - "exclusiveMaximum", (o, n) => - { - o.ExclusiveMaximum = bool.Parse(n.GetScalarValue()); - } + "exclusiveMaximum", + (o, n) => o.ExclusiveMaximum = bool.Parse(n.GetScalarValue()) }, { - "minimum", (o, n) => - { - o.Minimum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); - } + "minimum", + (o, n) => o.Minimum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture) }, { - "exclusiveMinimum", (o, n) => - { - o.ExclusiveMinimum = bool.Parse(n.GetScalarValue()); - } + "exclusiveMinimum", + (o, n) => o.ExclusiveMinimum = bool.Parse(n.GetScalarValue()) }, { - "maxLength", (o, n) => - { - o.MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxLength", + (o, n) => o.MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minLength", (o, n) => - { - o.MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minLength", + (o, n) => o.MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "pattern", (o, n) => - { - o.Pattern = n.GetScalarValue(); - } + "pattern", + (o, n) => o.Pattern = n.GetScalarValue() }, { - "maxItems", (o, n) => - { - o.MaxItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxItems", + (o, n) => o.MaxItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minItems", (o, n) => - { - o.MinItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minItems", + (o, n) => o.MinItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "uniqueItems", (o, n) => - { - o.UniqueItems = bool.Parse(n.GetScalarValue()); - } + "uniqueItems", + (o, n) => o.UniqueItems = bool.Parse(n.GetScalarValue()) }, { - "maxProperties", (o, n) => - { - o.MaxProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxProperties", + (o, n) => o.MaxProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minProperties", (o, n) => - { - o.MinProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minProperties", + (o, n) => o.MinProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "required", (o, n) => - { - o.Required = new HashSet(n.CreateSimpleList(n2 => n2.GetScalarValue())); - } + "required", + (o, n) => o.Required = new HashSet(n.CreateSimpleList(n2 => n2.GetScalarValue())) }, { - "enum", (o, n) => - { - o.Enum = n.CreateListOfAny(); - } + "enum", + (o, n) => o.Enum = n.CreateListOfAny() }, { - "type", (o, n) => - { - o.Type = n.GetScalarValue(); - } + "type", + (o, n) => o.Type = n.GetScalarValue() }, { - "allOf", (o, n) => - { - o.AllOf = n.CreateList(LoadSchema); - } + "allOf", + (o, n) => o.AllOf = n.CreateList(LoadSchema) }, { - "items", (o, n) => - { - o.Items = LoadSchema(n); - } + "items", + (o, n) => o.Items = LoadSchema(n) }, { - "properties", (o, n) => - { - o.Properties = n.CreateMap(LoadSchema); - } + "properties", + (o, n) => o.Properties = n.CreateMap(LoadSchema) }, { "additionalProperties", (o, n) => @@ -152,22 +112,16 @@ internal static partial class OpenApiV2Deserializer } }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "format", (o, n) => - { - o.Format = n.GetScalarValue(); - } + "format", + (o, n) => o.Format = n.GetScalarValue() }, { - "default", (o, n) => - { - o.Default = n.CreateAny(); - } + "default", + (o, n) => o.Default = n.CreateAny() }, { "discriminator", (o, n) => @@ -179,28 +133,20 @@ internal static partial class OpenApiV2Deserializer } }, { - "readOnly", (o, n) => - { - o.ReadOnly = bool.Parse(n.GetScalarValue()); - } + "readOnly", + (o, n) => o.ReadOnly = bool.Parse(n.GetScalarValue()) }, { - "xml", (o, n) => - { - o.Xml = LoadXml(n); - } + "xml", + (o, n) => o.Xml = LoadXml(n) }, { - "externalDocs", (o, n) => - { - o.ExternalDocs = LoadExternalDocs(n); - } + "externalDocs", + (o, n) => o.ExternalDocs = LoadExternalDocs(n) }, { - "example", (o, n) => - { - o.Example = n.CreateAny(); - } + "example", + (o, n) => o.Example = n.CreateAny() }, }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs index 3cb9efe52..87086690f 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs @@ -47,30 +47,18 @@ internal static partial class OpenApiV2Deserializer {"name", (o, n) => o.Name = n.GetScalarValue()}, {"in", (o, n) => o.In = n.GetScalarValue().GetEnumFromDisplayName()}, { - "flow", (o, n) => - { - _flowValue = n.GetScalarValue(); - } + "flow", (_, n) => _flowValue = n.GetScalarValue() }, { "authorizationUrl", - (o, n) => - { - _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + (_, n) => _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { "tokenUrl", - (o, n) => - { - _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + (_, n) => _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "scopes", (o, n) => - { - _flow.Scopes = n.CreateSimpleMap(LoadString); - } + "scopes", (_, n) => _flow.Scopes = n.CreateSimpleMap(LoadString) } }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs index 6bdd60692..388b4fdb5 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs @@ -16,22 +16,16 @@ internal static partial class OpenApiV2Deserializer private static readonly FixedFieldMap _tagFixedFields = new() { { - OpenApiConstants.Name, (o, n) => - { - o.Name = n.GetScalarValue(); - } + OpenApiConstants.Name, + (o, n) => o.Name = n.GetScalarValue() }, { - OpenApiConstants.Description, (o, n) => - { - o.Description = n.GetScalarValue(); - } + OpenApiConstants.Description, + (o, n) => o.Description = n.GetScalarValue() }, { - OpenApiConstants.ExternalDocs, (o, n) => - { - o.ExternalDocs = LoadExternalDocs(n); - } + OpenApiConstants.ExternalDocs, + (o, n) => o.ExternalDocs = LoadExternalDocs(n) } }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index 2ddf6321c..86a7e2393 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -177,7 +177,7 @@ public OpenApiReference ConvertToOpenApiReference(string reference, ReferenceTyp } // Where fragments point into a non-OpenAPI document, the id will be the complete fragment identifier - string id = segments[1]; + var id = segments[1]; // $ref: externalSource.yaml#/Pet if (id.StartsWith("/definitions/")) { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs index 3be5bfe7b..d11a51d65 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs @@ -18,10 +18,8 @@ internal static partial class OpenApiV2Deserializer private static readonly FixedFieldMap _xmlFixedFields = new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { "namespace", (o, n) => @@ -37,22 +35,16 @@ internal static partial class OpenApiV2Deserializer } }, { - "prefix", (o, n) => - { - o.Prefix = n.GetScalarValue(); - } + "prefix", + (o, n) => o.Prefix = n.GetScalarValue() }, { - "attribute", (o, n) => - { - o.Attribute = bool.Parse(n.GetScalarValue()); - } + "attribute", + (o, n) => o.Attribute = bool.Parse(n.GetScalarValue()) }, { - "wrapped", (o, n) => - { - o.Wrapped = bool.Parse(n.GetScalarValue()); - } + "wrapped", + (o, n) => o.Wrapped = bool.Parse(n.GetScalarValue()) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs index 7d9f469f8..cd38440fa 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs @@ -17,22 +17,16 @@ internal static partial class OpenApiV3Deserializer private static FixedFieldMap _contactFixedFields = new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { - "email", (o, n) => - { - o.Email = n.GetScalarValue(); - } + "email", + (o, n) => o.Email = n.GetScalarValue() }, { - "url", (o, n) => - { - o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "url", + (o, n) => o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs index 93258cffe..0c3df1536 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs @@ -16,16 +16,12 @@ internal static partial class OpenApiV3Deserializer new() { { - "propertyName", (o, n) => - { - o.PropertyName = n.GetScalarValue(); - } + "propertyName", + (o, n) => o.PropertyName = n.GetScalarValue() }, { - "mapping", (o, n) => - { - o.Mapping = n.CreateSimpleMap(LoadString); - } + "mapping", + (o, n) => o.Mapping = n.CreateSimpleMap(LoadString) } }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs index a4d16a429..edeca23ad 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs @@ -16,7 +16,7 @@ internal static partial class OpenApiV3Deserializer private static FixedFieldMap _openApiFixedFields = new() { { - "openapi", (o, n) => + "openapi", (_, _) => { } /* Version is valid field but we already parsed it */ }, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs index 6a275ff00..c627ea8f5 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs @@ -16,34 +16,24 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _encodingFixedFields = new() { { - "contentType", (o, n) => - { - o.ContentType = n.GetScalarValue(); - } + "contentType", + (o, n) => o.ContentType = n.GetScalarValue() }, { - "headers", (o, n) => - { - o.Headers = n.CreateMap(LoadHeader); - } + "headers", + (o, n) => o.Headers = n.CreateMap(LoadHeader) }, { - "style", (o, n) => - { - o.Style = n.GetScalarValue().GetEnumFromDisplayName(); - } + "style", + (o, n) => o.Style = n.GetScalarValue().GetEnumFromDisplayName() }, { - "explode", (o, n) => - { - o.Explode = bool.Parse(n.GetScalarValue()); - } + "explode", + (o, n) => o.Explode = bool.Parse(n.GetScalarValue()) }, { - "allowedReserved", (o, n) => - { - o.AllowReserved = bool.Parse(n.GetScalarValue()); - } + "allowedReserved", + (o, n) => o.AllowReserved = bool.Parse(n.GetScalarValue()) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs index ea7e44aed..0399ad84d 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs @@ -16,28 +16,20 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _exampleFixedFields = new() { { - "summary", (o, n) => - { - o.Summary = n.GetScalarValue(); - } + "summary", + (o, n) => o.Summary = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "value", (o, n) => - { - o.Value = n.CreateAny(); - } + "value", + (o, n) => o.Value = n.CreateAny() }, { - "externalValue", (o, n) => - { - o.ExternalValue = n.GetScalarValue(); - } + "externalValue", + (o, n) => o.ExternalValue = n.GetScalarValue() }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs index f742fb1de..e516bcfbc 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs @@ -19,16 +19,12 @@ internal static partial class OpenApiV3Deserializer { // $ref { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "url", (o, n) => - { - o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "url", + (o, n) => o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs index 4b296c046..cd74df4b4 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs @@ -16,64 +16,44 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _headerFixedFields = new() { { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "required", (o, n) => - { - o.Required = bool.Parse(n.GetScalarValue()); - } + "required", + (o, n) => o.Required = bool.Parse(n.GetScalarValue()) }, { - "deprecated", (o, n) => - { - o.Deprecated = bool.Parse(n.GetScalarValue()); - } + "deprecated", + (o, n) => o.Deprecated = bool.Parse(n.GetScalarValue()) }, { - "allowEmptyValue", (o, n) => - { - o.AllowEmptyValue = bool.Parse(n.GetScalarValue()); - } + "allowEmptyValue", + (o, n) => o.AllowEmptyValue = bool.Parse(n.GetScalarValue()) }, { - "allowReserved", (o, n) => - { - o.AllowReserved = bool.Parse(n.GetScalarValue()); - } + "allowReserved", + (o, n) => o.AllowReserved = bool.Parse(n.GetScalarValue()) }, { - "style", (o, n) => - { - o.Style = n.GetScalarValue().GetEnumFromDisplayName(); - } + "style", + (o, n) => o.Style = n.GetScalarValue().GetEnumFromDisplayName() }, { - "explode", (o, n) => - { - o.Explode = bool.Parse(n.GetScalarValue()); - } + "explode", + (o, n) => o.Explode = bool.Parse(n.GetScalarValue()) }, { - "schema", (o, n) => - { - o.Schema = LoadSchema(n); - } + "schema", + (o, n) => o.Schema = LoadSchema(n) }, { - "examples", (o, n) => - { - o.Examples = n.CreateMap(LoadExample); - } + "examples", + (o, n) => o.Examples = n.CreateMap(LoadExample) }, { - "example", (o, n) => - { - o.Example = n.CreateAny(); - } + "example", + (o, n) => o.Example = n.CreateAny() }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs index 11fb88034..042bb5a5e 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs @@ -18,40 +18,28 @@ internal static partial class OpenApiV3Deserializer public static FixedFieldMap InfoFixedFields = new() { { - "title", (o, n) => - { - o.Title = n.GetScalarValue(); - } + "title", + (o, n) => o.Title = n.GetScalarValue() }, { - "version", (o, n) => - { - o.Version = n.GetScalarValue(); - } + "version", + (o, n) => o.Version = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "termsOfService", (o, n) => - { - o.TermsOfService = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "termsOfService", + (o, n) => o.TermsOfService = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "contact", (o, n) => - { - o.Contact = LoadContact(n); - } + "contact", + (o, n) => o.Contact = LoadContact(n) }, { - "license", (o, n) => - { - o.License = LoadLicense(n); - } + "license", + (o, n) => o.License = LoadLicense(n) } }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs index 1582d75b2..bde763454 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs @@ -17,16 +17,12 @@ internal static partial class OpenApiV3Deserializer private static FixedFieldMap _licenseFixedFields = new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { - "url", (o, n) => - { - o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "url", + (o, n) => o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs index 6db2a82fb..462bb875e 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs @@ -16,34 +16,24 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _linkFixedFields = new() { { - "operationRef", (o, n) => - { - o.OperationRef = n.GetScalarValue(); - } + "operationRef", + (o, n) => o.OperationRef = n.GetScalarValue() }, { - "operationId", (o, n) => - { - o.OperationId = n.GetScalarValue(); - } + "operationId", + (o, n) => o.OperationId = n.GetScalarValue() }, { - "parameters", (o, n) => - { - o.Parameters = n.CreateSimpleMap(LoadRuntimeExpressionAnyWrapper); - } + "parameters", + (o, n) => o.Parameters = n.CreateSimpleMap(LoadRuntimeExpressionAnyWrapper) }, { - "requestBody", (o, n) => - { - o.RequestBody = LoadRuntimeExpressionAnyWrapper(n); - } + "requestBody", + (o, n) => o.RequestBody = LoadRuntimeExpressionAnyWrapper(n) }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, {"server", (o, n) => o.Server = LoadServer(n)} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs index 5ae07962d..a2625f438 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs @@ -17,28 +17,20 @@ internal static partial class OpenApiV3Deserializer new() { { - OpenApiConstants.Schema, (o, n) => - { - o.Schema = LoadSchema(n); - } + OpenApiConstants.Schema, + (o, n) => o.Schema = LoadSchema(n) }, { - OpenApiConstants.Examples, (o, n) => - { - o.Examples = n.CreateMap(LoadExample); - } + OpenApiConstants.Examples, + (o, n) => o.Examples = n.CreateMap(LoadExample) }, { - OpenApiConstants.Example, (o, n) => - { - o.Example = n.CreateAny(); - } + OpenApiConstants.Example, + (o, n) => o.Example = n.CreateAny() }, { - OpenApiConstants.Encoding, (o, n) => - { - o.Encoding = n.CreateMap(LoadEncoding); - } + OpenApiConstants.Encoding, + (o, n) => o.Encoding = n.CreateMap(LoadEncoding) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs index 16fc934a9..77e19ccbc 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs @@ -18,22 +18,16 @@ internal static partial class OpenApiV3Deserializer new() { { - "authorizationUrl", (o, n) => - { - o.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "authorizationUrl", + (o, n) => o.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "tokenUrl", (o, n) => - { - o.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "tokenUrl", + (o, n) => o.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "refreshUrl", (o, n) => - { - o.RefreshUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "refreshUrl", + (o, n) => o.RefreshUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, {"scopes", (o, n) => o.Scopes = n.CreateSimpleMap(LoadString)} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs index c3ac122f1..471b3a207 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs @@ -24,70 +24,48 @@ internal static partial class OpenApiV3Deserializer valueNode.GetScalarValue())) }, { - "summary", (o, n) => - { - o.Summary = n.GetScalarValue(); - } + "summary", + (o, n) => o.Summary = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "externalDocs", (o, n) => - { - o.ExternalDocs = LoadExternalDocs(n); - } + "externalDocs", + (o, n) => o.ExternalDocs = LoadExternalDocs(n) }, { - "operationId", (o, n) => - { - o.OperationId = n.GetScalarValue(); - } + "operationId", + (o, n) => o.OperationId = n.GetScalarValue() }, { - "parameters", (o, n) => - { - o.Parameters = n.CreateList(LoadParameter); - } + "parameters", + (o, n) => o.Parameters = n.CreateList(LoadParameter) }, { - "requestBody", (o, n) => - { - o.RequestBody = LoadRequestBody(n); - } + "requestBody", + (o, n) => o.RequestBody = LoadRequestBody(n) }, { - "responses", (o, n) => - { - o.Responses = LoadResponses(n); - } + "responses", + (o, n) => o.Responses = LoadResponses(n) }, { - "callbacks", (o, n) => - { - o.Callbacks = n.CreateMap(LoadCallback); - } + "callbacks", + (o, n) => o.Callbacks = n.CreateMap(LoadCallback) }, { - "deprecated", (o, n) => - { - o.Deprecated = bool.Parse(n.GetScalarValue()); - } + "deprecated", + (o, n) => o.Deprecated = bool.Parse(n.GetScalarValue()) }, { - "security", (o, n) => - { - o.Security = n.CreateList(LoadSecurityRequirement); - } + "security", + (o, n) => o.Security = n.CreateList(LoadSecurityRequirement) }, { - "servers", (o, n) => - { - o.Servers = n.CreateList(LoadServer); - } + "servers", + (o, n) => o.Servers = n.CreateList(LoadServer) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs index c502d38b0..954cc7109 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs @@ -19,10 +19,8 @@ internal static partial class OpenApiV3Deserializer new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { "in", (o, n) => @@ -42,70 +40,48 @@ internal static partial class OpenApiV3Deserializer } }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "required", (o, n) => - { - o.Required = bool.Parse(n.GetScalarValue()); - } + "required", + (o, n) => o.Required = bool.Parse(n.GetScalarValue()) }, { - "deprecated", (o, n) => - { - o.Deprecated = bool.Parse(n.GetScalarValue()); - } + "deprecated", + (o, n) => o.Deprecated = bool.Parse(n.GetScalarValue()) }, { - "allowEmptyValue", (o, n) => - { - o.AllowEmptyValue = bool.Parse(n.GetScalarValue()); - } + "allowEmptyValue", + (o, n) => o.AllowEmptyValue = bool.Parse(n.GetScalarValue()) }, { - "allowReserved", (o, n) => - { - o.AllowReserved = bool.Parse(n.GetScalarValue()); - } + "allowReserved", + (o, n) => o.AllowReserved = bool.Parse(n.GetScalarValue()) }, { - "style", (o, n) => - { - o.Style = n.GetScalarValue().GetEnumFromDisplayName(); - } + "style", + (o, n) => o.Style = n.GetScalarValue().GetEnumFromDisplayName() }, { - "explode", (o, n) => - { - o.Explode = bool.Parse(n.GetScalarValue()); - } + "explode", + (o, n) => o.Explode = bool.Parse(n.GetScalarValue()) }, { - "schema", (o, n) => - { - o.Schema = LoadSchema(n); - } + "schema", + (o, n) => o.Schema = LoadSchema(n) }, { - "content", (o, n) => - { - o.Content = n.CreateMap(LoadMediaType); - } + "content", + (o, n) => o.Content = n.CreateMap(LoadMediaType) }, { - "examples", (o, n) => - { - o.Examples = n.CreateMap(LoadExample); - } + "examples", + (o, n) => o.Examples = n.CreateMap(LoadExample) }, { - "example", (o, n) => - { - o.Example = n.CreateAny(); - } + "example", + (o, n) => o.Example = n.CreateAny() }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs index fcafcc786..f4ab2ad3b 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs @@ -22,16 +22,12 @@ internal static partial class OpenApiV3Deserializer } }, { - "summary", (o, n) => - { - o.Summary = n.GetScalarValue(); - } + "summary", + (o, n) => o.Summary = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, {"get", (o, n) => o.AddOperation(OperationType.Get, LoadOperation(n))}, {"put", (o, n) => o.AddOperation(OperationType.Put, LoadOperation(n))}, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs index d65279788..751fd1ac5 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs @@ -17,22 +17,16 @@ internal static partial class OpenApiV3Deserializer new() { { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "content", (o, n) => - { - o.Content = n.CreateMap(LoadMediaType); - } + "content", + (o, n) => o.Content = n.CreateMap(LoadMediaType) }, { - "required", (o, n) => - { - o.Required = bool.Parse(n.GetScalarValue()); - } + "required", + (o, n) => o.Required = bool.Parse(n.GetScalarValue()) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs index 64515dc3b..4fe97c7e1 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs @@ -17,28 +17,20 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _responseFixedFields = new() { { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "headers", (o, n) => - { - o.Headers = n.CreateMap(LoadHeader); - } + "headers", + (o, n) => o.Headers = n.CreateMap(LoadHeader) }, { - "content", (o, n) => - { - o.Content = n.CreateMap(LoadMediaType); - } + "content", + (o, n) => o.Content = n.CreateMap(LoadMediaType) }, { - "links", (o, n) => - { - o.Links = n.CreateMap(LoadLink); - } + "links", + (o, n) => o.Links = n.CreateMap(LoadLink) } }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs index fd375bfdf..52b79a1f9 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs @@ -18,142 +18,96 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _schemaFixedFields = new() { { - "title", (o, n) => - { - o.Title = n.GetScalarValue(); - } + "title", + (o, n) => o.Title = n.GetScalarValue() }, { - "multipleOf", (o, n) => - { - o.MultipleOf = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); - } + "multipleOf", + (o, n) => o.MultipleOf = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture) }, { - "maximum", (o, n) => - { - o.Maximum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); - } + "maximum", + (o, n) => o.Maximum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture) }, { - "exclusiveMaximum", (o, n) => - { - o.ExclusiveMaximum = bool.Parse(n.GetScalarValue()); - } + "exclusiveMaximum", + (o, n) => o.ExclusiveMaximum = bool.Parse(n.GetScalarValue()) }, { - "minimum", (o, n) => - { - o.Minimum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture); - } + "minimum", + (o, n) => o.Minimum = decimal.Parse(n.GetScalarValue(), NumberStyles.Float, CultureInfo.InvariantCulture) }, { - "exclusiveMinimum", (o, n) => - { - o.ExclusiveMinimum = bool.Parse(n.GetScalarValue()); - } + "exclusiveMinimum", + (o, n) => o.ExclusiveMinimum = bool.Parse(n.GetScalarValue()) }, { - "maxLength", (o, n) => - { - o.MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxLength", + (o, n) => o.MaxLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minLength", (o, n) => - { - o.MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minLength", + (o, n) => o.MinLength = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "pattern", (o, n) => - { - o.Pattern = n.GetScalarValue(); - } + "pattern", + (o, n) => o.Pattern = n.GetScalarValue() }, { - "maxItems", (o, n) => - { - o.MaxItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxItems", + (o, n) => o.MaxItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minItems", (o, n) => - { - o.MinItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minItems", + (o, n) => o.MinItems = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "uniqueItems", (o, n) => - { - o.UniqueItems = bool.Parse(n.GetScalarValue()); - } + "uniqueItems", + (o, n) => o.UniqueItems = bool.Parse(n.GetScalarValue()) }, { - "maxProperties", (o, n) => - { - o.MaxProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "maxProperties", + (o, n) => o.MaxProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "minProperties", (o, n) => - { - o.MinProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture); - } + "minProperties", + (o, n) => o.MinProperties = int.Parse(n.GetScalarValue(), CultureInfo.InvariantCulture) }, { - "required", (o, n) => - { - o.Required = new HashSet(n.CreateSimpleList(n2 => n2.GetScalarValue())); - } + "required", + (o, n) => o.Required = new HashSet(n.CreateSimpleList(n2 => n2.GetScalarValue())) }, { - "enum", (o, n) => - { - o.Enum = n.CreateListOfAny(); - } + "enum", + (o, n) => o.Enum = n.CreateListOfAny() }, { - "type", (o, n) => - { - o.Type = n.GetScalarValue(); - } + "type", + (o, n) => o.Type = n.GetScalarValue() }, { - "allOf", (o, n) => - { - o.AllOf = n.CreateList(LoadSchema); - } + "allOf", + (o, n) => o.AllOf = n.CreateList(LoadSchema) }, { - "oneOf", (o, n) => - { - o.OneOf = n.CreateList(LoadSchema); - } + "oneOf", + (o, n) => o.OneOf = n.CreateList(LoadSchema) }, { - "anyOf", (o, n) => - { - o.AnyOf = n.CreateList(LoadSchema); - } + "anyOf", + (o, n) => o.AnyOf = n.CreateList(LoadSchema) }, { - "not", (o, n) => - { - o.Not = LoadSchema(n); - } + "not", + (o, n) => o.Not = LoadSchema(n) }, { - "items", (o, n) => - { - o.Items = LoadSchema(n); - } + "items", + (o, n) => o.Items = LoadSchema(n) }, { - "properties", (o, n) => - { - o.Properties = n.CreateMap(LoadSchema); - } + "properties", + (o, n) => o.Properties = n.CreateMap(LoadSchema) }, { "additionalProperties", (o, n) => @@ -169,71 +123,48 @@ internal static partial class OpenApiV3Deserializer } }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "format", (o, n) => - { - o.Format = n.GetScalarValue(); - } + "format", + (o, n) => o.Format = n.GetScalarValue() }, { - "default", (o, n) => - { - o.Default = n.CreateAny(); - } + "default", + (o, n) => o.Default = n.CreateAny() }, - { - "nullable", (o, n) => - { - o.Nullable = bool.Parse(n.GetScalarValue()); - } + "nullable", + (o, n) => o.Nullable = bool.Parse(n.GetScalarValue()) }, { - "discriminator", (o, n) => - { - o.Discriminator = LoadDiscriminator(n); - } + "discriminator", + (o, n) => o.Discriminator = LoadDiscriminator(n) }, { - "readOnly", (o, n) => - { - o.ReadOnly = bool.Parse(n.GetScalarValue()); - } + "readOnly", + (o, n) => o.ReadOnly = bool.Parse(n.GetScalarValue()) }, { - "writeOnly", (o, n) => - { - o.WriteOnly = bool.Parse(n.GetScalarValue()); - } + "writeOnly", + (o, n) => o.WriteOnly = bool.Parse(n.GetScalarValue()) }, { - "xml", (o, n) => - { - o.Xml = LoadXml(n); - } + "xml", + (o, n) => o.Xml = LoadXml(n) }, { - "externalDocs", (o, n) => - { - o.ExternalDocs = LoadExternalDocs(n); - } + "externalDocs", + (o, n) => o.ExternalDocs = LoadExternalDocs(n) }, { - "example", (o, n) => - { - o.Example = n.CreateAny(); - } + "example", + (o, n) => o.Example = n.CreateAny() }, { - "deprecated", (o, n) => - { - o.Deprecated = bool.Parse(n.GetScalarValue()); - } + "deprecated", + (o, n) => o.Deprecated = bool.Parse(n.GetScalarValue()) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs index e2ea91abe..c219d586f 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs @@ -18,52 +18,36 @@ internal static partial class OpenApiV3Deserializer new() { { - "type", (o, n) => - { - o.Type = n.GetScalarValue().GetEnumFromDisplayName(); - } + "type", + (o, n) => o.Type = n.GetScalarValue().GetEnumFromDisplayName() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { - "in", (o, n) => - { - o.In = n.GetScalarValue().GetEnumFromDisplayName(); - } + "in", + (o, n) => o.In = n.GetScalarValue().GetEnumFromDisplayName() }, { - "scheme", (o, n) => - { - o.Scheme = n.GetScalarValue(); - } + "scheme", + (o, n) => o.Scheme = n.GetScalarValue() }, { - "bearerFormat", (o, n) => - { - o.BearerFormat = n.GetScalarValue(); - } + "bearerFormat", + (o, n) => o.BearerFormat = n.GetScalarValue() }, { - "openIdConnectUrl", (o, n) => - { - o.OpenIdConnectUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + "openIdConnectUrl", + (o, n) => o.OpenIdConnectUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "flows", (o, n) => - { - o.Flows = LoadOAuthFlows(n); - } + "flows", + (o, n) => o.Flows = LoadOAuthFlows(n) } }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs index b29c3b0bf..cfdb5d3ae 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs @@ -16,22 +16,16 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _serverFixedFields = new() { { - "url", (o, n) => - { - o.Url = n.GetScalarValue(); - } + "url", + (o, n) => o.Url = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, { - "variables", (o, n) => - { - o.Variables = n.CreateMap(LoadServerVariable); - } + "variables", + (o, n) => o.Variables = n.CreateMap(LoadServerVariable) } }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs index c506930d3..e65222dde 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs @@ -17,22 +17,16 @@ internal static partial class OpenApiV3Deserializer new() { { - "enum", (o, n) => - { - o.Enum = n.CreateSimpleList(s => s.GetScalarValue()); - } + "enum", + (o, n) => o.Enum = n.CreateSimpleList(s => s.GetScalarValue()) }, { - "default", (o, n) => - { - o.Default = n.GetScalarValue(); - } + "default", + (o, n) => o.Default = n.GetScalarValue() }, { - "description", (o, n) => - { - o.Description = n.GetScalarValue(); - } + "description", + (o, n) => o.Description = n.GetScalarValue() }, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs index b78cdfc60..441ab330e 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs @@ -16,22 +16,16 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _tagFixedFields = new() { { - OpenApiConstants.Name, (o, n) => - { - o.Name = n.GetScalarValue(); - } + OpenApiConstants.Name, + (o, n) => o.Name = n.GetScalarValue() }, { - OpenApiConstants.Description, (o, n) => - { - o.Description = n.GetScalarValue(); - } + OpenApiConstants.Description, + (o, n) => o.Description = n.GetScalarValue() }, { - OpenApiConstants.ExternalDocs, (o, n) => - { - o.ExternalDocs = LoadExternalDocs(n); - } + OpenApiConstants.ExternalDocs, + (o, n) => o.ExternalDocs = LoadExternalDocs(n) } }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 73fedb662..96cf563f2 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -110,7 +110,7 @@ public OpenApiReference ConvertToOpenApiReference( } } // Where fragments point into a non-OpenAPI document, the id will be the complete fragment identifier - string id = segments[1]; + var id = segments[1]; var openApiReference = new OpenApiReference(); // $ref: externalSource.yaml#/Pet diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs index 866f38d01..b88aaade9 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs @@ -17,34 +17,24 @@ internal static partial class OpenApiV3Deserializer private static readonly FixedFieldMap _xmlFixedFields = new() { { - "name", (o, n) => - { - o.Name = n.GetScalarValue(); - } + "name", + (o, n) => o.Name = n.GetScalarValue() }, { - "namespace", (o, n) => - { - o.Namespace = new(n.GetScalarValue(), UriKind.Absolute); - } + "namespace", + (o, n) => o.Namespace = new(n.GetScalarValue(), UriKind.Absolute) }, { - "prefix", (o, n) => - { - o.Prefix = n.GetScalarValue(); - } + "prefix", + (o, n) => o.Prefix = n.GetScalarValue() }, { - "attribute", (o, n) => - { - o.Attribute = bool.Parse(n.GetScalarValue()); - } + "attribute", + (o, n) => o.Attribute = bool.Parse(n.GetScalarValue()) }, { - "wrapped", (o, n) => - { - o.Wrapped = bool.Parse(n.GetScalarValue()); - } + "wrapped", + (o, n) => o.Wrapped = bool.Parse(n.GetScalarValue()) }, }; diff --git a/src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs b/src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs index d1f8bd798..907870ed2 100644 --- a/src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs +++ b/src/Microsoft.OpenApi.Workbench/EnumBindingSourceExtension.cs @@ -16,7 +16,7 @@ public Type EnumType { if (null != value) { - Type enumType = Nullable.GetUnderlyingType(value) ?? value; + var enumType = Nullable.GetUnderlyingType(value) ?? value; if (!enumType.IsEnum) throw new ArgumentException("Type must be for an Enum."); } @@ -38,13 +38,13 @@ public override object ProvideValue(IServiceProvider serviceProvider) if (null == this._enumType) throw new InvalidOperationException("The EnumType must be specified."); - Type actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType; - Array enumValues = Enum.GetValues(actualEnumType); + var actualEnumType = Nullable.GetUnderlyingType(this._enumType) ?? this._enumType; + var enumValues = Enum.GetValues(actualEnumType); if (actualEnumType == this._enumType) return enumValues; - Array tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1); + var tempArray = Array.CreateInstance(actualEnumType, enumValues.Length + 1); enumValues.CopyTo(tempArray, 1); return tempArray; } diff --git a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs index 4a67e074e..b0e553f71 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiAnyCloneHelper.cs @@ -20,9 +20,9 @@ public static IOpenApiAny CloneFromCopyConstructor(IOpenApiAny obj) if (obj != null) { var t = obj.GetType(); - foreach (ConstructorInfo ci in t.GetConstructors()) + foreach (var ci in t.GetConstructors()) { - ParameterInfo[] pi = ci.GetParameters(); + var pi = ci.GetParameters(); if (pi.Length == 1 && pi[0].ParameterType == t) { return (IOpenApiAny)ci.Invoke(new object[] { obj }); diff --git a/src/Microsoft.OpenApi/Any/OpenApiByte.cs b/src/Microsoft.OpenApi/Any/OpenApiByte.cs index 88b0e178c..f28a50175 100644 --- a/src/Microsoft.OpenApi/Any/OpenApiByte.cs +++ b/src/Microsoft.OpenApi/Any/OpenApiByte.cs @@ -12,7 +12,7 @@ public class OpenApiByte : OpenApiPrimitive /// Initializes the class. /// public OpenApiByte(byte value) - : this(new byte[] { value }) + : this(new[] { value }) { } diff --git a/src/Microsoft.OpenApi/Expressions/BodyExpression.cs b/src/Microsoft.OpenApi/Expressions/BodyExpression.cs index c09e06d4d..c63b1bc58 100644 --- a/src/Microsoft.OpenApi/Expressions/BodyExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/BodyExpression.cs @@ -55,12 +55,6 @@ public override string Expression /// /// Gets the fragment string. /// - public string Fragment - { - get - { - return Value; - } - } + public string Fragment { get => Value; } } } diff --git a/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs b/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs index e5f92bed3..99bbf2a96 100644 --- a/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs @@ -26,23 +26,11 @@ public HeaderExpression(string token) /// /// Gets the expression string. /// - public override string Expression - { - get - { - return Header + Value; - } - } + public override string Expression { get => Header + Value; } /// /// Gets the token string. /// - public string Token - { - get - { - return Value; - } - } + public string Token { get => Value; } } } diff --git a/src/Microsoft.OpenApi/Expressions/PathExpression.cs b/src/Microsoft.OpenApi/Expressions/PathExpression.cs index b9c1cc618..1d43b9b21 100644 --- a/src/Microsoft.OpenApi/Expressions/PathExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/PathExpression.cs @@ -26,23 +26,11 @@ public PathExpression(string name) /// /// Gets the expression string. /// - public override string Expression - { - get - { - return Path + Value; - } - } + public override string Expression { get => Path + Value; } /// /// Gets the name string. /// - public string Name - { - get - { - return Value; - } - } + public string Name { get => Value; } } } diff --git a/src/Microsoft.OpenApi/Expressions/QueryExpression.cs b/src/Microsoft.OpenApi/Expressions/QueryExpression.cs index 322c34de1..55016d82a 100644 --- a/src/Microsoft.OpenApi/Expressions/QueryExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/QueryExpression.cs @@ -26,23 +26,11 @@ public QueryExpression(string name) /// /// Gets the expression string. /// - public override string Expression - { - get - { - return Query + Value; - } - } + public override string Expression { get => Query + Value; } /// /// Gets the name string. /// - public string Name - { - get - { - return Value; - } - } + public string Name { get => Value; } } } diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs index 25d8b630e..845f6ce65 100755 --- a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs @@ -98,7 +98,6 @@ public static void Serialize( /// The Open API element. /// The output writer. /// Version of the specification the output should conform to - public static void Serialize(this T element, IOpenApiWriter writer, OpenApiSpecVersion specVersion) where T : IOpenApiSerializable { diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 31b7282f3..5a52c9584 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -101,7 +101,7 @@ public void SerializeAsV3(IOpenApiWriter writer) { var loops = writer.GetSettings().LoopDetector.Loops; writer.WriteStartObject(); - if (loops.TryGetValue(typeof(OpenApiSchema), out List schemas)) + if (loops.TryGetValue(typeof(OpenApiSchema), out var schemas)) { var openApiSchemas = schemas.Cast().Distinct().ToList() .ToDictionary(k => k.Reference.Id); @@ -109,9 +109,7 @@ public void SerializeAsV3(IOpenApiWriter writer) writer.WriteOptionalMap( OpenApiConstants.Schemas, Schemas, - (w, key, component) => { - component.SerializeAsV3WithoutReference(w); - }); + (w, _, component) => component.SerializeAsV3WithoutReference(w)); } writer.WriteEndObject(); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index a53f6ee1b..365b96807 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -68,8 +68,6 @@ public void SerializeAsV2(IOpenApiWriter writer) private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - Utils.CheckArgumentNull(writer); - writer.WriteStartObject(); // name diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index c2fa42890..77ccef663 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -160,7 +160,7 @@ public void SerializeAsV2(IOpenApiWriter writer) { var loops = writer.GetSettings().LoopDetector.Loops; - if (loops.TryGetValue(typeof(OpenApiSchema), out List schemas)) + if (loops.TryGetValue(typeof(OpenApiSchema), out var schemas)) { var openApiSchemas = schemas.Cast().Distinct().ToList() .ToDictionary(k => k.Reference.Id); @@ -173,10 +173,7 @@ public void SerializeAsV2(IOpenApiWriter writer) writer.WriteOptionalMap( OpenApiConstants.Definitions, openApiSchemas, - (w, key, component) => - { - component.SerializeAsV2WithoutReference(w); - }); + (w, _, component) => component.SerializeAsV2WithoutReference(w)); } } else @@ -425,8 +422,8 @@ private static string ConvertByteArrayToString(byte[] hash) { // Build the final string by converting each byte // into hex and appending it to a StringBuilder - StringBuilder sb = new StringBuilder(); - for (int i = 0; i < hash.Length; i++) + var sb = new StringBuilder(); + for (var i = 0; i < hash.Length; i++) { sb.Append(hash[i].ToString("X2")); } diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index c591ee5b3..5720570fa 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -61,8 +61,6 @@ public void SerializeAsV2(IOpenApiWriter writer) private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - Utils.CheckArgumentNull(writer); - writer.WriteStartObject(); // description diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index a05c915d5..c629224f8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -61,8 +61,6 @@ public void SerializeAsV2(IOpenApiWriter writer) private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - Utils.CheckArgumentNull(writer); - writer.WriteStartObject(); // name diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index fb406473d..b7bdeb3f8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -147,6 +147,9 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) // server writer.WriteOptionalObject(OpenApiConstants.Server, Server, (w, s) => s.SerializeAsV3(w)); + // specification extensions + writer.WriteExtensions(Extensions, OpenApiSpecVersion.OpenApi3_0); + writer.WriteEndObject(); } diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index cdf18cddb..11171a7ae 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -143,10 +143,7 @@ public void SerializeAsV3(IOpenApiWriter writer) writer.WriteOptionalCollection( OpenApiConstants.Tags, Tags, - (w, t) => - { - t.SerializeAsV3(w); - }); + (w, t) => t.SerializeAsV3(w)); // summary writer.WriteProperty(OpenApiConstants.Summary, Summary); @@ -200,10 +197,7 @@ public void SerializeAsV2(IOpenApiWriter writer) writer.WriteOptionalCollection( OpenApiConstants.Tags, Tags, - (w, t) => - { - t.SerializeAsV2(w); - }); + (w, t) => t.SerializeAsV2(w)); // summary writer.WriteProperty(OpenApiConstants.Summary, Summary); diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index ccd8a0034..fd38927b6 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -493,8 +493,6 @@ internal void SerializeAsV2( ISet parentRequiredProperties, string propertyName) { - Utils.CheckArgumentNull(writer); - var settings = writer.GetSettings(); var target = this; @@ -554,8 +552,6 @@ internal void SerializeAsV2WithoutReference( internal void WriteAsItemsProperties(IOpenApiWriter writer) { - Utils.CheckArgumentNull(writer); - // type writer.WriteProperty(OpenApiConstants.Type, Type); @@ -625,8 +621,6 @@ internal void WriteAsSchemaProperties( ISet parentRequiredProperties, string propertyName) { - Utils.CheckArgumentNull(writer); - // format if (string.IsNullOrEmpty(Format)) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index 1b1abcdf7..ff1d196d4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -81,8 +81,6 @@ public void SerializeAsV2(IOpenApiWriter writer) private void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - Utils.CheckArgumentNull(writer); - writer.WriteStartObject(); // name diff --git a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs index 94bd995c4..fa1b9911e 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs @@ -304,12 +304,12 @@ private static void ValidateFilters(IDictionary> requestUrl { if (operationIds == "*") { - return (url, operationType, operation) => true; // All operations + return (_, _, _) => true; // All operations } else { var operationIdsArray = operationIds.Split(','); - return (url, operationType, operation) => operationIdsArray.Contains(operation.OperationId); + return (_, _, operation) => operationIdsArray.Contains(operation.OperationId); } } @@ -319,11 +319,11 @@ private static void ValidateFilters(IDictionary> requestUrl if (tagsArray.Length == 1) { var regex = new Regex(tagsArray[0]); - return (url, operationType, operation) => operation.Tags.Any(tag => regex.IsMatch(tag.Name)); + return (_, _, operation) => operation.Tags.Any(tag => regex.IsMatch(tag.Name)); } else { - return (url, operationType, operation) => operation.Tags.Any(tag => tagsArray.Contains(tag.Name)); + return (_, _, operation) => operation.Tags.Any(tag => tagsArray.Contains(tag.Name)); } } @@ -357,7 +357,7 @@ private static void ValidateFilters(IDictionary> requestUrl } // predicate for matching url and operationTypes - return (path, operationType, operation) => operationTypes.Contains(operationType + path); + return (path, operationType, _) => operationTypes.Contains(operationType + path); } private static List GetOperationTypes(IDictionary openApiOperations, List url, string path) diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index 19e463e36..671157eeb 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -196,7 +196,7 @@ public override void Visit(OpenApiSchema schema) /// private void ResolveTags(IList tags) { - for (int i = 0; i < tags.Count; i++) + for (var i = 0; i < tags.Count; i++) { var tag = tags[i]; if (IsUnresolvedReference(tag)) @@ -229,7 +229,7 @@ private void ResolveTags(IList tags) { if (list == null) return; - for (int i = 0; i < list.Count; i++) + for (var i = 0; i < list.Count; i++) { var entity = list[i]; if (IsUnresolvedReference(entity)) diff --git a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs index 52f2207ed..d0e662453 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs @@ -41,13 +41,7 @@ public virtual void Exit() /// /// Pointer to source of validation error in document /// - public string PathString - { - get - { - return "#/" + String.Join("/", _path.Reverse()); - } - } + public string PathString { get => "#/" + String.Join("/", _path.Reverse()); } /// /// Visits diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index 4811f647c..a0d28d7af 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -68,7 +68,7 @@ internal void Walk(IList tags) // Visit tags if (tags != null) { - for (int i = 0; i < tags.Count; i++) + for (var i = 0; i < tags.Count; i++) { Walk(i.ToString(), () => Walk(tags[i])); } @@ -246,7 +246,7 @@ internal void Walk(IList servers) // Visit Servers if (servers != null) { - for (int i = 0; i < servers.Count; i++) + for (var i = 0; i < servers.Count; i++) { Walk(i.ToString(), () => Walk(servers[i])); } @@ -515,7 +515,7 @@ internal void Walk(IList securityRequirements) if (securityRequirements != null) { - for (int i = 0; i < securityRequirements.Count; i++) + for (var i = 0; i < securityRequirements.Count; i++) { Walk(i.ToString(), () => Walk(securityRequirements[i])); } @@ -536,7 +536,7 @@ internal void Walk(IList parameters) if (parameters != null) { - for (int i = 0; i < parameters.Count; i++) + for (var i = 0; i < parameters.Count; i++) { Walk(i.ToString(), () => Walk(parameters[i])); } @@ -614,12 +614,9 @@ internal void Walk(OpenApiRequestBody requestBody, bool isComponent = false) _visitor.Visit(requestBody); - if (requestBody != null) + if (requestBody is {Content: not null}) { - if (requestBody.Content != null) - { - Walk(OpenApiConstants.Content, () => Walk(requestBody.Content)); - } + Walk(OpenApiConstants.Content, () => Walk(requestBody.Content)); } Walk(requestBody as IOpenApiExtensible); } @@ -776,6 +773,11 @@ internal void Walk(OpenApiSchema schema, bool isComponent = false) Walk("items", () => Walk(schema.Items)); } + if (schema.Not != null) + { + Walk("not", () => Walk(schema.Not)); + } + if (schema.AllOf != null) { Walk("allOf", () => Walk(schema.AllOf)); @@ -879,7 +881,7 @@ internal void Walk(IList examples) // Visit Examples if (examples != null) { - for (int i = 0; i < examples.Count; i++) + for (var i = 0; i < examples.Count; i++) { Walk(i.ToString(), () => Walk(examples[i])); } @@ -899,7 +901,7 @@ internal void Walk(IList schemas) // Visit Schemas if (schemas != null) { - for (int i = 0; i < schemas.Count; i++) + for (var i = 0; i < schemas.Count; i++) { Walk(i.ToString(), () => Walk(schemas[i])); } diff --git a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs index eda6e1a1d..c275458a5 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -72,7 +72,7 @@ public OpenApiWorkspace(OpenApiWorkspace workspace){} /// Returns true if a matching document is found. public bool Contains(string location) { - Uri key = ToLocationUrl(location); + var key = ToLocationUrl(location); return _documents.ContainsKey(key) || _fragments.ContainsKey(key) || _artifacts.ContainsKey(key); } diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index ae2c52721..f8061db64 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -30,24 +30,12 @@ public OpenApiValidator(ValidationRuleSet ruleSet) /// /// Gets the validation errors. /// - public IEnumerable Errors - { - get - { - return _errors; - } - } + public IEnumerable Errors { get => _errors; } /// /// Gets the validation warnings. /// - public IEnumerable Warnings - { - get - { - return _warnings; - } - } + public IEnumerable Warnings { get => _warnings; } /// /// Register an error with the validation context. diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index 493341acf..a936766c8 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -45,7 +45,7 @@ public static class OpenApiSchemaRules if (schema.Enum != null) { - for (int i = 0; i < schema.Enum.Count; i++) + for (var i = 0; i < schema.Enum.Count; i++) { context.Enter(i.ToString()); RuleHelpers.ValidateDataTypeMismatch(context, nameof(SchemaMismatchedDataType), schema.Enum[i], schema); diff --git a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs index e777d0b04..4fdc6d2cf 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs @@ -87,9 +87,10 @@ public static void ValidateDataTypeMismatch( { context.Enter(key); - if (schema.Properties != null && schema.Properties.ContainsKey(key)) + if (schema.Properties != null && + schema.Properties.TryGetValue(key, out var property)) { - ValidateDataTypeMismatch(context, ruleName, anyObject[key], schema.Properties[key]); + ValidateDataTypeMismatch(context, ruleName, anyObject[key], property); } else { @@ -121,7 +122,7 @@ public static void ValidateDataTypeMismatch( return; } - for (int i = 0; i < anyArray.Count; i++) + for (var i = 0; i < anyArray.Count; i++) { context.Enter(i.ToString()); diff --git a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs index c1cf0a569..3f01ef549 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationExtensions.cs @@ -13,7 +13,7 @@ public static class ValidationContextExtensions /// public static void CreateError(this IValidationContext context, string ruleName, string message) { - OpenApiValidatorError error = new OpenApiValidatorError(ruleName, context.PathString, message); + var error = new OpenApiValidatorError(ruleName, context.PathString, message); context.AddError(error); } @@ -22,7 +22,7 @@ public static void CreateError(this IValidationContext context, string ruleName, /// public static void CreateWarning(this IValidationContext context, string ruleName, string message) { - OpenApiValidatorWarning warning = new OpenApiValidatorWarning(ruleName, context.PathString, message); + var warning = new OpenApiValidatorWarning(ruleName, context.PathString, message); context.AddWarning(warning); } } diff --git a/src/Microsoft.OpenApi/Validations/ValidationRule.cs b/src/Microsoft.OpenApi/Validations/ValidationRule.cs index 5c930de1b..48907635d 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRule.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRule.cs @@ -50,8 +50,6 @@ internal override Type ElementType internal override void Evaluate(IValidationContext context, object item) { - Utils.CheckArgumentNull(context); - if (item == null) { return; @@ -62,7 +60,7 @@ internal override void Evaluate(IValidationContext context, object item) throw new ArgumentException(string.Format(SRResource.InputItemShouldBeType, typeof(T).FullName)); } - T typedItem = (T)item; + var typedItem = (T)item; this._validate(context, typedItem); } } diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index 7c93919e4..a5c6fee83 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -83,7 +83,7 @@ public ValidationRuleSet(ValidationRuleSet ruleSet) return; } - foreach (ValidationRule rule in ruleSet) + foreach (var rule in ruleSet) { Add(rule); } @@ -100,7 +100,7 @@ public ValidationRuleSet(IEnumerable rules) return; } - foreach (ValidationRule rule in rules) + foreach (var rule in rules) { Add(rule); } @@ -111,10 +111,7 @@ public ValidationRuleSet(IEnumerable rules) /// public IList Rules { - get - { - return _rules.Values.SelectMany(v => v).ToList(); - } + get => _rules.Values.SelectMany(v => v).ToList(); } /// @@ -163,10 +160,10 @@ IEnumerator IEnumerable.GetEnumerator() private static ValidationRuleSet BuildDefaultRuleSet() { - ValidationRuleSet ruleSet = new ValidationRuleSet(); - Type validationRuleType = typeof(ValidationRule); + var ruleSet = new ValidationRuleSet(); + var validationRuleType = typeof(ValidationRule); - IEnumerable rules = typeof(ValidationRuleSet).Assembly.GetTypes() + var rules = typeof(ValidationRuleSet).Assembly.GetTypes() .Where(t => t.IsClass && t != typeof(object) && t.GetCustomAttributes(typeof(OpenApiRuleAttribute), false).Any()) diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs index 05b6771ec..6aa449901 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs @@ -73,9 +73,6 @@ public static void WriteAny(this IOpenApiWriter writer, T any) where T : IOpe private static void WriteArray(this IOpenApiWriter writer, OpenApiArray array) { - Utils.CheckArgumentNull(writer); - Utils.CheckArgumentNull(array); - writer.WriteStartArray(); foreach (var item in array) @@ -88,9 +85,6 @@ private static void WriteArray(this IOpenApiWriter writer, OpenApiArray array) private static void WriteObject(this IOpenApiWriter writer, OpenApiObject entity) { - Utils.CheckArgumentNull(writer); - Utils.CheckArgumentNull(entity); - writer.WriteStartObject(); foreach (var item in entity) @@ -104,9 +98,6 @@ private static void WriteObject(this IOpenApiWriter writer, OpenApiObject entity private static void WritePrimitive(this IOpenApiWriter writer, IOpenApiPrimitive primitive) { - Utils.CheckArgumentNull(writer); - Utils.CheckArgumentNull(primitive); - // The Spec version is meaning for the Any type, so it's ok to use the latest one. primitive.Write(writer, OpenApiSpecVersion.OpenApi3_0); } diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs index 7c532da5b..7b85dd680 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -367,7 +367,7 @@ private static void WriteMapInternal( IDictionary elements, Action action) { - WriteMapInternal(writer, name, elements, (w, k, s) => action(w, s)); + WriteMapInternal(writer, name, elements, (w, _, s) => action(w, s)); } private static void WriteMapInternal( diff --git a/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs index be8794941..20ed519ff 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs @@ -200,7 +200,7 @@ public override void WriteValue(string value) using (var reader = new StringReader(value)) { - bool firstLine = true; + var firstLine = true; while (reader.ReadLine() is var line && line != null) { if (firstLine) diff --git a/src/Microsoft.OpenApi/Writers/Scope.cs b/src/Microsoft.OpenApi/Writers/Scope.cs index 3bfdb5ef8..9afb46090 100644 --- a/src/Microsoft.OpenApi/Writers/Scope.cs +++ b/src/Microsoft.OpenApi/Writers/Scope.cs @@ -46,13 +46,7 @@ public Scope(ScopeType type) /// /// Gets the scope type for this scope. /// - public ScopeType Type - { - get - { - return _type; - } - } + public ScopeType Type { get => _type; } /// /// Get/Set the whether it is in previous array scope. diff --git a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs index 02d30ec08..708aa7237 100644 --- a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -14,34 +15,34 @@ public static class SpecialCharacterStringExtensions { // Plain style strings cannot start with indicators. // http://www.yaml.org/spec/1.2/spec.html#indicator// - private static readonly char[] _yamlIndicators = + private static readonly HashSet _yamlIndicators = new() { - '-', - '?', - ':', - ',', - '{', - '}', - '[', - ']', - '&', - '*', - '#', - '?', - '|', - '-', - '>', - '!', - '%', - '@', - '`', - '\'', - '"', + "-", + "?", + ":", + ",", + "{", + "}", + "[", + "]", + "&", + "*", + "#", + "?", + "|", + "-", + ">", + "!", + "%", + "@", + "`", + "'", + "\"" }; // Plain style strings cannot contain these character combinations. // http://www.yaml.org/spec/1.2/spec.html#style/flow/plain - private static readonly string[] _yamlPlainStringForbiddenCombinations = + private static readonly HashSet _yamlPlainStringForbiddenCombinations = new() { ": ", " #", @@ -57,48 +58,51 @@ public static class SpecialCharacterStringExtensions // Plain style strings cannot end with these characters. // http://www.yaml.org/spec/1.2/spec.html#style/flow/plain - private static readonly string[] _yamlPlainStringForbiddenTerminals = + private static readonly HashSet _yamlPlainStringForbiddenTerminals = new() { ":" }; // Double-quoted strings are needed for these non-printable control characters. // http://www.yaml.org/spec/1.2/spec.html#style/flow/double-quoted - private static readonly char[] _yamlControlCharacters = + private static readonly Dictionary _yamlControlCharacterCharReplacements = new() { - '\0', - '\x01', - '\x02', - '\x03', - '\x04', - '\x05', - '\x06', - '\a', - '\b', - '\t', - '\n', - '\v', - '\f', - '\r', - '\x0e', - '\x0f', - '\x10', - '\x11', - '\x12', - '\x13', - '\x14', - '\x15', - '\x16', - '\x17', - '\x18', - '\x19', - '\x1a', - '\x1b', - '\x1c', - '\x1d', - '\x1e', - '\x1f' + {'\0', "\\0"}, + {'\x01', "\\x01"}, + {'\x02', "\\x02"}, + {'\x03', "\\x03"}, + {'\x04', "\\x04"}, + {'\x05', "\\x05"}, + {'\x06', "\\x06"}, + {'\a', "\\a"}, + {'\b', "\\b"}, + {'\t', "\\t"}, + {'\n', "\\n"}, + {'\v', "\\v"}, + {'\f', "\\f"}, + {'\r', "\\r"}, + {'\x0e', "\\x0e"}, + {'\x0f', "\\x0f"}, + {'\x10', "\\x10"}, + {'\x11', "\\x11"}, + {'\x12', "\\x12"}, + {'\x13', "\\x13"}, + {'\x14', "\\x14"}, + {'\x15', "\\x15"}, + {'\x16', "\\x16"}, + {'\x17', "\\x17"}, + {'\x18', "\\x18"}, + {'\x19', "\\x19"}, + {'\x1a', "\\x1a"}, + {'\x1b', "\\x1b"}, + {'\x1c', "\\x1c"}, + {'\x1d', "\\x1d"}, + {'\x1e', "\\x1e"}, + {'\x1f', "\\x1f"}, }; + + private static readonly Dictionary _yamlControlCharacterStringReplacements = _yamlControlCharacterCharReplacements + .ToDictionary(x => x.Key.ToString(), x => x.Value); /// /// Escapes all special characters and put the string in quotes if necessary to @@ -106,26 +110,21 @@ public static class SpecialCharacterStringExtensions /// internal static string GetYamlCompatibleString(this string input) { - // If string is an empty string, wrap it in quote to ensure it is not recognized as null. - if (input == "") - { - return "''"; - } - - // If string is the word null, wrap it in quote to ensure it is not recognized as empty scalar null. - if (input == "null") - { - return "'null'"; - } - - // If string is the letter ~, wrap it in quote to ensure it is not recognized as empty scalar null. - if (input == "~") + switch (input) { - return "'~'"; + // If string is an empty string, wrap it in quote to ensure it is not recognized as null. + case "": + return "''"; + // If string is the word null, wrap it in quote to ensure it is not recognized as empty scalar null. + case "null": + return "'null'"; + // If string is the letter ~, wrap it in quote to ensure it is not recognized as empty scalar null. + case "~": + return "'~'"; } // If string includes a control character, wrapping in double quote is required. - if (input.Any(c => _yamlControlCharacters.Contains(c))) + if (input.Any(c => _yamlControlCharacterCharReplacements.ContainsKey(c))) { // Replace the backslash first, so that the new backslashes created by other Replaces are not duplicated. input = input.Replace("\\", "\\\\"); @@ -134,39 +133,11 @@ internal static string GetYamlCompatibleString(this string input) input = input.Replace("\"", "\\\""); // Escape all the control characters. - input = input.Replace("\0", "\\0"); - input = input.Replace("\x01", "\\x01"); - input = input.Replace("\x02", "\\x02"); - input = input.Replace("\x03", "\\x03"); - input = input.Replace("\x04", "\\x04"); - input = input.Replace("\x05", "\\x05"); - input = input.Replace("\x06", "\\x06"); - input = input.Replace("\a", "\\a"); - input = input.Replace("\b", "\\b"); - input = input.Replace("\t", "\\t"); - input = input.Replace("\n", "\\n"); - input = input.Replace("\v", "\\v"); - input = input.Replace("\f", "\\f"); - input = input.Replace("\r", "\\r"); - input = input.Replace("\x0e", "\\x0e"); - input = input.Replace("\x0f", "\\x0f"); - input = input.Replace("\x10", "\\x10"); - input = input.Replace("\x11", "\\x11"); - input = input.Replace("\x12", "\\x12"); - input = input.Replace("\x13", "\\x13"); - input = input.Replace("\x14", "\\x14"); - input = input.Replace("\x15", "\\x15"); - input = input.Replace("\x16", "\\x16"); - input = input.Replace("\x17", "\\x17"); - input = input.Replace("\x18", "\\x18"); - input = input.Replace("\x19", "\\x19"); - input = input.Replace("\x1a", "\\x1a"); - input = input.Replace("\x1b", "\\x1b"); - input = input.Replace("\x1c", "\\x1c"); - input = input.Replace("\x1d", "\\x1d"); - input = input.Replace("\x1e", "\\x1e"); - input = input.Replace("\x1f", "\\x1f"); - + foreach (var replacement in _yamlControlCharacterStringReplacements) + { + input = input.Replace(replacement.Key, replacement.Value); + } + return $"\"{input}\""; } @@ -177,8 +148,8 @@ internal static string GetYamlCompatibleString(this string input) // wrap the string in single quote. // http://www.yaml.org/spec/1.2/spec.html#style/flow/plain if (_yamlPlainStringForbiddenCombinations.Any(fc => input.Contains(fc)) || - _yamlIndicators.Any(i => input.StartsWith(i.ToString())) || - _yamlPlainStringForbiddenTerminals.Any(i => input.EndsWith(i.ToString())) || + _yamlIndicators.Any(i => input.StartsWith(i)) || + _yamlPlainStringForbiddenTerminals.Any(i => input.EndsWith(i)) || input.Trim() != input) { // Escape single quotes with two single quotes. @@ -189,10 +160,10 @@ internal static string GetYamlCompatibleString(this string input) // If string can be mistaken as a number, c-style hexadecimal notation, a boolean, or a timestamp, // wrap it in quote to indicate that this is indeed a string, not a number, c-style hexadecimal notation, a boolean, or a timestamp - if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out var _) || + if (decimal.TryParse(input, NumberStyles.Float, CultureInfo.InvariantCulture, out _) || IsHexadecimalNotation(input) || - bool.TryParse(input, out var _) || - DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out var _)) + bool.TryParse(input, out _) || + DateTime.TryParse(input, CultureInfo.InvariantCulture, DateTimeStyles.None, out _)) { return $"'{input}'"; } @@ -215,21 +186,20 @@ internal static string GetJsonCompatibleString(this string value) // http://json.org/ // Replace the backslash first, so that the new backslashes created by other Replaces are not duplicated. - value = value.Replace("\\", "\\\\"); - - value = value.Replace("\b", "\\b"); - value = value.Replace("\f", "\\f"); - value = value.Replace("\n", "\\n"); - value = value.Replace("\r", "\\r"); - value = value.Replace("\t", "\\t"); - value = value.Replace("\"", "\\\""); + value = value.Replace("\\", "\\\\") + .Replace("\b", "\\b") + .Replace("\f", "\\f") + .Replace("\n", "\\n") + .Replace("\r", "\\r") + .Replace("\t", "\\t") + .Replace("\"", "\\\""); return $"\"{value}\""; } internal static bool IsHexadecimalNotation(string input) { - return input.StartsWith("0x") && int.TryParse(input.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out var _); + return input.StartsWith("0x") && int.TryParse(input.Substring(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out _); } } } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj index 1f2ec91e3..23a9f1698 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -14,8 +14,8 @@ - - + + diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index b2b6b6c9b..2844849e0 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -180,7 +180,6 @@ public Task ThrowIfOpenApiUrlIsNotProvidedWhenValidating() OpenApiService.ValidateOpenApiDocument("", _logger)); } - [Fact] public Task ThrowIfURLIsNotResolvableWhenValidating() { @@ -208,7 +207,7 @@ public async Task ValidateCommandProcessesOpenApi() [Fact] public async Task TransformCommandConvertsOpenApi() { - HidiOptions options = new HidiOptions + var options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml"), Output = new("sample.json"), @@ -228,7 +227,7 @@ public async Task TransformCommandConvertsOpenApi() [Fact] public async Task TransformCommandConvertsOpenApiWithDefaultOutputName() { - HidiOptions options = new HidiOptions + var options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml"), CleanOutput = true, @@ -246,7 +245,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputName() [Fact] public async Task TransformCommandConvertsCsdlWithDefaultOutputName() { - HidiOptions options = new HidiOptions + var options = new HidiOptions { Csdl = Path.Combine("UtilityFiles", "Todo.xml"), CleanOutput = true, @@ -264,7 +263,7 @@ public async Task TransformCommandConvertsCsdlWithDefaultOutputName() [Fact] public async Task TransformCommandConvertsOpenApiWithDefaultOutputNameAndSwitchFormat() { - HidiOptions options = new HidiOptions + var options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml"), CleanOutput = true, @@ -284,7 +283,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputNameAndSwitchF [Fact] public Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() { - HidiOptions options = new HidiOptions + var options = new HidiOptions { CleanOutput = true, TerseOutput = false, @@ -299,7 +298,7 @@ public Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() public async Task TransformToPowerShellCompliantOpenApi() { var settingsPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "UtilityFiles", "examplepowershellsettings.json"); - HidiOptions options = new HidiOptions + var options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml"), CleanOutput = true, @@ -322,7 +321,7 @@ public void InvokeTransformCommand() { var rootCommand = Program.CreateRootCommand(); var openapi = Path.Combine(".", "UtilityFiles", "SampleOpenApi.yml"); - var args = new string[] { "transform", "-d", openapi, "-o", "sample.json", "--co" }; + var args = new[] { "transform", "-d", openapi, "-o", "sample.json", "--co" }; var parseResult = rootCommand.Parse(args); var handler = rootCommand.Subcommands.Where(c => c.Name == "transform").First().Handler; var context = new InvocationContext(parseResult); @@ -339,7 +338,7 @@ public void InvokeShowCommand() { var rootCommand = Program.CreateRootCommand(); var openApi = Path.Combine(".", "UtilityFiles", "SampleOpenApi.yml"); - var args = new string[] { "show", "-d", openApi, "-o", "sample.md" }; + var args = new[] { "show", "-d", openApi, "-o", "sample.md" }; var parseResult = rootCommand.Parse(args); var handler = rootCommand.Subcommands.Where(c => c.Name == "show").First().Handler; var context = new InvocationContext(parseResult); @@ -355,7 +354,7 @@ public void InvokePluginCommand() { var rootCommand = Program.CreateRootCommand(); var manifest = Path.Combine(".", "UtilityFiles", "exampleapimanifest.json"); - var args = new string[] { "plugin", "-m", manifest, "--of", AppDomain.CurrentDomain.BaseDirectory }; + var args = new[] { "plugin", "-m", manifest, "--of", AppDomain.CurrentDomain.BaseDirectory }; var parseResult = rootCommand.Parse(args); var handler = rootCommand.Subcommands.Where(c => c.Name == "plugin").First().Handler; var context = new InvocationContext(parseResult); diff --git a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj index 0284522af..e076c0bec 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -21,8 +21,8 @@ - - + + diff --git a/test/Microsoft.OpenApi.Readers.Tests/Resources.cs b/test/Microsoft.OpenApi.Readers.Tests/Resources.cs index 460e33710..431c86e04 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Resources.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/Resources.cs @@ -15,7 +15,7 @@ internal static class Resources /// The file contents. public static string GetString(string fileName) { - using Stream stream = GetStream(fileName); + using var stream = GetStream(fileName); using TextReader reader = new StreamReader(stream); return reader.ReadToEnd(); } @@ -27,8 +27,8 @@ public static string GetString(string fileName) /// The file stream. public static Stream GetStream(string fileName) { - string path = GetPath(fileName); - Stream stream = typeof(Resources).Assembly.GetManifestResourceStream(path); + var path = GetPath(fileName); + var stream = typeof(Resources).Assembly.GetManifestResourceStream(path); if (stream == null) { diff --git a/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs b/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs index 50013739c..561cde431 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/TestCustomExtension.cs @@ -27,7 +27,7 @@ public void ParseCustomExtension() """; var settings = new OpenApiReaderSettings { - ExtensionParsers = { { "x-foo", (a,v) => { + ExtensionParsers = { { "x-foo", (a,_) => { var fooNode = (OpenApiObject)a; return new FooExtension { diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index 9e76f6491..3a1c86298 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -401,11 +401,11 @@ public void ShouldAssignSchemaToAllResponses() public void ShouldAllowComponentsThatJustContainAReference() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "ComponentRootReference.json")); - OpenApiStreamReader reader = new OpenApiStreamReader(); - OpenApiDocument doc = reader.Read(stream, out OpenApiDiagnostic diags); - OpenApiSchema schema1 = doc.Components.Schemas["AllPets"]; + var reader = new OpenApiStreamReader(); + var doc = reader.Read(stream, out var diags); + var schema1 = doc.Components.Schemas["AllPets"]; Assert.False(schema1.UnresolvedReference); - OpenApiSchema schema2 = doc.ResolveReferenceTo(schema1.Reference); + var schema2 = doc.ResolveReferenceTo(schema1.Reference); if (schema2.UnresolvedReference && schema1.Reference.Id == schema2.Reference.Id) { // detected a cycle - this code gets triggered @@ -418,7 +418,7 @@ public void ParseDocumentWithDefaultContentTypeSettingShouldSucceed() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "docWithEmptyProduces.yaml")); var doc = new OpenApiStreamReader(new() { DefaultContentType = new() { "application/json" } }) - .Read(stream, out OpenApiDiagnostic diags); + .Read(stream, out var diags); var mediaType = doc.Paths["/example"].Operations[OperationType.Get].Responses["200"].Content; Assert.Contains("application/json", mediaType); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index 4505ce33a..1f86ab895 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -38,7 +38,7 @@ public T Clone(T element) where T : IOpenApiSerializable using var streamReader = new StreamReader(stream); var result = streamReader.ReadToEnd(); - return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); + return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out var diagnostic4); } public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) @@ -56,7 +56,7 @@ public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) using var streamReader = new StreamReader(stream); var result = streamReader.ReadToEnd(); - return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic4); + return new OpenApiStringReader().ReadFragment(result, OpenApiSpecVersion.OpenApi3_0, out var diagnostic4); } [Fact] diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 637e25583..7fa988024 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -12,8 +12,8 @@ - - + + diff --git a/test/Microsoft.OpenApi.Tests/Expressions/BodyExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/BodyExpressionTests.cs index 6e11be18f..b5f067580 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/BodyExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/BodyExpressionTests.cs @@ -34,8 +34,8 @@ public void BodyExpressionWorksWithDefaultConstructor() public void BodyExpressionConstructorCreateCorrectBodyExpression() { // Arrange - string expression = "#/user/uuid"; - JsonPointer pointer = new JsonPointer(expression); + var expression = "#/user/uuid"; + var pointer = new JsonPointer(expression); // Act var body = new BodyExpression(pointer); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs index abe1cf929..601387385 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs @@ -27,7 +27,7 @@ public void HeaderExpressionConstructorThrows(string token) public void BodyExpressionWorksWithConstructor() { // Arrange - string expression = "accept"; + var expression = "accept"; // Act var header = new HeaderExpression(expression); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs index 3ff084f77..49438b5a5 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs @@ -27,7 +27,7 @@ public void PathExpressionConstructorThrows(string name) public void PathExpressionConstructorWorks() { // Arrange - string name = "anyValue"; + var name = "anyValue"; // Act var path = new PathExpression(name); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs index e4d215496..1c025cfa3 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs @@ -27,7 +27,7 @@ public void QueryExpressionConstructorThrows(string name) public void QueryExpressionConstructorWorks() { // Arrange - string name = "anyValue"; + var name = "anyValue"; // Act var query = new QueryExpression(name); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/RequestExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/RequestExpressionTests.cs index ba74cbd92..4406485f1 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/RequestExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/RequestExpressionTests.cs @@ -24,10 +24,10 @@ public void RequestExpressionConstructorThrows() public void RequestExpressionConstructorWorks() { // Arrange - SourceExpression source = SourceExpression.Build("header.accept"); + var source = SourceExpression.Build("header.accept"); // Act - RequestExpression request = new RequestExpression(source); + var request = new RequestExpression(source); // Assert Assert.Same(source, request.Source); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/ResponseExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/ResponseExpressionTests.cs index a384d6cac..d20cdf7a7 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/ResponseExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/ResponseExpressionTests.cs @@ -24,10 +24,10 @@ public void ResponseExpressionConstructorThrows() public void ResponseExpressionConstructorWorks() { // Arrange - SourceExpression source = SourceExpression.Build("header.accept"); + var source = SourceExpression.Build("header.accept"); // Act - ResponseExpression response = new ResponseExpression(source); + var response = new ResponseExpression(source); // Assert Assert.Same(source, response.Source); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs index 9b43b93ec..a60e2698a 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs @@ -38,7 +38,7 @@ public void BuildRuntimeExpressionThrowsInvalidFormat(string expression) Action test = () => RuntimeExpression.Build(expression); // Assert - OpenApiException exception = Assert.Throws(test); + var exception = Assert.Throws(test); Assert.Equal(String.Format(SRResource.RuntimeExpressionHasInvalidFormat, expression), exception.Message); } @@ -46,7 +46,7 @@ public void BuildRuntimeExpressionThrowsInvalidFormat(string expression) public void BuildMethodRuntimeExpressionReturnsMethodExpression() { // Arrange - string expression = "$method"; + var expression = "$method"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -61,7 +61,7 @@ public void BuildMethodRuntimeExpressionReturnsMethodExpression() public void BuildUrlRuntimeExpressionReturnsUrlExpression() { // Arrange - string expression = "$url"; + var expression = "$url"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -76,7 +76,7 @@ public void BuildUrlRuntimeExpressionReturnsUrlExpression() public void BuildStatusCodeRuntimeExpressionReturnsStatusCodeExpression() { // Arrange - string expression = "$statusCode"; + var expression = "$statusCode"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -91,7 +91,7 @@ public void BuildStatusCodeRuntimeExpressionReturnsStatusCodeExpression() public void BuildRequestRuntimeExpressionReturnsRequestExpression() { // Arrange - string expression = "$request.header.accept"; + var expression = "$request.header.accept"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -114,7 +114,7 @@ public void BuildRequestRuntimeExpressionReturnsRequestExpression() public void BuildResponseRuntimeExpressionReturnsResponseExpression() { // Arrange - string expression = "$response.body#/status"; + var expression = "$response.body#/status"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -153,7 +153,7 @@ public void BuildRuntimeExpressionTwiceCreatesNewEquivalentInstances(string expr public void CompositeRuntimeExpressionContainsExpression() { // Arrange - string expression = "This is a composite expression {$url} yay"; + var expression = "This is a composite expression {$url} yay"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -171,7 +171,7 @@ public void CompositeRuntimeExpressionContainsExpression() public void CompositeRuntimeExpressionContainsMultipleExpressions() { // Arrange - string expression = "This is a composite expression {$url} yay and {$request.header.foo}"; + var expression = "This is a composite expression {$url} yay and {$request.header.foo}"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -195,7 +195,7 @@ public void CompositeRuntimeExpressionContainsMultipleExpressions() public void CompositeRuntimeExpressionForWebHook() { // Arrange - string expression = "http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}"; + var expression = "http://notificationServer.com?transactionId={$request.body#/id}&email={$request.body#/email}"; // Act var runtimeExpression = RuntimeExpression.Build(expression); @@ -216,7 +216,7 @@ public void CompositeRuntimeExpressionForWebHook() public void CompositeRuntimeExpressionWithMultipleRuntimeExpressionsAndFakeBraces() { // Arrange - string expression = "This is a composite expression {url} {test} and {} {$url} and {$request.header.foo}"; + var expression = "This is a composite expression {url} {test} and {} {$url} and {$request.header.foo}"; // Act var runtimeExpression = RuntimeExpression.Build(expression); diff --git a/test/Microsoft.OpenApi.Tests/Expressions/SourceExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/SourceExpressionTests.cs index 12aaf47c5..5ed80bf6e 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/SourceExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/SourceExpressionTests.cs @@ -24,7 +24,7 @@ public void BuildSourceExpressionThrowsInvalidFormat(string expression) Action test = () => SourceExpression.Build(expression); // Assert - OpenApiException exception = Assert.Throws(test); + var exception = Assert.Throws(test); Assert.Equal(String.Format(SRResource.SourceExpressionHasInvalidFormat, expression), exception.Message); } @@ -32,7 +32,7 @@ public void BuildSourceExpressionThrowsInvalidFormat(string expression) public void BuildHeaderExpressionReturnsHeaderExpression() { // Arrange - string expression = "header.accept"; + var expression = "header.accept"; // Act var sourceExpression = SourceExpression.Build(expression); @@ -48,7 +48,7 @@ public void BuildHeaderExpressionReturnsHeaderExpression() public void BuildQueryExpressionReturnsQueryExpression() { // Arrange - string expression = "query.anyValue"; + var expression = "query.anyValue"; // Act var sourceExpression = SourceExpression.Build(expression); @@ -64,7 +64,7 @@ public void BuildQueryExpressionReturnsQueryExpression() public void BuildPathExpressionReturnsPathExpression() { // Arrange - string expression = "path.anyValue"; + var expression = "path.anyValue"; // Act var sourceExpression = SourceExpression.Build(expression); @@ -80,7 +80,7 @@ public void BuildPathExpressionReturnsPathExpression() public void BuildBodyExpressionReturnsBodyExpression() { // Arrange - string expression = "body#/user/uuid"; + var expression = "body#/user/uuid"; // Act var sourceExpression = SourceExpression.Build(expression); diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 331846dae..b5e18ee5c 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,9 +15,9 @@ - - - + + + diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs index 5f4cd74fa..8f0a77160 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs @@ -13,8 +13,8 @@ public class OpenApiDeprecationExtensionTests public void ExtensionNameMatchesExpected() { // Act - string name = OpenApiDeprecationExtension.Name; - string expectedName = "x-ms-deprecation"; + var name = OpenApiDeprecationExtension.Name; + var expectedName = "x-ms-deprecation"; // Assert Assert.Equal(expectedName, name); @@ -30,7 +30,7 @@ public void WritesNothingWhenNoValues() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.Null(extension.Date); @@ -55,7 +55,7 @@ public void WritesAllValues() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.NotNull(extension.Date); diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumFlagsExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumFlagsExtensionTests.cs index 9c05a8e18..61868ff94 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumFlagsExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumFlagsExtensionTests.cs @@ -13,8 +13,8 @@ public class OpenApiEnumFlagsExtensionTests public void ExtensionNameMatchesExpected() { // Act - string name = OpenApiEnumFlagsExtension.Name; - string expectedName = "x-ms-enum-flags"; + var name = OpenApiEnumFlagsExtension.Name; + var expectedName = "x-ms-enum-flags"; // Assert Assert.Equal(expectedName, name); @@ -30,7 +30,7 @@ public void WritesDefaultValues() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.Contains("\"isFlags\": false", result); @@ -51,7 +51,7 @@ public void WritesAllDefaultValues() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.Contains("\"isFlags\": true", result); @@ -71,7 +71,7 @@ public void WritesAllValues() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.True(extension.IsFlags); diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs index e8ea2fe07..3b9f9964a 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiEnumValuesDescriptionExtensionTests.cs @@ -11,8 +11,8 @@ public class OpenApiEnumValuesDescriptionExtensionTests public void ExtensionNameMatchesExpected() { // Act - string name = OpenApiEnumValuesDescriptionExtension.Name; - string expectedName = "x-ms-enum"; + var name = OpenApiEnumValuesDescriptionExtension.Name; + var expectedName = "x-ms-enum"; // Assert Assert.Equal(expectedName, name); @@ -27,7 +27,7 @@ public void WritesNothingWhenNoValues() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.Empty(extension.EnumName); @@ -55,7 +55,7 @@ public void WritesEnumDescription() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.Contains("values", result); diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPagingExtensionsTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPagingExtensionsTests.cs index cfbbf0a17..2eb362885 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPagingExtensionsTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPagingExtensionsTests.cs @@ -13,7 +13,7 @@ public class OpenApiPagingExtensionsTests public void ExtensionNameMatchesExpected() { // Act - string name = OpenApiPagingExtension.Name; + var name = OpenApiPagingExtension.Name; var expectedName = "x-ms-pageable"; // Assert diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs index 5ef75d8a9..9ea10df21 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs @@ -16,8 +16,8 @@ public class OpenApiPrimaryErrorMessageExtensionTests public void ExtensionNameMatchesExpected() { // Act - string name = MicrosoftExtensions.OpenApiPrimaryErrorMessageExtension.Name; - string expectedName = "x-ms-primary-error-message"; + var name = MicrosoftExtensions.OpenApiPrimaryErrorMessageExtension.Name; + var expectedName = "x-ms-primary-error-message"; // Assert Assert.Equal(expectedName, name); @@ -36,7 +36,7 @@ public void WritesValue() // Act extension.Write(writer, OpenApiSpecVersion.OpenApi3_0); - string result = sWriter.ToString(); + var result = sWriter.ToString(); // Assert Assert.True(extension.IsPrimaryErrorMessage); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 1538aa2fb..ea0b98956 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1655,7 +1655,7 @@ And reading in similar documents(one has a whitespace) yields the same hash code private static OpenApiDocument ParseInputFile(string filePath) { // Read in the input yaml file - using FileStream stream = File.OpenRead(filePath); + using var stream = File.OpenRead(filePath); var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); return openApiDoc; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs index 3f95fb9e3..2f4a532a7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs @@ -17,7 +17,7 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiLinkTests { - public static OpenApiLink AdvancedLink = new() + public static readonly OpenApiLink AdvancedLink = new() { OperationId = "operationId1", Parameters = @@ -41,7 +41,7 @@ public class OpenApiLinkTests } }; - public static OpenApiLink ReferencedLink = new() + public static readonly OpenApiLink ReferencedLink = new() { Reference = new() { @@ -120,5 +120,35 @@ public async Task SerializeReferencedLinkAsV3JsonWithoutReferenceWorksAsync(bool // Assert await Verifier.Verify(outputStringWriter).UseParameters(produceTerseOutput); } + + [Fact] + public void LinkExtensionsSerializationWorks() + { + // Arrange + var link = new OpenApiLink() + { + Extensions = { + { "x-display", new OpenApiString("Abc") } +} + }; + + var expected = + """ + { + "x-display": "Abc" + } + """; + + var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = false }); + + + // Act + link.SerializeAsV3(writer); + + // Assert + var actual = outputStringWriter.ToString(); + Assert.Equal(expected.MakeLineBreaksEnvironmentNeutral(), actual.MakeLineBreaksEnvironmentNeutral()); + } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index b4c331830..c4a9ddd53 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -1,15 +1,18 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Collections.Generic; using System.Globalization; using System.IO; +using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Writers; using VerifyXunit; using Xunit; @@ -22,7 +25,7 @@ public class OpenApiSchemaTests { public static OpenApiSchema BasicSchema = new(); - public static OpenApiSchema AdvancedSchemaNumber = new() + public static readonly OpenApiSchema AdvancedSchemaNumber = new() { Title = "title1", MultipleOf = 3, @@ -39,7 +42,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema AdvancedSchemaObject = new() + public static readonly OpenApiSchema AdvancedSchemaObject = new() { Title = "title1", Properties = new Dictionary @@ -88,7 +91,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema AdvancedSchemaWithAllOf = new() + public static readonly OpenApiSchema AdvancedSchemaWithAllOf = new() { Title = "title1", AllOf = new List @@ -140,7 +143,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema ReferencedSchema = new() + public static readonly OpenApiSchema ReferencedSchema = new() { Title = "title1", MultipleOf = 3, @@ -163,7 +166,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema AdvancedSchemaWithRequiredPropertiesObject = new() + public static readonly OpenApiSchema AdvancedSchemaWithRequiredPropertiesObject = new() { Title = "title1", Required = new HashSet { "property1" }, @@ -506,5 +509,56 @@ public void CloningSchemaExtensionsWorks() }; Assert.NotEqual(schema.Extensions, schemaCopy.Extensions); } + + [Fact] + public void OpenApiWalkerVisitsOpenApiSchemaNot() + { + var outerSchema = new OpenApiSchema() + { + Title = "Outer Schema", + Not = new OpenApiSchema() + { + Title = "Inner Schema", + Type = "string", + } + }; + + var document = new OpenApiDocument() + { + Paths = new OpenApiPaths() + { + ["/foo"] = new OpenApiPathItem() + { + Parameters = new[] + { + new OpenApiParameter() + { + Name = "foo", + In = ParameterLocation.Query, + Schema = outerSchema, + } + } + } + } + }; + + // Act + var visitor = new SchemaVisitor(); + var walker = new OpenApiWalker(visitor); + walker.Walk(document); + + // Assert + visitor.Titles.Count.Should().Be(2); + } + } + + internal class SchemaVisitor : OpenApiVisitorBase + { + public List Titles = new(); + + public override void Visit(OpenApiSchema schema) + { + Titles.Add(schema.Title); + } } } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs index 36ead6e72..4c962aaad 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs @@ -265,9 +265,9 @@ public void SchemesShouldConsiderOnlyReferenceIdForEquality() securityRequirement.Add(securityScheme1, new List()); securityRequirement.Add(securityScheme2, new List { "scope1", "scope2" }); - Action addSecurityScheme1Duplicate = () => + var addSecurityScheme1Duplicate = () => securityRequirement.Add(securityScheme1Duplicate, new List()); - Action addSecurityScheme1WithDifferentProperties = () => + var addSecurityScheme1WithDifferentProperties = () => securityRequirement.Add(securityScheme1WithDifferentProperties, new List()); // Assert diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index c7ee7e692..94164c3cd 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -109,7 +109,7 @@ public void CreateMultiplePathsWorks() { var doc = OpenApiDocumentSample_1; - string label = "assets"; + var label = "assets"; var rootNode = OpenApiUrlTreeNode.Create(doc, label); Assert.NotNull(rootNode); @@ -378,28 +378,13 @@ public void AdditionalDataWorks() Assert.Equal(4, rootNode.AdditionalData.Count); Assert.True(rootNode.AdditionalData.ContainsKey("DatePurchased")); Assert.Collection(rootNode.AdditionalData["Location"], - item => - { - Assert.Equal("Seattle, WA", item); - }); + item => Assert.Equal("Seattle, WA", item)); Assert.Collection(rootNode.Children["houses"].AdditionalData["Bedrooms"], - item => - { - Assert.Equal("Five", item); - }); + item => Assert.Equal("Five", item)); Assert.Collection(rootNode.Children["cars"].AdditionalData["Categories"], - item => - { - Assert.Equal("Coupe", item); - }, - item => - { - Assert.Equal("Sedan", item); - }, - item => - { - Assert.Equal("Convertible", item); - }); + item => Assert.Equal("Coupe", item), + item => Assert.Equal("Sedan", item), + item => Assert.Equal("Convertible", item)); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs index e4a24c308..f6ce92ead 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiComponentsValidationTests.cs @@ -20,7 +20,7 @@ public void ValidateKeyMustMatchRegularExpressionInComponents() // Arrange const string key = "%@abc"; - OpenApiComponents components = new OpenApiComponents + var components = new OpenApiComponents { Responses = new Dictionary { @@ -31,12 +31,12 @@ public void ValidateKeyMustMatchRegularExpressionInComponents() var errors = components.Validate(ValidationRuleSet.GetDefaultRuleSet()); // Act - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); - OpenApiError error = Assert.Single(errors); + var error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_ComponentsKeyMustMatchRegularExpr, key, "responses", OpenApiComponentsRules.KeyRegex.ToString()), error.Message); } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs index bf927297e..3ad7130ad 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiContactValidationTests.cs @@ -18,19 +18,19 @@ public void ValidateEmailFieldIsEmailAddressInContact() // Arrange const string testEmail = "support/example.com"; - OpenApiContact contact = new OpenApiContact + var contact = new OpenApiContact { Email = testEmail }; // Act var errors = contact.Validate(ValidationRuleSet.GetDefaultRuleSet()); - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); - OpenApiError error = Assert.Single(errors); + var error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_StringMustBeEmailAddress, testEmail), error.Message); } } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs index d5b404438..001e5da92 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiExternalDocsValidationTests.cs @@ -16,18 +16,18 @@ public class OpenApiExternalDocsValidationTests public void ValidateUrlIsRequiredInExternalDocs() { // Arrange - OpenApiExternalDocs externalDocs = new OpenApiExternalDocs(); + var externalDocs = new OpenApiExternalDocs(); // Act var errors = externalDocs.Validate(ValidationRuleSet.GetDefaultRuleSet()); // Assert - bool result = !errors.Any(); + var result = !errors.Any(); Assert.False(result); Assert.NotNull(errors); - OpenApiError error = Assert.Single(errors); + var error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "url", "External Documentation"), error.Message); } } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs index b051c1a22..240b8b833 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs @@ -36,7 +36,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() errors = validator.Errors; var warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -107,7 +107,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(header); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs index e67b3b116..95dde7942 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiInfoValidationTests.cs @@ -16,15 +16,15 @@ public class OpenApiInfoValidationTests public void ValidateFieldIsRequiredInInfo() { // Arrange - string titleError = String.Format(SRResource.Validation_FieldIsRequired, "title", "info"); - string versionError = String.Format(SRResource.Validation_FieldIsRequired, "version", "info"); + var titleError = String.Format(SRResource.Validation_FieldIsRequired, "title", "info"); + var versionError = String.Format(SRResource.Validation_FieldIsRequired, "version", "info"); var info = new OpenApiInfo(); // Act var errors = info.Validate(ValidationRuleSet.GetDefaultRuleSet()); // Assert - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs index 45bab5671..0f30b0580 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiLicenseValidationTests.cs @@ -18,7 +18,7 @@ public void ValidateFieldIsRequiredInLicense() { // Arrange IEnumerable errors; - OpenApiLicense license = new OpenApiLicense(); + var license = new OpenApiLicense(); // Act var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); @@ -26,12 +26,12 @@ public void ValidateFieldIsRequiredInLicense() walker.Walk(license); errors = validator.Errors; - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); - OpenApiError error = Assert.Single(errors); + var error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "name", "license"), error.Message); } } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs index d33cb02da..550b01022 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs @@ -35,7 +35,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(mediaType); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -106,7 +106,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(mediaType); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs index 329727b2b..a49b3f9bb 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiOAuthFlowValidationTests.cs @@ -17,10 +17,10 @@ public class OpenApiOAuthFlowValidationTests public void ValidateFixedFieldsIsRequiredInResponse() { // Arrange - string authorizationUrlError = String.Format(SRResource.Validation_FieldIsRequired, "authorizationUrl", "OAuth Flow"); - string tokenUrlError = String.Format(SRResource.Validation_FieldIsRequired, "tokenUrl", "OAuth Flow"); + var authorizationUrlError = String.Format(SRResource.Validation_FieldIsRequired, "authorizationUrl", "OAuth Flow"); + var tokenUrlError = String.Format(SRResource.Validation_FieldIsRequired, "tokenUrl", "OAuth Flow"); IEnumerable errors; - OpenApiOAuthFlow oAuthFlow = new OpenApiOAuthFlow(); + var oAuthFlow = new OpenApiOAuthFlow(); // Act var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); @@ -28,7 +28,7 @@ public void ValidateFixedFieldsIsRequiredInResponse() walker.Walk(oAuthFlow); errors = validator.Errors; - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs index 27ea80c48..bc8f1a517 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs @@ -21,8 +21,8 @@ public class OpenApiParameterValidationTests public void ValidateFieldIsRequiredInParameter() { // Arrange - string nameError = String.Format(SRResource.Validation_FieldIsRequired, "name", "parameter"); - string inError = String.Format(SRResource.Validation_FieldIsRequired, "in", "parameter"); + var nameError = String.Format(SRResource.Validation_FieldIsRequired, "name", "parameter"); + var inError = String.Format(SRResource.Validation_FieldIsRequired, "in", "parameter"); var parameter = new OpenApiParameter(); // Act @@ -85,7 +85,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(parameter); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -159,7 +159,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(parameter); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -203,7 +203,7 @@ public void PathParameterNotInThePathShouldReturnAnError() walker.Walk(parameter); errors = validator.Errors; - bool result = errors.Any(); + var result = errors.Any(); // Assert result.Should().BeTrue(); @@ -246,7 +246,7 @@ public void PathParameterInThePathShouldBeOk() walker.Walk(parameter); errors = validator.Errors; - bool result = errors.Any(); + var result = errors.Any(); // Assert result.Should().BeFalse(); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs index b145f9ab9..4c252716f 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs @@ -28,7 +28,7 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() UnresolvedReference = false }; - OpenApiDocument document = new OpenApiDocument(); + var document = new OpenApiDocument(); document.Components = new() { Schemas = new Dictionary @@ -84,7 +84,7 @@ public void UnresolvedReferenceSchemaShouldNotBeValidated() UnresolvedReference = true }; - OpenApiDocument document = new OpenApiDocument(); + var document = new OpenApiDocument(); document.Components = new() { Schemas = new Dictionary @@ -114,7 +114,7 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() UnresolvedReference = true }; - OpenApiDocument document = new OpenApiDocument(); + var document = new OpenApiDocument(); document.Paths = new() { @@ -152,7 +152,7 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() public class AlwaysFailRule : ValidationRule where T : IOpenApiElement { - public AlwaysFailRule() : base((c, t) => c.CreateError("x", "y")) + public AlwaysFailRule() : base((c, _) => c.CreateError("x", "y")) { } } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs index a3a84af95..b967ebab6 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiResponseValidationTests.cs @@ -18,7 +18,7 @@ public void ValidateDescriptionIsRequiredInResponse() { // Arrange IEnumerable errors; - OpenApiResponse response = new OpenApiResponse(); + var response = new OpenApiResponse(); // Act var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); @@ -26,12 +26,12 @@ public void ValidateDescriptionIsRequiredInResponse() walker.Walk(response); errors = validator.Errors; - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); - OpenApiValidatorError error = Assert.Single(errors) as OpenApiValidatorError; + var error = Assert.Single(errors) as OpenApiValidatorError; Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "description", "response"), error.Message); Assert.Equal("#/description", error.Pointer); } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs index bfe3706f1..7f3caa20a 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs @@ -34,7 +34,7 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(schema); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -66,7 +66,7 @@ public void ValidateExampleAndDefaultShouldNotHaveDataTypeMismatchForSimpleSchem walker.Walk(schema); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -121,7 +121,7 @@ public void ValidateEnumShouldNotHaveDataTypeMismatchForSimpleSchema() walker.Walk(schema); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -211,7 +211,7 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForComplexSchema() walker.Walk(schema); warnings = validator.Warnings; - bool result = !warnings.Any(); + var result = !warnings.Any(); // Assert result.Should().BeFalse(); @@ -257,7 +257,7 @@ public void ValidateSchemaRequiredFieldListMustContainThePropertySpecifiedInTheD walker.Walk(components); errors = validator.Errors; - bool result = !errors.Any(); + var result = !errors.Any(); // Assert result.Should().BeFalse(); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs index 0cc6f9877..aa6d6ecd0 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiServerValidationTests.cs @@ -17,18 +17,18 @@ public void ValidateFieldIsRequiredInServer() { // Arrange IEnumerable errors; - OpenApiServer server = new OpenApiServer(); + var server = new OpenApiServer(); // Act var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); validator.Visit(server); errors = validator.Errors; - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); - OpenApiError error = Assert.Single(errors); + var error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "url", "server"), error.Message); } } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs index 7e530e6d2..b1362664f 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiTagValidationTests.cs @@ -19,18 +19,18 @@ public void ValidateNameIsRequiredInTag() { // Arrange IEnumerable errors; - OpenApiTag tag = new OpenApiTag(); + var tag = new OpenApiTag(); // Act var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); validator.Visit(tag); errors = validator.Errors; - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); - OpenApiError error = Assert.Single(errors); + var error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "name", "tag"), error.Message); } @@ -39,7 +39,7 @@ public void ValidateExtensionNameStartsWithXDashInTag() { // Arrange IEnumerable errors; - OpenApiTag tag = new OpenApiTag + var tag = new OpenApiTag { Name = "tag" }; @@ -49,12 +49,12 @@ public void ValidateExtensionNameStartsWithXDashInTag() var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); validator.Visit(tag as IOpenApiExtensible); errors = validator.Errors; - bool result = !errors.Any(); + var result = !errors.Any(); // Assert Assert.False(result); Assert.NotNull(errors); - OpenApiError error = Assert.Single(errors); + var error = Assert.Single(errors); Assert.Equal(String.Format(SRResource.Validation_ExtensionNameMustBeginWithXDash, "tagExt", "#/extensions"), error.Message); } } diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs index f86295f35..12798779d 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs @@ -103,7 +103,8 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther_short() op.CreateResponse("200", re => { re.Description = "Success"; - re.CreateContent("application/json", co => + re.CreateContent("application/json", + co => co.Schema = new() { Reference = new() // Reference diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs index f53beb8e3..784750ab6 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs @@ -22,7 +22,8 @@ public class OpenApiJsonWriterTests public static IEnumerable WriteStringListAsJsonShouldMatchExpectedTestCases() { return - from input in new string[][] { + from input in new[] + { new[] { "string1", @@ -234,7 +235,7 @@ public void WriteMapAsJsonShouldMatchExpected(IDictionary inputM public static IEnumerable WriteDateTimeAsJsonTestCases() { return - from input in new DateTimeOffset[] { + from input in new[] { new(2018, 1, 1, 10, 20, 30, TimeSpan.Zero), new(2018, 1, 1, 10, 20, 30, 100, TimeSpan.FromHours(14)), DateTimeOffset.UtcNow + TimeSpan.FromDays(4), diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs index 7c378c16f..1e632572e 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs @@ -40,7 +40,7 @@ public static IEnumerable IntInputs get { return - from input in new int[] { + from input in new[] { int.MinValue, 42, int.MaxValue, @@ -68,7 +68,7 @@ public static IEnumerable LongInputs get { return - from input in new long[] { + from input in new[] { long.MinValue, 42, long.MaxValue, @@ -96,7 +96,7 @@ public static IEnumerable FloatInputs get { return - from input in new float[] { + from input in new[] { float.MinValue, 42.42f, float.MaxValue, @@ -124,7 +124,7 @@ public static IEnumerable DoubleInputs get { return - from input in new double[] { + from input in new[] { double.MinValue, 42.42d, double.MaxValue, @@ -180,13 +180,10 @@ public void WriteOpenApiDateTimeAsJsonWorks(string inputString, bool produceTers public static IEnumerable BooleanInputs { - get - { - return - from input in new [] { true, false } - from shouldBeTerse in shouldProduceTerseOutputValues - select new object[] { input, shouldBeTerse }; - } + get => + from input in new [] { true, false } + from shouldBeTerse in shouldProduceTerseOutputValues + select new object[] { input, shouldBeTerse }; } [Theory] diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs index 5e738ecc6..a127e982b 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs @@ -18,23 +18,20 @@ public class OpenApiWriterSpecialCharacterTests public static IEnumerable StringWithSpecialCharacters { - get - { - return - from inputExpected in new[] { - new[]{ "Test\bTest", "\"Test\\bTest\"" }, - new[]{ "Test\fTest", "\"Test\\fTest\""}, - new[]{ "Test\nTest", "\"Test\\nTest\""}, - new[]{ "Test\rTest", "\"Test\\rTest\""}, - new[]{ "Test\tTest", "\"Test\\tTest\""}, - new[]{ "Test\\Test", "\"Test\\\\Test\""}, - new[]{ "Test\"Test", "\"Test\\\"Test\""}, - new[]{ "StringsWith\"Quotes\"", "\"StringsWith\\\"Quotes\\\"\""}, - new[]{ "0x1234", "\"0x1234\""}, - } - from shouldBeTerse in shouldProduceTerseOutputValues - select new object[] { inputExpected[0], inputExpected[1], shouldBeTerse }; - } + get => + from inputExpected in new[] { + new[]{ "Test\bTest", "\"Test\\bTest\"" }, + new[]{ "Test\fTest", "\"Test\\fTest\""}, + new[]{ "Test\nTest", "\"Test\\nTest\""}, + new[]{ "Test\rTest", "\"Test\\rTest\""}, + new[]{ "Test\tTest", "\"Test\\tTest\""}, + new[]{ "Test\\Test", "\"Test\\\\Test\""}, + new[]{ "Test\"Test", "\"Test\\\"Test\""}, + new[]{ "StringsWith\"Quotes\"", "\"StringsWith\\\"Quotes\\\"\""}, + new[]{ "0x1234", "\"0x1234\""}, + } + from shouldBeTerse in shouldProduceTerseOutputValues + select new object[] { inputExpected[0], inputExpected[1], shouldBeTerse }; } [Theory]