From e6535f7380e424668163f812da80d8e8c270b649 Mon Sep 17 00:00:00 2001 From: Fabian Niederer Date: Tue, 28 Apr 2020 11:09:22 +0200 Subject: [PATCH 01/61] added validation & renabled OpenApiPaths validators --- .../Properties/SRResource.Designer.cs | 11 ++++- .../Properties/SRResource.resx | 3 ++ .../Services/OpenApiWalker.cs | 2 + .../Validations/OpenApiValidator.cs | 6 +++ .../Validations/Rules/OpenApiPathsRules.cs | 26 ++++++++++ .../OpenApiPathsValidationTests.cs | 49 +++++++++++++++++++ .../Validations/ValidationRuleSetTests.cs | 2 +- 7 files changed, 97 insertions(+), 2 deletions(-) create mode 100644 test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs diff --git a/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs b/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs index 47f9493b9..69cc96223 100644 --- a/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs +++ b/src/Microsoft.OpenApi/Properties/SRResource.Designer.cs @@ -19,7 +19,7 @@ namespace Microsoft.OpenApi.Properties { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SRResource { @@ -330,6 +330,15 @@ internal static string Validation_PathItemMustBeginWithSlash { } } + /// + /// Looks up a localized string similar to The path signature '{0}' MUST begin be unique.. + /// + internal static string Validation_PathSignatureMustBeUnique { + get { + return ResourceManager.GetString("Validation_PathSignatureMustBeUnique", resourceCulture); + } + } + /// /// Looks up a localized string similar to The same rule cannot be in the same rule set twice.. /// diff --git a/src/Microsoft.OpenApi/Properties/SRResource.resx b/src/Microsoft.OpenApi/Properties/SRResource.resx index 48f910a95..5e439868b 100644 --- a/src/Microsoft.OpenApi/Properties/SRResource.resx +++ b/src/Microsoft.OpenApi/Properties/SRResource.resx @@ -207,6 +207,9 @@ The path item name '{0}' MUST begin with a slash. + + The path signature '{0}' MUST begin be unique. + The same rule cannot be in the same rule set twice. diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index dd3c09564..6167d8d24 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -219,6 +219,7 @@ internal void Walk(OpenApiPaths paths) _visitor.CurrentKeys.Path = null; } } + } /// @@ -1036,6 +1037,7 @@ internal void Walk(IOpenApiElement element) case OpenApiOAuthFlow e: Walk(e); break; case OpenApiOperation e: Walk(e); break; case OpenApiParameter e: Walk(e); break; + case OpenApiPaths e: Walk(e); break; case OpenApiRequestBody e: Walk(e); break; case OpenApiResponse e: Walk(e); break; case OpenApiSchema e: Walk(e); break; diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index 69bcda93d..e6edd8fc7 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -131,6 +131,12 @@ public void AddError(OpenApiValidatorError error) /// The object to be validated public override void Visit(OpenApiParameter item) => Validate(item); + /// + /// Execute validation rules against an + /// + /// The object to be validated + public override void Visit(OpenApiPaths item) => Validate(item); + /// /// Execute validation rules against an /// diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs index 7ac374b62..5e5424870 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs @@ -1,6 +1,8 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System.Collections.Generic; +using System.Text.RegularExpressions; using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Properties; @@ -34,6 +36,30 @@ public static class OpenApiPathsRules } }); + /// + /// A relative path to an individual endpoint. The field name MUST begin with a slash. + /// + public static ValidationRule PathMustBeUnique => + new ValidationRule( + (context, item) => + { + const string regexPath = "\\{([^/]+)\\}"; + var hashSet = new HashSet(); + + foreach (var path in item.Keys) + { + context.Enter(path); + + var pathSignature = Regex.Replace(path, regexPath, "{}"); + + if (!hashSet.Add(pathSignature)) + context.CreateError(nameof(PathMustBeUnique), + string.Format(SRResource.Validation_PathSignatureMustBeUnique, pathSignature)); + + context.Exit(); + } + }); + // add more rules } } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs new file mode 100644 index 000000000..23a0a3e0f --- /dev/null +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiPathsValidationTests.cs @@ -0,0 +1,49 @@ +using System.Linq; +using FluentAssertions; +using Microsoft.OpenApi.Extensions; +using Microsoft.OpenApi.Models; +using Microsoft.OpenApi.Properties; +using Xunit; + +namespace Microsoft.OpenApi.Validations.Tests +{ + public class OpenApiPathsValidationTests + { + [Fact] + public void ValidatePathsMustBeginWithSlash() + { + // Arrange + var error = string.Format(SRResource.Validation_PathItemMustBeginWithSlash, "pets/{petId}"); + var paths = new OpenApiPaths + { + {"pets/{petId}",new OpenApiPathItem() } + }; + + // Act + var errors = paths.Validate(ValidationRuleSet.GetDefaultRuleSet()); + + // Assert + errors.Should().NotBeEmpty(); + errors.Select(e => e.Message).Should().BeEquivalentTo(error); + } + + [Fact] + public void ValidatePathsAreUnique() + { + // Arrange + var error = string.Format(SRResource.Validation_PathSignatureMustBeUnique, "/pets/{}"); + var paths = new OpenApiPaths + { + {"/pets/{petId}",new OpenApiPathItem() }, + {"/pets/{name}",new OpenApiPathItem() } + }; + + // Act + var errors = paths.Validate(ValidationRuleSet.GetDefaultRuleSet()); + + // Assert + errors.Should().NotBeEmpty(); + errors.Select(e => e.Message).Should().BeEquivalentTo(error); + } + } +} diff --git a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs index af259cf1b..8153e6054 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs @@ -43,7 +43,7 @@ public void DefaultRuleSetPropertyReturnsTheCorrectRules() Assert.NotEmpty(rules); // Update the number if you add new default rule(s). - Assert.Equal(21, rules.Count); + Assert.Equal(22, rules.Count); } } } From 6bf85c5bd09203f8fcf4e6d8111b83cddeb306cc Mon Sep 17 00:00:00 2001 From: Darrel Date: Tue, 28 Jul 2020 22:59:08 -0400 Subject: [PATCH 02/61] Update src/Microsoft.OpenApi/Properties/SRResource.resx --- src/Microsoft.OpenApi/Properties/SRResource.resx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Properties/SRResource.resx b/src/Microsoft.OpenApi/Properties/SRResource.resx index 5e439868b..8039212f9 100644 --- a/src/Microsoft.OpenApi/Properties/SRResource.resx +++ b/src/Microsoft.OpenApi/Properties/SRResource.resx @@ -208,7 +208,7 @@ The path item name '{0}' MUST begin with a slash. - The path signature '{0}' MUST begin be unique. + The path signature '{0}' MUST be unique. The same rule cannot be in the same rule set twice. @@ -219,4 +219,4 @@ The string '{0}' MUST be in the format of an email address. - \ No newline at end of file + From 57706d136b7de4082cf6b3cdead555aa6a8ceb61 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Tue, 3 Oct 2023 21:39:03 +1100 Subject: [PATCH 03/61] cleanup exception handling --- .../Attributes/DisplayAttribute.cs | 7 +- .../CallerArgumentExpressionAttribute.cs | 16 +++ src/Microsoft.OpenApi/Error.cs | 98 ------------------- .../Expressions/BodyExpression.cs | 5 +- .../Expressions/HeaderExpression.cs | 5 +- .../Expressions/PathExpression.cs | 5 +- .../Expressions/QueryExpression.cs | 5 +- .../Expressions/RequestExpression.cs | 2 +- .../Expressions/ResponseExpression.cs | 2 +- .../Expressions/RuntimeExpression.cs | 5 +- .../Extensions/OpenApiExtensibleExtensions.cs | 13 +-- .../OpenApiSerializableExtensions.cs | 21 +--- .../Models/OpenApiCallback.cs | 16 +-- .../Models/OpenApiComponents.cs | 5 +- .../Models/OpenApiContact.cs | 5 +- .../Models/OpenApiDiscriminator.cs | 5 +- .../Models/OpenApiDocument.cs | 10 +- .../Models/OpenApiEncoding.cs | 5 +- .../Models/OpenApiExample.cs | 5 +- .../Models/OpenApiExtensibleDictionary.cs | 10 +- .../Models/OpenApiExternalDocs.cs | 5 +- src/Microsoft.OpenApi/Models/OpenApiHeader.cs | 10 +- src/Microsoft.OpenApi/Models/OpenApiInfo.cs | 10 +- .../Models/OpenApiLicense.cs | 5 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 5 +- .../Models/OpenApiMediaType.cs | 5 +- .../Models/OpenApiOAuthFlow.cs | 5 +- .../Models/OpenApiOAuthFlows.cs | 5 +- .../Models/OpenApiOperation.cs | 10 +- .../Models/OpenApiParameter.cs | 10 +- .../Models/OpenApiPathItem.cs | 10 +- .../Models/OpenApiReference.cs | 15 +-- .../Models/OpenApiRequestBody.cs | 5 +- .../Models/OpenApiResponse.cs | 10 +- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 20 +--- .../Models/OpenApiSecurityRequirement.cs | 10 +- .../Models/OpenApiSecurityScheme.cs | 10 +- src/Microsoft.OpenApi/Models/OpenApiServer.cs | 5 +- .../Models/OpenApiServerVariable.cs | 5 +- src/Microsoft.OpenApi/Models/OpenApiTag.cs | 10 +- src/Microsoft.OpenApi/Models/OpenApiXml.cs | 5 +- .../Models/RuntimeExpressionAnyWrapper.cs | 5 +- .../Services/OpenApiUrlTreeNode.cs | 18 ++-- src/Microsoft.OpenApi/Utils.cs | 9 +- .../Validations/OpenApiValidator.cs | 10 +- .../Validations/ValidationRule.cs | 10 +- .../Writers/OpenApiWriterAnyExtensions.cs | 43 ++------ .../Writers/OpenApiWriterBase.cs | 5 +- .../Writers/OpenApiWriterExtensions.cs | 20 +--- .../Resources.cs | 4 +- 50 files changed, 118 insertions(+), 426 deletions(-) create mode 100644 src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs delete mode 100644 src/Microsoft.OpenApi/Error.cs diff --git a/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs b/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs index db60448ea..5c9d48a59 100644 --- a/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs +++ b/src/Microsoft.OpenApi/Attributes/DisplayAttribute.cs @@ -17,12 +17,7 @@ public class DisplayAttribute : Attribute /// The display name. public DisplayAttribute(string name) { - if (string.IsNullOrWhiteSpace(name)) - { - throw Error.ArgumentNullOrWhiteSpace(nameof(name)); - } - - Name = name; + Name = Utils.CheckArgumentNullOrEmpty(name); } /// diff --git a/src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs b/src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs new file mode 100644 index 000000000..60ef93911 --- /dev/null +++ b/src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs @@ -0,0 +1,16 @@ +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace System.Runtime.CompilerServices; + +[ExcludeFromCodeCoverage] +[DebuggerNonUserCode] +[AttributeUsage(AttributeTargets.Parameter)] +sealed class CallerArgumentExpressionAttribute : + Attribute +{ + public CallerArgumentExpressionAttribute(string parameterName) => + ParameterName = parameterName; + + public string ParameterName { get; } +} diff --git a/src/Microsoft.OpenApi/Error.cs b/src/Microsoft.OpenApi/Error.cs deleted file mode 100644 index d0c41780d..000000000 --- a/src/Microsoft.OpenApi/Error.cs +++ /dev/null @@ -1,98 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT license. - -using System; -using System.Globalization; -using Microsoft.OpenApi.Properties; - -namespace Microsoft.OpenApi -{ - /// - /// Utility class for creating and unwrapping instances. - /// - internal static class Error - { - /// - /// Formats the specified resource string using . - /// - /// A composite format string. - /// An object array that contains zero or more objects to format. - /// The formatted string. - internal static string Format(string format, params object[] args) - { - return string.Format(CultureInfo.CurrentCulture, format, args); - } - - /// - /// Creates an with the provided properties. - /// - /// A composite format string explaining the reason for the exception. - /// An object array that contains zero or more objects to format. - /// The logged . - internal static ArgumentException Argument(string messageFormat, params object[] messageArgs) - { - return new ArgumentException(Format(messageFormat, messageArgs)); - } - - /// - /// Creates an with the provided properties. - /// - /// The name of the parameter that caused the current exception. - /// A composite format string explaining the reason for the exception. - /// An object array that contains zero or more objects to format. - /// The logged . - internal static ArgumentException Argument( - string parameterName, - string messageFormat, - params object[] messageArgs) - { - return new ArgumentException(Format(messageFormat, messageArgs), parameterName); - } - - /// - /// Creates an with the provided properties. - /// - /// The name of the parameter that caused the current exception. - /// The logged . - internal static ArgumentNullException ArgumentNull(string parameterName) - { - return new ArgumentNullException(parameterName); - } - - /// - /// Creates an with the provided properties. - /// - /// The name of the parameter that caused the current exception. - /// A composite format string explaining the reason for the exception. - /// An object array that contains zero or more objects to format. - /// The logged . - internal static ArgumentNullException ArgumentNull( - string parameterName, - string messageFormat, - params object[] messageArgs) - { - return new ArgumentNullException(parameterName, Format(messageFormat, messageArgs)); - } - - /// - /// Creates an with a default message. - /// - /// The name of the parameter that caused the current exception. - /// The logged . - internal static ArgumentException ArgumentNullOrWhiteSpace(string parameterName) - { - return Argument(parameterName, SRResource.ArgumentNullOrWhiteSpace, parameterName); - } - - /// - /// Creates an . - /// - /// A composite format string explaining the reason for the exception. - /// An object array that contains zero or more objects to format. - /// The logged . - internal static NotSupportedException NotSupported(string messageFormat, params object[] messageArgs) - { - return new NotSupportedException(Format(messageFormat, messageArgs)); - } - } -} diff --git a/src/Microsoft.OpenApi/Expressions/BodyExpression.cs b/src/Microsoft.OpenApi/Expressions/BodyExpression.cs index cd5c86bd9..8e5b53902 100644 --- a/src/Microsoft.OpenApi/Expressions/BodyExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/BodyExpression.cs @@ -33,10 +33,7 @@ public BodyExpression() public BodyExpression(JsonPointer pointer) : base(pointer?.ToString()) { - if (pointer == null) - { - throw Error.ArgumentNull(nameof(pointer)); - } + Utils.CheckArgumentNull(pointer); } /// diff --git a/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs b/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs index f6642cb08..bfabf218e 100644 --- a/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/HeaderExpression.cs @@ -20,10 +20,7 @@ public class HeaderExpression : SourceExpression public HeaderExpression(string token) : base(token) { - if (string.IsNullOrWhiteSpace(token)) - { - throw Error.ArgumentNullOrWhiteSpace(nameof(token)); - } + Utils.CheckArgumentNullOrEmpty(token); } /// diff --git a/src/Microsoft.OpenApi/Expressions/PathExpression.cs b/src/Microsoft.OpenApi/Expressions/PathExpression.cs index a92c8a569..199fb35cf 100644 --- a/src/Microsoft.OpenApi/Expressions/PathExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/PathExpression.cs @@ -20,10 +20,7 @@ public sealed class PathExpression : SourceExpression public PathExpression(string name) : base(name) { - if (string.IsNullOrWhiteSpace(name)) - { - throw Error.ArgumentNullOrWhiteSpace(nameof(name)); - } + Utils.CheckArgumentNullOrEmpty(name); } /// diff --git a/src/Microsoft.OpenApi/Expressions/QueryExpression.cs b/src/Microsoft.OpenApi/Expressions/QueryExpression.cs index 3277233b3..80ba415f1 100644 --- a/src/Microsoft.OpenApi/Expressions/QueryExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/QueryExpression.cs @@ -20,10 +20,7 @@ public sealed class QueryExpression : SourceExpression public QueryExpression(string name) : base(name) { - if (string.IsNullOrWhiteSpace(name)) - { - throw Error.ArgumentNullOrWhiteSpace(nameof(name)); - } + Utils.CheckArgumentNullOrEmpty(name); } /// diff --git a/src/Microsoft.OpenApi/Expressions/RequestExpression.cs b/src/Microsoft.OpenApi/Expressions/RequestExpression.cs index 7ebf77471..2d6b6d983 100644 --- a/src/Microsoft.OpenApi/Expressions/RequestExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/RequestExpression.cs @@ -19,7 +19,7 @@ public sealed class RequestExpression : RuntimeExpression /// The source of the request. public RequestExpression(SourceExpression source) { - Source = source ?? throw Error.ArgumentNull(nameof(source)); + Source = Utils.CheckArgumentNull(source); } /// diff --git a/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs b/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs index b91370297..e0aedde81 100644 --- a/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/ResponseExpression.cs @@ -19,7 +19,7 @@ public sealed class ResponseExpression : RuntimeExpression /// The source of the response. public ResponseExpression(SourceExpression source) { - Source = source ?? throw Error.ArgumentNull(nameof(source)); + Source = Utils.CheckArgumentNull(source); } /// diff --git a/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs b/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs index 965572dfd..4f78c75d3 100644 --- a/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/RuntimeExpression.cs @@ -29,10 +29,7 @@ public abstract class RuntimeExpression : IEquatable /// The built runtime expression object. public static RuntimeExpression Build(string expression) { - if (string.IsNullOrWhiteSpace(expression)) - { - throw Error.ArgumentNullOrWhiteSpace(nameof(expression)); - } + Utils.CheckArgumentNullOrEmpty(expression); if (!expression.StartsWith(Prefix)) { diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs index 7656aad89..dbe96df89 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiExtensibleExtensions.cs @@ -23,22 +23,15 @@ public static class OpenApiExtensibleExtensions public static void AddExtension(this T element, string name, IOpenApiExtension any) where T : IOpenApiExtensible { - if (element == null) - { - throw Error.ArgumentNull(nameof(element)); - } - - if (string.IsNullOrWhiteSpace(name)) - { - throw Error.ArgumentNullOrWhiteSpace(nameof(name)); - } + Utils.CheckArgumentNull(element); + Utils.CheckArgumentNullOrEmpty(name); if (!name.StartsWith(OpenApiConstants.ExtensionFieldNamePrefix)) { throw new OpenApiException(string.Format(SRResource.ExtensionFieldNameMustBeginWithXDash, name)); } - element.Extensions[name] = any ?? throw Error.ArgumentNull(nameof(any)); + element.Extensions[name] = Utils.CheckArgumentNull(any); } } } diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs index f60c5483b..4f1d108b3 100755 --- a/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiSerializableExtensions.cs @@ -78,10 +78,7 @@ public static void Serialize( OpenApiWriterSettings settings) where T : IOpenApiSerializable { - if (stream == null) - { - throw Error.ArgumentNull(nameof(stream)); - } + Utils.CheckArgumentNull(stream); var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); @@ -105,15 +102,8 @@ public static void Serialize( public static void Serialize(this T element, IOpenApiWriter writer, OpenApiSpecVersion specVersion) where T : IOpenApiSerializable { - if (element == null) - { - throw Error.ArgumentNull(nameof(element)); - } - - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(element); + Utils.CheckArgumentNull(writer); switch (specVersion) { @@ -174,10 +164,7 @@ public static string Serialize( OpenApiFormat format) where T : IOpenApiSerializable { - if (element == null) - { - throw Error.ArgumentNull(nameof(element)); - } + Utils.CheckArgumentNull(element); using (var stream = new MemoryStream()) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index e6aa5d075..46f7c6417 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -57,15 +57,8 @@ public OpenApiCallback(OpenApiCallback callback) /// The path item. public void AddPathItem(RuntimeExpression expression, OpenApiPathItem pathItem) { - if (expression == null) - { - throw Error.ArgumentNull(nameof(expression)); - } - - if (pathItem == null) - { - throw Error.ArgumentNull(nameof(pathItem)); - } + Utils.CheckArgumentNull(expression); + Utils.CheckArgumentNull(pathItem); if (PathItems == null) { @@ -80,10 +73,7 @@ public void AddPathItem(RuntimeExpression expression, OpenApiPathItem pathItem) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index a6bfef594..c403782d7 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -93,10 +93,7 @@ public OpenApiComponents(OpenApiComponents components) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); // If references have been inlined we don't need the to render the components section // however if they have cycles, then we will need a component rendered diff --git a/src/Microsoft.OpenApi/Models/OpenApiContact.cs b/src/Microsoft.OpenApi/Models/OpenApiContact.cs index 113c91b13..c256249b5 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiContact.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiContact.cs @@ -68,10 +68,7 @@ public void SerializeAsV2(IOpenApiWriter writer) private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs index 9ae7f0e6a..0854dec33 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDiscriminator.cs @@ -41,10 +41,7 @@ public OpenApiDiscriminator(OpenApiDiscriminator discriminator) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index d2d9cf893..9b2f46deb 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -96,10 +96,7 @@ public OpenApiDocument(OpenApiDocument document) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); @@ -141,10 +138,7 @@ public void SerializeAsV3(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs index 13b6e3a0a..81dab6628 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiEncoding.cs @@ -75,10 +75,7 @@ public OpenApiEncoding(OpenApiEncoding encoding) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull("writer"); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiExample.cs b/src/Microsoft.OpenApi/Models/OpenApiExample.cs index 4d091a361..b146268da 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExample.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExample.cs @@ -78,10 +78,7 @@ public OpenApiExample(OpenApiExample example) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; diff --git a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs index 40c26d429..c156b25b5 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExtensibleDictionary.cs @@ -43,10 +43,7 @@ protected OpenApiExtensibleDictionary( /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); @@ -65,10 +62,7 @@ public void SerializeAsV3(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs index 91d750e6c..0531ef135 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs @@ -61,10 +61,7 @@ public void SerializeAsV2(IOpenApiWriter writer) private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs index fb4411478..5fc78ae39 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiHeader.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiHeader.cs @@ -117,10 +117,7 @@ public OpenApiHeader(OpenApiHeader header) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; @@ -209,10 +206,7 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; diff --git a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs index e903c8947..676e9d04a 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiInfo.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiInfo.cs @@ -72,10 +72,7 @@ public OpenApiInfo(OpenApiInfo info) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); @@ -108,10 +105,7 @@ public void SerializeAsV3(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs index e22441dc3..5df51db35 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLicense.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLicense.cs @@ -61,10 +61,7 @@ public void SerializeAsV2(IOpenApiWriter writer) private void WriteInternal(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 801ef2ce1..7e851c39f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -86,10 +86,7 @@ public OpenApiLink(OpenApiLink link) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; diff --git a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs index 63a58cd02..2f1923243 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiMediaType.cs @@ -65,10 +65,7 @@ public OpenApiMediaType(OpenApiMediaType mediaType) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs index a9cd2b7df..427164b84 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlow.cs @@ -62,10 +62,7 @@ public OpenApiOAuthFlow(OpenApiOAuthFlow oAuthFlow) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs index d9e71510c..78876c0fd 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOAuthFlows.cs @@ -60,10 +60,7 @@ public OpenApiOAuthFlows(OpenApiOAuthFlows oAuthFlows) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 9336662d8..a83f7aef5 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -135,10 +135,7 @@ public OpenApiOperation(OpenApiOperation operation) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); @@ -195,10 +192,7 @@ public void SerializeAsV3(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 3918f233b..f6627df23 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -177,10 +177,7 @@ public OpenApiParameter(OpenApiParameter parameter) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; @@ -277,10 +274,7 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; if (Reference != null) diff --git a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs index ddd358dc2..68e78738f 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiPathItem.cs @@ -90,10 +90,7 @@ public OpenApiPathItem(OpenApiPathItem pathItem) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; if (Reference != null) @@ -133,10 +130,7 @@ public OpenApiPathItem GetEffective(OpenApiDocument doc) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; diff --git a/src/Microsoft.OpenApi/Models/OpenApiReference.cs b/src/Microsoft.OpenApi/Models/OpenApiReference.cs index e8798cc64..54a54e7fa 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiReference.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiReference.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Writers; @@ -69,7 +70,7 @@ public string ReferenceV3 if (!Type.HasValue) { - throw Error.ArgumentNull(nameof(Type)); + throw new ArgumentNullException(nameof(Type)); } if (Type == ReferenceType.Tag) @@ -100,7 +101,7 @@ public string ReferenceV2 if (!Type.HasValue) { - throw Error.ArgumentNull(nameof(Type)); + throw new ArgumentNullException(nameof(Type)); } if (Type == ReferenceType.Tag) @@ -138,10 +139,7 @@ public OpenApiReference(OpenApiReference reference) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (Type == ReferenceType.Tag) { @@ -170,10 +168,7 @@ public void SerializeAsV3(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (Type == ReferenceType.Tag) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 70f1f742a..07b36b961 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -70,10 +70,7 @@ public OpenApiRequestBody(OpenApiRequestBody requestBody) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; diff --git a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs index a173f6c1a..beef1deb2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiResponse.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiResponse.cs @@ -75,10 +75,7 @@ public OpenApiResponse(OpenApiResponse response) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; @@ -144,10 +141,7 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var target = this; diff --git a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs index b0ac2dbac..a7e0b9ffe 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSchema.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSchema.cs @@ -298,10 +298,7 @@ public OpenApiSchema(OpenApiSchema schema) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var settings = writer.GetSettings(); var target = this; @@ -498,10 +495,7 @@ internal void SerializeAsV2( ISet parentRequiredProperties, string propertyName) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); var settings = writer.GetSettings(); var target = this; @@ -563,10 +557,7 @@ internal void SerializeAsV2WithoutReference( internal void WriteAsItemsProperties(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); // type writer.WriteProperty(OpenApiConstants.Type, Type); @@ -637,10 +628,7 @@ internal void WriteAsSchemaProperties( ISet parentRequiredProperties, string propertyName) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); // format if (string.IsNullOrEmpty(Format)) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs index d2564daf2..d22af1df0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityRequirement.cs @@ -33,10 +33,7 @@ public OpenApiSecurityRequirement() /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); @@ -73,10 +70,7 @@ public void SerializeAsV3(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 64a65bf83..b37cc5a28 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -100,10 +100,7 @@ public OpenApiSecurityScheme(OpenApiSecurityScheme securityScheme) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (Reference != null) @@ -167,10 +164,7 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (Reference != null) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiServer.cs b/src/Microsoft.OpenApi/Models/OpenApiServer.cs index a13a6fb2d..cc949aa6d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServer.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServer.cs @@ -56,10 +56,7 @@ public OpenApiServer(OpenApiServer server) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index 4512f76dc..1e38e7156 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -54,10 +54,7 @@ public OpenApiServerVariable(OpenApiServerVariable serverVariable) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiTag.cs b/src/Microsoft.OpenApi/Models/OpenApiTag.cs index a0bae5015..5c5bfd729 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiTag.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiTag.cs @@ -65,10 +65,7 @@ public OpenApiTag(OpenApiTag tag) /// public void SerializeAsV3(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (Reference != null) { @@ -106,10 +103,7 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) /// public void SerializeAsV2(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (Reference != null) { diff --git a/src/Microsoft.OpenApi/Models/OpenApiXml.cs b/src/Microsoft.OpenApi/Models/OpenApiXml.cs index 1fb18d508..20b0041d3 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiXml.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiXml.cs @@ -81,10 +81,7 @@ public void SerializeAsV2(IOpenApiWriter writer) private void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); writer.WriteStartObject(); diff --git a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs index 1a1f12a18..2efe00e46 100644 --- a/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs +++ b/src/Microsoft.OpenApi/Models/RuntimeExpressionAnyWrapper.cs @@ -67,10 +67,7 @@ public RuntimeExpression Expression /// public void WriteValue(IOpenApiWriter writer) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (_any != null) { diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index 488a437bc..b1ecc36d0 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -56,7 +56,7 @@ public class OpenApiUrlTreeNode /// true or false. public bool HasOperations(string label) { - Utils.CheckArgumentNullOrEmpty(label, nameof(label)); + Utils.CheckArgumentNullOrEmpty(label); return PathItems is not null && PathItems.TryGetValue(label, out var item) && item.Operations is not null && item.Operations.Any(); } @@ -87,8 +87,8 @@ public static OpenApiUrlTreeNode Create() /// The root node of the created directory structure. public static OpenApiUrlTreeNode Create(OpenApiDocument doc, string label) { - Utils.CheckArgumentNull(doc, nameof(doc)); - Utils.CheckArgumentNullOrEmpty(label, nameof(label)); + Utils.CheckArgumentNull(doc); + Utils.CheckArgumentNullOrEmpty(label); var root = Create(); @@ -113,8 +113,8 @@ public static OpenApiUrlTreeNode Create(OpenApiDocument doc, string label) /// Name tag for labelling related nodes in the directory structure. public void Attach(OpenApiDocument doc, string label) { - Utils.CheckArgumentNull(doc, nameof(doc)); - Utils.CheckArgumentNullOrEmpty(label, nameof(label)); + Utils.CheckArgumentNull(doc); + Utils.CheckArgumentNullOrEmpty(label); var paths = doc.Paths; if (paths != null) @@ -139,9 +139,9 @@ public OpenApiUrlTreeNode Attach(string path, OpenApiPathItem pathItem, string label) { - Utils.CheckArgumentNullOrEmpty(label, nameof(label)); - Utils.CheckArgumentNullOrEmpty(path, nameof(path)); - Utils.CheckArgumentNull(pathItem, nameof(pathItem)); + Utils.CheckArgumentNullOrEmpty(label); + Utils.CheckArgumentNullOrEmpty(path); + Utils.CheckArgumentNull(pathItem); if (path.StartsWith(RootPathSegment)) { @@ -218,7 +218,7 @@ private OpenApiUrlTreeNode Attach(IEnumerable segments, /// A dictionary of key value pairs that contain information about a node. public void AddAdditionalData(Dictionary> additionalData) { - Utils.CheckArgumentNull(additionalData, nameof(additionalData)); + Utils.CheckArgumentNull(additionalData); foreach (var item in additionalData) { diff --git a/src/Microsoft.OpenApi/Utils.cs b/src/Microsoft.OpenApi/Utils.cs index 07751a57c..e8b01b164 100644 --- a/src/Microsoft.OpenApi/Utils.cs +++ b/src/Microsoft.OpenApi/Utils.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using System.Runtime.CompilerServices; namespace Microsoft.OpenApi { @@ -17,7 +18,9 @@ internal static class Utils /// The input value. /// The input parameter name. /// The input value. - internal static T CheckArgumentNull(T value, string parameterName) where T : class + internal static T CheckArgumentNull( + T value, + [CallerArgumentExpression("value")] string parameterName = "") { return value ?? throw new ArgumentNullException(parameterName, $"Value cannot be null: {parameterName}"); } @@ -28,7 +31,9 @@ internal static T CheckArgumentNull(T value, string parameterName) where T : /// The input string value. /// The input parameter name. /// The input value. - internal static string CheckArgumentNullOrEmpty(string value, string parameterName) + internal static string CheckArgumentNullOrEmpty( + string value, + [CallerArgumentExpression("value")] string parameterName = "") { return string.IsNullOrEmpty(value) ? throw new ArgumentNullException(parameterName, $"Value cannot be null or empty: {parameterName}") : value; } diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index 84a054386..cd3f19fab 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -55,10 +55,7 @@ public IEnumerable Warnings /// Error to register. public void AddError(OpenApiValidatorError error) { - if (error == null) - { - throw Error.ArgumentNull(nameof(error)); - } + Utils.CheckArgumentNull(error); _errors.Add(error); } @@ -69,10 +66,7 @@ public void AddError(OpenApiValidatorError error) /// Error to register. public void AddWarning(OpenApiValidatorWarning warning) { - if (warning == null) - { - throw Error.ArgumentNull(nameof(warning)); - } + Utils.CheckArgumentNull(warning); _warnings.Add(warning); } diff --git a/src/Microsoft.OpenApi/Validations/ValidationRule.cs b/src/Microsoft.OpenApi/Validations/ValidationRule.cs index fdbf5c330..8917c5fca 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRule.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRule.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. using System; +using System.Globalization; using Microsoft.OpenApi.Interfaces; using Microsoft.OpenApi.Properties; @@ -39,7 +40,7 @@ public class ValidationRule : ValidationRule where T : IOpenApiElement /// Action to perform the validation. public ValidationRule(Action validate) { - _validate = validate ?? throw Error.ArgumentNull(nameof(validate)); + _validate = Utils.CheckArgumentNull(validate); } internal override Type ElementType @@ -49,10 +50,7 @@ internal override Type ElementType internal override void Evaluate(IValidationContext context, object item) { - if (context == null) - { - throw Error.ArgumentNull(nameof(context)); - } + Utils.CheckArgumentNull(context); if (item == null) { @@ -61,7 +59,7 @@ internal override void Evaluate(IValidationContext context, object item) if (!(item is T)) { - throw Error.Argument(string.Format(SRResource.InputItemShouldBeType, typeof(T).FullName)); + throw new ArgumentException(string.Format(SRResource.InputItemShouldBeType, typeof(T).FullName)); } T typedItem = (T)item; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs index 361da3b2a..f06114516 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterAnyExtensions.cs @@ -20,10 +20,7 @@ public static class OpenApiWriterAnyExtensions /// Version of the OpenAPI specification that that will be output. public static void WriteExtensions(this IOpenApiWriter writer, IDictionary extensions, OpenApiSpecVersion specVersion) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (extensions != null) { @@ -43,10 +40,7 @@ public static void WriteExtensions(this IOpenApiWriter writer, IDictionaryThe Any value public static void WriteAny(this IOpenApiWriter writer, T any) where T : IOpenApiAny { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); if (any == null) { @@ -79,15 +73,8 @@ public static void WriteAny(this IOpenApiWriter writer, T any) where T : IOpe private static void WriteArray(this IOpenApiWriter writer, OpenApiArray array) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } - - if (array == null) - { - throw Error.ArgumentNull(nameof(array)); - } + Utils.CheckArgumentNull(writer); + Utils.CheckArgumentNull(array); writer.WriteStartArray(); @@ -101,15 +88,8 @@ private static void WriteArray(this IOpenApiWriter writer, OpenApiArray array) private static void WriteObject(this IOpenApiWriter writer, OpenApiObject entity) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } - - if (entity == null) - { - throw Error.ArgumentNull(nameof(entity)); - } + Utils.CheckArgumentNull(writer); + Utils.CheckArgumentNull(entity); writer.WriteStartObject(); @@ -124,15 +104,8 @@ private static void WriteObject(this IOpenApiWriter writer, OpenApiObject entity private static void WritePrimitive(this IOpenApiWriter writer, IOpenApiPrimitive primitive) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } - - if (primitive == null) - { - throw Error.ArgumentNull(nameof(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/OpenApiWriterBase.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs index fe24f460c..d10b1be8c 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs @@ -392,10 +392,7 @@ private bool IsScopeType(ScopeType type) /// property name protected void VerifyCanWritePropertyName(string name) { - if (name == null) - { - throw Error.ArgumentNull(nameof(name)); - } + Utils.CheckArgumentNull(name); if (Scopes.Count == 0) { diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs index 08aeb4efd..e9156b7d1 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -404,33 +404,21 @@ private static void CheckArguments(IOpenApiWriter writer, string name, Action { CheckArguments(writer, name); - if (action == null) - { - throw Error.ArgumentNull(nameof(action)); - } + Utils.CheckArgumentNull(action); } private static void CheckArguments(IOpenApiWriter writer, string name, Action action) { CheckArguments(writer, name); - if (action == null) - { - throw Error.ArgumentNull(nameof(action)); - } + Utils.CheckArgumentNull(action); } private static void CheckArguments(IOpenApiWriter writer, string name) { - if (writer == null) - { - throw Error.ArgumentNull(nameof(writer)); - } + Utils.CheckArgumentNull(writer); - if (string.IsNullOrWhiteSpace(name)) - { - throw Error.ArgumentNullOrWhiteSpace(nameof(name)); - } + Utils.CheckArgumentNullOrEmpty(name); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/Resources.cs b/test/Microsoft.OpenApi.Readers.Tests/Resources.cs index 895e1ed3f..3c7184cc4 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Resources.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/Resources.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.IO; namespace Microsoft.OpenApi.Readers.Tests @@ -33,8 +34,7 @@ public static Stream GetStream(string fileName) if (stream == null) { - string message = Error.Format("The embedded resource '{0}' was not found.", path); - throw new FileNotFoundException(message, path); + throw new FileNotFoundException($"The embedded resource '{path}' was not found.", path); } return stream; From 6f63c622aa72abb6f9fb4366c422bc1e219d2d8f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 4 Oct 2023 06:36:47 +1100 Subject: [PATCH 04/61] Update src/Microsoft.OpenApi/Utils.cs Co-authored-by: Vincent Biret --- src/Microsoft.OpenApi/Utils.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Utils.cs b/src/Microsoft.OpenApi/Utils.cs index e8b01b164..3ef7788ba 100644 --- a/src/Microsoft.OpenApi/Utils.cs +++ b/src/Microsoft.OpenApi/Utils.cs @@ -33,7 +33,7 @@ internal static T CheckArgumentNull( /// The input value. internal static string CheckArgumentNullOrEmpty( string value, - [CallerArgumentExpression("value")] string parameterName = "") + [CallerArgumentExpression(nameof(value))] string parameterName = "") { return string.IsNullOrEmpty(value) ? throw new ArgumentNullException(parameterName, $"Value cannot be null or empty: {parameterName}") : value; } From 5c05d56f0178126f4f80dd03eb858736cb66a88b Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 21:11:16 +1100 Subject: [PATCH 05/61] Update CallerArgumentExpressionAttribute.cs --- src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs b/src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs index 60ef93911..8e4a6b3c4 100644 --- a/src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs +++ b/src/Microsoft.OpenApi/CallerArgumentExpressionAttribute.cs @@ -1,4 +1,5 @@ -using System.Diagnostics; +#if !NETCOREAPP3_1_OR_GREATER +using System.Diagnostics; using System.Diagnostics.CodeAnalysis; namespace System.Runtime.CompilerServices; @@ -14,3 +15,4 @@ public CallerArgumentExpressionAttribute(string parameterName) => public string ParameterName { get; } } +#endif From 2a7c75559aad4023c28dc37b4447a8094f7cfde2 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 21:46:42 +1100 Subject: [PATCH 06/61] use wildcard for test resources --- .../Microsoft.OpenApi.Readers.Tests.csproj | 297 +----------------- 1 file changed, 2 insertions(+), 295 deletions(-) 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 5ba3103fe..0284522af 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -6,255 +6,10 @@ ..\..\src\Microsoft.OpenApi.snk - - - - - - - - - - - - - Never - - - Never - - - Never - - - Never - - - Never - - - PreserveNewest - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - + Never - - Never - - - Never - - - Never - - - Never - - - Never - - - - - - - - Never - - - Never - - - Never - - - Never - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - - Never - - - Never - - - Never - - - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - Never - - - - + Never @@ -274,53 +29,5 @@ - - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - Never - - - Never - - - PreserveNewest - - - Never - - - Never - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - \ No newline at end of file From 697cc055b5bb60340666f528eaf508214e2dd895 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 21:48:25 +1100 Subject: [PATCH 07/61] simplify UtilityFiles with wildcards --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 32 +------------------ 1 file changed, 1 insertion(+), 31 deletions(-) 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..c39d2cae9 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -25,37 +25,7 @@ - - Always - - - - - - Always - - - Always - - - Always - - - Always - - - Always - - - PreserveNewest - - - Always - - - Always - - + Always From 0353793610d575cd49f71510c6779f108a0a44b3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 21:51:41 +1100 Subject: [PATCH 08/61] Update Microsoft.OpenApi.Hidi.Tests.csproj --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 3 +++ 1 file changed, 3 insertions(+) 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 c39d2cae9..77c9b8001 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -28,6 +28,9 @@ Always + + Always + From 9068e562f1cdfaff9e5424bd0efe6aca0423903a Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 22:10:02 +1100 Subject: [PATCH 09/61] . --- src/Microsoft.OpenApi/Utils.cs | 2 +- .../Expressions/HeaderExpressionTests.cs | 2 +- test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs | 2 +- .../Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs | 2 +- .../Expressions/RuntimeExpressionTests.cs | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi/Utils.cs b/src/Microsoft.OpenApi/Utils.cs index 3ef7788ba..10d5595f8 100644 --- a/src/Microsoft.OpenApi/Utils.cs +++ b/src/Microsoft.OpenApi/Utils.cs @@ -35,7 +35,7 @@ internal static string CheckArgumentNullOrEmpty( string value, [CallerArgumentExpression(nameof(value))] string parameterName = "") { - return string.IsNullOrEmpty(value) ? throw new ArgumentNullException(parameterName, $"Value cannot be null or empty: {parameterName}") : value; + return string.IsNullOrWhiteSpace(value) ? throw new ArgumentNullException(parameterName, $"Value cannot be null or empty: {parameterName}") : value; } } } diff --git a/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs index 859c409b6..abe1cf929 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/HeaderExpressionTests.cs @@ -20,7 +20,7 @@ public void HeaderExpressionConstructorThrows(string token) Action test = () => new HeaderExpression(token); // Act - Assert.Throws("token", test); + Assert.Throws("token", test); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs index 235b11102..3ff084f77 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/PathExpressionTests.cs @@ -20,7 +20,7 @@ public void PathExpressionConstructorThrows(string name) Action test = () => new PathExpression(name); // Act - Assert.Throws("name", test); + Assert.Throws("name", test); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs index 3a741b80c..e4d215496 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/QueryExpressionTests.cs @@ -20,7 +20,7 @@ public void QueryExpressionConstructorThrows(string name) Action test = () => new QueryExpression(name); // Act - Assert.Throws("name", test); + Assert.Throws("name", test); } [Fact] diff --git a/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs b/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs index f9ada6dbd..9b43b93ec 100644 --- a/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs +++ b/test/Microsoft.OpenApi.Tests/Expressions/RuntimeExpressionTests.cs @@ -25,7 +25,7 @@ public void BuildRuntimeExpressionThrowsNullOrWhiteSpace(string expression) Action test = () => RuntimeExpression.Build(expression); // Assert - Assert.Throws("expression", test); + Assert.Throws("expression", test); } [Theory] From e4442679aa891cedca3e12ff5ddf8aab9b7544ec Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 22:42:49 +1100 Subject: [PATCH 10/61] remove some redundant qualifiers --- src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs | 2 +- src/Microsoft.OpenApi/Expressions/CompositeExpression.cs | 2 +- .../V3Tests/OpenApiOperationTests.cs | 2 +- test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs | 2 +- test/Microsoft.OpenApi.SmokeTests/GraphTests.cs | 2 +- .../OpenApiPrimaryErrorMessageExtensionTests.cs | 4 ++-- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs index bbc9e30b8..34acc3aee 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs @@ -36,7 +36,7 @@ public override List CreateList(Func map) public override List CreateListOfAny() { - return _nodeList.Select(n => ParseNode.Create(Context, n).CreateAny()) + return _nodeList.Select(n => Create(Context, n).CreateAny()) .Where(i => i != null) .ToList(); } diff --git a/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs b/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs index 98c5e069c..8fd1a16db 100644 --- a/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs @@ -34,7 +34,7 @@ public CompositeExpression(string expression) foreach (var item in matches.Cast()) { var value = item.Groups["exp"].Captures.Cast().First().Value; - ContainedExpressions.Add(RuntimeExpression.Build(value)); + ContainedExpressions.Add(Build(value)); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs index db2f3907c..553828aa8 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs @@ -21,7 +21,7 @@ public void OperationWithSecurityRequirementShouldReferenceSecurityScheme() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "securedOperation.yaml")); var openApiDoc = new OpenApiStreamReader().Read(stream, out var diagnostic); - var securityRequirement = openApiDoc.Paths["/"].Operations[Models.OperationType.Get].Security.First(); + var securityRequirement = openApiDoc.Paths["/"].Operations[OperationType.Get].Security.First(); Assert.Same(securityRequirement.Keys.First(), openApiDoc.Components.SecuritySchemes.First().Value); } diff --git a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs index 079ab6569..8cc20e6cd 100644 --- a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs +++ b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs @@ -27,7 +27,7 @@ public ApisGuruTests(ITestOutputHelper output) static ApisGuruTests() { - System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; _httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip diff --git a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs index 9bfebed25..f007acb86 100644 --- a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs +++ b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs @@ -19,7 +19,7 @@ public class GraphTests public GraphTests(ITestOutputHelper output) { _output = output; - System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; _httpClient = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs index b78ed1793..5ef75d8a9 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtensionTests.cs @@ -16,7 +16,7 @@ public class OpenApiPrimaryErrorMessageExtensionTests public void ExtensionNameMatchesExpected() { // Act - string name = Microsoft.OpenApi.MicrosoftExtensions.OpenApiPrimaryErrorMessageExtension.Name; + string name = MicrosoftExtensions.OpenApiPrimaryErrorMessageExtension.Name; string expectedName = "x-ms-primary-error-message"; // Assert @@ -50,7 +50,7 @@ public void ParsesValue() var value = new OpenApiBoolean(true); // Act - var extension = Microsoft.OpenApi.MicrosoftExtensions.OpenApiPrimaryErrorMessageExtension.Parse(value); + var extension = MicrosoftExtensions.OpenApiPrimaryErrorMessageExtension.Parse(value); // Assert Assert.True(extension.IsPrimaryErrorMessage); From 51f8923ddf4849f4a8b81ba33d644b8455d42ec8 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 22:46:48 +1100 Subject: [PATCH 11/61] use some target typed new --- .../Formatters/PowerShellFormatter.cs | 6 +- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 16 +- .../Options/HidiOptions.cs | 2 +- .../OpenApiDiagnostic.cs | 4 +- .../OpenApiReaderSettings.cs | 2 +- .../OpenApiStreamReader.cs | 2 +- .../OpenApiTextReaderReader.cs | 14 +- .../OpenApiYamlDocumentReader.cs | 14 +- .../ParseNodes/ListNode.cs | 4 +- .../ParseNodes/MapNode.cs | 14 +- .../ParseNodes/PropertyNode.cs | 11 +- .../ParseNodes/RootNode.cs | 2 +- .../ParsingContext.cs | 22 +- .../Services/DefaultStreamLoader.cs | 2 +- .../OpenApiRemoteReferenceCollector.cs | 2 +- .../Services/OpenApiWorkspaceLoader.cs | 4 +- .../V2/OpenApiContactDeserializer.cs | 6 +- .../V2/OpenApiDocumentDeserializer.cs | 18 +- .../V2/OpenApiExternalDocsDeserializer.cs | 7 +- .../V2/OpenApiHeaderDeserializer.cs | 12 +- .../V2/OpenApiInfoDeserializer.cs | 6 +- .../V2/OpenApiLicenseDeserializer.cs | 6 +- .../V2/OpenApiOperationDeserializer.cs | 13 +- .../V2/OpenApiParameterDeserializer.cs | 18 +- .../V2/OpenApiPathItemDeserializer.cs | 6 +- .../V2/OpenApiPathsDeserializer.cs | 4 +- .../V2/OpenApiResponseDeserializer.cs | 10 +- .../V2/OpenApiSchemaDeserializer.cs | 16 +- .../OpenApiSecurityRequirementDeserializer.cs | 4 +- .../V2/OpenApiSecuritySchemeDeserializer.cs | 18 +- .../V2/OpenApiTagDeserializer.cs | 4 +- .../V2/OpenApiV2Deserializer.cs | 5 +- .../V2/OpenApiV2VersionService.cs | 10 +- .../V2/OpenApiXmlDeserializer.cs | 6 +- .../V3/OpenApiCallbackDeserializer.cs | 5 +- .../V3/OpenApiComponentsDeserializer.cs | 4 +- .../V3/OpenApiContactDeserializer.cs | 6 +- .../V3/OpenApiDiscriminatorDeserializer.cs | 5 +- .../V3/OpenApiDocumentDeserializer.cs | 6 +- .../V3/OpenApiEncodingDeserializer.cs | 4 +- .../V3/OpenApiExampleDeserializer.cs | 4 +- .../V3/OpenApiExternalDocsDeserializer.cs | 7 +- .../V3/OpenApiHeaderDeserializer.cs | 4 +- .../V3/OpenApiInfoDeserializer.cs | 6 +- .../V3/OpenApiLicenseDeserializer.cs | 6 +- .../V3/OpenApiLinkDeserializer.cs | 4 +- .../V3/OpenApiMediaTypeDeserializer.cs | 14 +- .../V3/OpenApiOAuthFlowDeserializer.cs | 10 +- .../V3/OpenApiOAuthFlowsDeserializer.cs | 4 +- .../V3/OpenApiOperationDeserializer.cs | 6 +- .../V3/OpenApiParameterDeserializer.cs | 14 +- .../V3/OpenApiPathItemDeserializer.cs | 6 +- .../V3/OpenApiPathsDeserializer.cs | 4 +- .../V3/OpenApiRequestBodyDeserializer.cs | 4 +- .../V3/OpenApiResponseDeserializer.cs | 4 +- .../V3/OpenApiResponsesDeserializer.cs | 4 +- .../V3/OpenApiSchemaDeserializer.cs | 16 +- .../OpenApiSecurityRequirementDeserializer.cs | 4 +- .../V3/OpenApiSecuritySchemeDeserializer.cs | 6 +- .../V3/OpenApiServerDeserializer.cs | 4 +- .../V3/OpenApiServerVariableDeserializer.cs | 4 +- .../V3/OpenApiTagDeserializer.cs | 4 +- .../V3/OpenApiV3Deserializer.cs | 10 +- .../V3/OpenApiV3VersionService.cs | 8 +- .../V3/OpenApiXmlDeserializer.cs | 6 +- src/Microsoft.OpenApi.Workbench/MainModel.cs | 11 +- .../MainWindow.xaml.cs | 2 +- src/Microsoft.OpenApi/Error.cs | 10 +- .../Expressions/CompositeExpression.cs | 4 +- .../Expressions/SourceExpression.cs | 2 +- .../Extensions/OpenAPIWriterExtensions.cs | 2 +- .../Extensions/OpenApiTypeMapper.cs | 60 +- src/Microsoft.OpenApi/JsonPointer.cs | 2 +- .../OpenApiPrimaryErrorMessageExtension.cs | 2 +- .../OpenApiReservedParameterExtension.cs | 2 +- .../Models/OpenApiCallback.cs | 4 +- .../Models/OpenApiConstants.cs | 6 +- .../Models/OpenApiDocument.cs | 4 +- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 2 +- .../Models/OpenApiOperation.cs | 8 +- .../Models/OpenApiRequestBody.cs | 2 +- .../Models/OpenApiServerVariable.cs | 4 +- .../Services/CopyReferences.cs | 2 +- .../Services/LoopDetector.cs | 8 +- .../Services/OpenApiFilterService.cs | 12 +- .../Services/OpenApiReferenceResolver.cs | 6 +- .../Services/OpenApiUrlTreeNode.cs | 2 +- .../Services/OpenApiVisitorBase.cs | 4 +- .../Services/OpenApiWalker.cs | 4 +- .../Services/OpenApiWorkspace.cs | 14 +- .../Services/OperationSearch.cs | 4 +- .../Rules/OpenApiComponentsRules.cs | 4 +- .../Validations/Rules/OpenApiContactRules.cs | 2 +- .../Validations/Rules/OpenApiDocumentRules.cs | 2 +- .../Rules/OpenApiExtensionRules.cs | 2 +- .../Rules/OpenApiExternalDocsRules.cs | 2 +- .../Validations/Rules/OpenApiHeaderRules.cs | 2 +- .../Validations/Rules/OpenApiInfoRules.cs | 2 +- .../Validations/Rules/OpenApiLicenseRules.cs | 2 +- .../Rules/OpenApiMediaTypeRules.cs | 2 +- .../Rules/OpenApiOAuthFlowRules.cs | 2 +- .../Rules/OpenApiParameterRules.cs | 8 +- .../Validations/Rules/OpenApiPathsRules.cs | 2 +- .../Validations/Rules/OpenApiResponseRules.cs | 2 +- .../Rules/OpenApiResponsesRules.cs | 4 +- .../Validations/Rules/OpenApiSchemaRules.cs | 4 +- .../Validations/Rules/OpenApiServerRules.cs | 2 +- .../Validations/Rules/OpenApiTagRules.cs | 2 +- .../Validations/ValidationRuleSet.cs | 4 +- .../Writers/OpenApiWriterBase.cs | 4 +- .../Writers/OpenApiWriterSettings.cs | 2 +- .../Formatters/PowerShellFormatterTests.cs | 16 +- .../Services/OpenApiFilterServiceTests.cs | 2 +- .../Services/OpenApiServiceTests.cs | 10 +- .../UtilityFiles/OpenApiDocumentMock.cs | 172 +++--- .../OpenApiDiagnosticTests.cs | 8 +- .../OpenApiStreamReaderTests.cs | 4 +- .../OpenApiWorkspaceStreamTests.cs | 10 +- .../ParseNodeTests.cs | 4 +- .../ParseNodes/OpenApiAnyConverterTests.cs | 68 +-- .../ConvertToOpenApiReferenceV2Tests.cs | 2 +- .../ConvertToOpenApiReferenceV3Tests.cs | 2 +- .../TryLoadReferenceV2Tests.cs | 30 +- .../TestHelper.cs | 4 +- .../V2Tests/OpenApiContactTests.cs | 3 +- .../V2Tests/OpenApiDocumentTests.cs | 61 +- .../V2Tests/OpenApiHeaderTests.cs | 4 +- .../V2Tests/OpenApiOperationTests.cs | 102 ++-- .../V2Tests/OpenApiParameterTests.cs | 24 +- .../V2Tests/OpenApiPathItemTests.cs | 86 +-- .../V2Tests/OpenApiSecuritySchemeTests.cs | 25 +- .../V2Tests/OpenApiServerTests.cs | 45 +- .../V3Tests/OpenApiCallbackTests.cs | 70 +-- .../V3Tests/OpenApiContactTests.cs | 3 +- .../V3Tests/OpenApiDocumentTests.cs | 365 ++++++------ .../V3Tests/OpenApiEncodingTests.cs | 4 +- .../V3Tests/OpenApiInfoTests.cs | 21 +- .../V3Tests/OpenApiMediaTypeTests.cs | 8 +- .../V3Tests/OpenApiOperationTests.cs | 6 +- .../V3Tests/OpenApiParameterTests.cs | 36 +- .../V3Tests/OpenApiSchemaTests.cs | 88 +-- .../V3Tests/OpenApiSecuritySchemeTests.cs | 9 +- .../V3Tests/OpenApiXmlTests.cs | 3 +- test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs | 6 +- .../GraphTests.cs | 6 +- .../OpenApiDeprecationExtensionTests.cs | 12 +- .../Models/OpenApiCallbackTests.cs | 40 +- .../Models/OpenApiComponentsTests.cs | 91 ++- .../Models/OpenApiContactTests.cs | 7 +- .../Models/OpenApiDocumentTests.cs | 548 +++++++++--------- .../Models/OpenApiEncodingTests.cs | 4 +- .../Models/OpenApiExampleTests.cs | 12 +- .../Models/OpenApiExternalDocsTests.cs | 7 +- .../Models/OpenApiHeaderTests.cs | 23 +- .../Models/OpenApiInfoTests.cs | 7 +- .../Models/OpenApiLicenseTests.cs | 9 +- .../Models/OpenApiLinkTests.cs | 24 +- .../Models/OpenApiMediaTypeTests.cs | 12 +- .../Models/OpenApiOAuthFlowTests.cs | 15 +- .../Models/OpenApiOAuthFlowsTests.cs | 21 +- .../Models/OpenApiOperationTests.cs | 109 ++-- .../Models/OpenApiParameterTests.cs | 58 +- .../Models/OpenApiRequestBodyTests.cs | 20 +- .../Models/OpenApiResponseTests.cs | 48 +- .../Models/OpenApiSchemaTests.cs | 89 ++- .../Models/OpenApiSecurityRequirementTests.cs | 38 +- .../Models/OpenApiSecuritySchemeTests.cs | 49 +- .../Models/OpenApiServerTests.cs | 12 +- .../Models/OpenApiServerVariableTests.cs | 7 +- .../Models/OpenApiTagTests.cs | 24 +- .../Models/OpenApiXmlTests.cs | 7 +- .../PublicApi/PublicApiTests.cs | 2 +- .../Services/OpenApiUrlTreeNodeTests.cs | 82 +-- .../Services/OpenApiValidatorTests.cs | 24 +- .../OpenApiHeaderValidationTests.cs | 14 +- .../OpenApiMediaTypeValidationTests.cs | 14 +- .../OpenApiParameterValidationTests.cs | 18 +- .../OpenApiReferenceValidationTests.cs | 40 +- .../OpenApiSchemaValidationTests.cs | 30 +- .../Visitors/InheritanceTests.cs | 2 +- .../Walkers/WalkerLocationTests.cs | 52 +- .../Workspaces/OpenApiReferencableTests.cs | 28 +- .../Workspaces/OpenApiWorkspaceTests.cs | 50 +- .../Writers/OpenApiJsonWriterTests.cs | 12 +- .../OpenApiWriterAnyExtensionsTests.cs | 2 +- .../OpenApiWriterSpecialCharacterTests.cs | 2 +- .../Writers/OpenApiYamlWriterTests.cs | 42 +- 187 files changed, 1857 insertions(+), 1879 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs index 183de1691..d473fcd58 100644 --- a/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs +++ b/src/Microsoft.OpenApi.Hidi/Formatters/PowerShellFormatter.cs @@ -163,10 +163,10 @@ private static IList ResolveFunctionParameters(IList options.TerseOutput ? new OpenApiJsonWriter(textWriter, settings, options.TerseOutput) : new OpenApiJsonWriter(textWriter, settings, false), + OpenApiFormat.Json => options.TerseOutput ? new(textWriter, settings, options.TerseOutput) : new OpenApiJsonWriter(textWriter, settings, false), OpenApiFormat.Yaml => new OpenApiYamlWriter(textWriter, settings), _ => throw new ArgumentException("Unknown format"), }; @@ -368,11 +368,11 @@ private static async Task ParseOpenApi(string openApiFile, bool inli { stopwatch.Start(); - result = await new OpenApiStreamReader(new OpenApiReaderSettings - { + result = await new OpenApiStreamReader(new() + { LoadExternalRefs = inlineExternal, BaseUrl = openApiFile.StartsWith("http", StringComparison.OrdinalIgnoreCase) ? - new Uri(openApiFile) : + new(openApiFile) : new Uri("file://" + new FileInfo(openApiFile).DirectoryName + Path.DirectorySeparatorChar) } ).ReadAsync(stream, cancellationToken).ConfigureAwait(false); @@ -459,7 +459,7 @@ private static Dictionary> EnumerateJsonDocument(JsonElemen } else { - paths.Add(path, new List {method}); + paths.Add(path, new() {method}); } } else @@ -741,7 +741,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C outputFolder.Create(); } // Write OpenAPI to Output folder - options.Output = new FileInfo(Path.Combine(options.OutputFolder, "openapi.json")); + options.Output = new(Path.Combine(options.OutputFolder, "openapi.json")); options.TerseOutput = true; WriteOpenApi(options, OpenApiFormat.Json, OpenApiSpecVersion.OpenApi3_0, document, logger); @@ -762,7 +762,7 @@ internal static async Task PluginManifest(HidiOptions options, ILogger logger, C // Write OpenAIPluginManifest to Output folder var manifestFile = new FileInfo(Path.Combine(options.OutputFolder, "ai-plugin.json")); using var file = new FileStream(manifestFile.FullName, FileMode.Create); - using var jsonWriter = new Utf8JsonWriter(file, new JsonWriterOptions { Indented = true }); + using var jsonWriter = new Utf8JsonWriter(file, new() { Indented = true }); manifest.Write(jsonWriter); await jsonWriter.FlushAsync(cancellationToken).ConfigureAwait(false); } diff --git a/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs b/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs index d2a2bfe40..fca97c87f 100644 --- a/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs +++ b/src/Microsoft.OpenApi.Hidi/Options/HidiOptions.cs @@ -53,7 +53,7 @@ private void ParseHidiOptions(ParseResult parseResult, CommandOptions options) LogLevel = parseResult.GetValueForOption(options.LogLevelOption); InlineLocal = parseResult.GetValueForOption(options.InlineLocalOption); InlineExternal = parseResult.GetValueForOption(options.InlineExternalOption); - FilterOptions = new FilterOptions + FilterOptions = new() { FilterByOperationIds = parseResult.GetValueForOption(options.FilterByOperationIdsOption), FilterByTags = parseResult.GetValueForOption(options.FilterByTagsOption), diff --git a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs index 1c70db887..509358174 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiDiagnostic.cs @@ -39,12 +39,12 @@ public void AppendDiagnostic(OpenApiDiagnostic diagnosticToAdd, string fileNameT foreach (var err in diagnosticToAdd.Errors) { var errMsgWithFileName = fileNameIsSupplied ? $"[File: {fileNameToAdd}] {err.Message}" : err.Message; - Errors.Add(new OpenApiError(err.Pointer, errMsgWithFileName)); + Errors.Add(new(err.Pointer, errMsgWithFileName)); } foreach (var warn in diagnosticToAdd.Warnings) { var warnMsgWithFileName = fileNameIsSupplied ? $"[File: {fileNameToAdd}] {warn.Message}" : warn.Message; - Warnings.Add(new OpenApiError(warn.Pointer, warnMsgWithFileName)); + Warnings.Add(new(warn.Pointer, warnMsgWithFileName)); } } } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs index 71a18e137..5d251802f 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiReaderSettings.cs @@ -50,7 +50,7 @@ public class OpenApiReaderSettings /// /// Dictionary of parsers for converting extensions into strongly typed classes /// - public Dictionary> ExtensionParsers { get; set; } = new Dictionary>(); + public Dictionary> ExtensionParsers { get; set; } = new(); /// /// Rules to use for validating OpenAPI specification. If none are provided a default set of rules are applied. diff --git a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs index 4776fcce4..e96aa4b12 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiStreamReader.cs @@ -68,7 +68,7 @@ public async Task ReadAsync(Stream input, CancellationToken cancella { // Buffer stream so that OpenApiTextReaderReader can process it synchronously // YamlDocument doesn't support async reading. - bufferedStream = new MemoryStream(); + bufferedStream = new(); await input.CopyToAsync(bufferedStream, 81920, cancellationToken); bufferedStream.Position = 0; } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs index 68550135d..dff20fc7f 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiTextReaderReader.cs @@ -46,9 +46,9 @@ public OpenApiDocument Read(TextReader input, out OpenApiDiagnostic diagnostic) } catch (YamlException ex) { - diagnostic = new OpenApiDiagnostic(); - diagnostic.Errors.Add(new OpenApiError($"#line={ex.Start.Line}", ex.Message)); - return new OpenApiDocument(); + diagnostic = new(); + diagnostic.Errors.Add(new($"#line={ex.Start.Line}", ex.Message)); + return new(); } return new OpenApiYamlDocumentReader(this._settings).Read(yamlDocument, out diagnostic); @@ -72,8 +72,8 @@ public async Task ReadAsync(TextReader input, CancellationToken canc catch (YamlException ex) { var diagnostic = new OpenApiDiagnostic(); - diagnostic.Errors.Add(new OpenApiError($"#line={ex.Start.Line}", ex.Message)); - return new ReadResult + diagnostic.Errors.Add(new($"#line={ex.Start.Line}", ex.Message)); + return new() { OpenApiDocument = null, OpenApiDiagnostic = diagnostic @@ -101,8 +101,8 @@ public T ReadFragment(TextReader input, OpenApiSpecVersion version, out OpenA } catch (YamlException ex) { - diagnostic = new OpenApiDiagnostic(); - diagnostic.Errors.Add(new OpenApiError($"#line={ex.Start.Line}", ex.Message)); + diagnostic = new(); + diagnostic.Errors.Add(new($"#line={ex.Start.Line}", ex.Message)); return default; } diff --git a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs index 03076d6c7..c0626aa17 100644 --- a/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs +++ b/src/Microsoft.OpenApi.Readers/OpenApiYamlDocumentReader.cs @@ -42,7 +42,7 @@ public OpenApiYamlDocumentReader(OpenApiReaderSettings settings = null) /// Instance of newly created OpenApiDocument public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic) { - diagnostic = new OpenApiDiagnostic(); + diagnostic = new(); var context = new ParsingContext(diagnostic) { ExtensionParsers = _settings.ExtensionParsers, @@ -65,7 +65,7 @@ public OpenApiDocument Read(YamlDocument input, out OpenApiDiagnostic diagnostic } catch (OpenApiException ex) { - diagnostic.Errors.Add(new OpenApiError(ex)); + diagnostic.Errors.Add(new(ex)); } // Validate the document @@ -115,7 +115,7 @@ public async Task ReadAsync(YamlDocument input, CancellationToken ca } catch (OpenApiException ex) { - diagnostic.Errors.Add(new OpenApiError(ex)); + diagnostic.Errors.Add(new(ex)); } // Validate the document @@ -132,7 +132,7 @@ public async Task ReadAsync(YamlDocument input, CancellationToken ca } } - return new ReadResult + return new() { OpenApiDocument = document, OpenApiDiagnostic = diagnostic @@ -147,7 +147,7 @@ private Task LoadExternalRefs(OpenApiDocument document, Cance // Load this root document into the workspace var streamLoader = new DefaultStreamLoader(_settings.BaseUrl); var workspaceLoader = new OpenApiWorkspaceLoader(openApiWorkSpace, _settings.CustomExternalLoader ?? streamLoader, _settings); - return workspaceLoader.LoadAsync(new OpenApiReference { ExternalResource = "/" }, document, null, cancellationToken); + return workspaceLoader.LoadAsync(new() { ExternalResource = "/" }, document, null, cancellationToken); } private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument document) @@ -181,7 +181,7 @@ private void ResolveReferences(OpenApiDiagnostic diagnostic, OpenApiDocument doc /// Instance of newly created OpenApiDocument public T ReadFragment(YamlDocument input, OpenApiSpecVersion version, out OpenApiDiagnostic diagnostic) where T : IOpenApiElement { - diagnostic = new OpenApiDiagnostic(); + diagnostic = new(); var context = new ParsingContext(diagnostic) { ExtensionParsers = _settings.ExtensionParsers @@ -195,7 +195,7 @@ public T ReadFragment(YamlDocument input, OpenApiSpecVersion version, out Ope } catch (OpenApiException ex) { - diagnostic.Errors.Add(new OpenApiError(ex)); + diagnostic.Errors.Add(new(ex)); } // Validate the element diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs index bbc9e30b8..bfb9a554f 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs @@ -29,7 +29,7 @@ public override List CreateList(Func map) $"Expected list at line {_nodeList.Start.Line} while parsing {typeof(T).Name}", _nodeList); } - return _nodeList.Select(n => map(new MapNode(Context, n as YamlMappingNode))) + return _nodeList.Select(n => map(new(Context, n as YamlMappingNode))) .Where(i => i != null) .ToList(); } @@ -49,7 +49,7 @@ public override List CreateSimpleList(Func map) $"Expected list at line {_nodeList.Start.Line} while parsing {typeof(T).Name}", _nodeList); } - return _nodeList.Select(n => map(new ValueNode(Context, n))).ToList(); + return _nodeList.Select(n => map(new(Context, n))).ToList(); } public IEnumerator GetEnumerator() diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs index b5107b743..c924311d7 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs @@ -49,7 +49,7 @@ public PropertyNode this[string key] { if (this._node.Children.TryGetValue(new YamlScalarNode(key), out var node)) { - return new PropertyNode(Context, key, node); + return new(Context, key, node); } return null; @@ -74,7 +74,7 @@ public override Dictionary CreateMap(Func map) Context.StartObject(key); value = n.Value as YamlMappingNode == null ? default - : map(new MapNode(Context, n.Value as YamlMappingNode)); + : map(new(Context, n.Value as YamlMappingNode)); } finally { @@ -110,7 +110,7 @@ public override Dictionary CreateMapWithReference( Context.StartObject(key); entry = ( key: key, - value: map(new MapNode(Context, (YamlMappingNode)n.Value)) + value: map(new(Context, (YamlMappingNode)n.Value)) ); if (entry.value == null) { @@ -119,7 +119,7 @@ public override Dictionary CreateMapWithReference( // If the component isn't a reference to another component, then point it to itself. if (entry.value.Reference == null) { - entry.value.Reference = new OpenApiReference + entry.value.Reference = new() { Type = referenceType, Id = entry.key @@ -155,7 +155,7 @@ public override Dictionary CreateSimpleMap(Func map) { throw new OpenApiReaderException($"Expected scalar while parsing {typeof(T).Name}", Context); } - return (key, value: map(new ValueNode(Context, (YamlScalarNode)n.Value))); + return (key, value: map(new(Context, (YamlScalarNode)n.Value))); } finally { Context.EndObject(); } @@ -175,14 +175,14 @@ IEnumerator IEnumerable.GetEnumerator() public override string GetRaw() { - var x = new Serializer(new SerializerSettings(new JsonSchema()) { EmitJsonComptible = true }); + var x = new Serializer(new(new JsonSchema()) { EmitJsonComptible = true }); return x.Serialize(_node); } public T GetReferencedObject(ReferenceType referenceType, string referenceId) where T : IOpenApiReferenceable, new() { - return new T + return new() { UnresolvedReference = true, Reference = Context.VersionService.ConvertToOpenApiReference(referenceId, referenceType) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs index 7927520c7..6a059c348 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/PropertyNode.cs @@ -6,7 +6,6 @@ using System.Linq; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Exceptions; -using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.Exceptions; using SharpYaml.Serialization; @@ -39,12 +38,12 @@ public void ParseField( } catch (OpenApiReaderException ex) { - Context.Diagnostic.Errors.Add(new OpenApiError(ex)); + Context.Diagnostic.Errors.Add(new(ex)); } catch (OpenApiException ex) { ex.Pointer = Context.GetLocation(); - Context.Diagnostic.Errors.Add(new OpenApiError(ex)); + Context.Diagnostic.Errors.Add(new(ex)); } finally { @@ -63,12 +62,12 @@ public void ParseField( } catch (OpenApiReaderException ex) { - Context.Diagnostic.Errors.Add(new OpenApiError(ex)); + Context.Diagnostic.Errors.Add(new(ex)); } catch (OpenApiException ex) { ex.Pointer = Context.GetLocation(); - Context.Diagnostic.Errors.Add(new OpenApiError(ex)); + Context.Diagnostic.Errors.Add(new(ex)); } finally { @@ -78,7 +77,7 @@ public void ParseField( else { Context.Diagnostic.Errors.Add( - new OpenApiError("", $"{Name} is not a valid property at {Context.GetLocation()}")); + new("", $"{Name} is not a valid property at {Context.GetLocation()}")); } } } diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs index d9f18603f..f70b9ca99 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/RootNode.cs @@ -32,7 +32,7 @@ public ParseNode Find(JsonPointer referencePointer) public MapNode GetMap() { - return new MapNode(Context, (YamlMappingNode)_yamlDocument.RootNode); + return new(Context, (YamlMappingNode)_yamlDocument.RootNode); } } } diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index 781a16ed8..93a7d6564 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -21,13 +21,13 @@ namespace Microsoft.OpenApi.Readers /// public class ParsingContext { - private readonly Stack _currentLocation = new Stack(); - private readonly Dictionary _tempStorage = new Dictionary(); - private readonly Dictionary> _scopedTempStorage = new Dictionary>(); - private readonly Dictionary> _loopStacks = new Dictionary>(); - internal Dictionary> ExtensionParsers { get; set; } = new Dictionary>(); + private readonly Stack _currentLocation = new(); + private readonly Dictionary _tempStorage = new(); + private readonly Dictionary> _scopedTempStorage = new(); + private readonly Dictionary> _loopStacks = new(); + internal Dictionary> ExtensionParsers { get; set; } = new(); internal RootNode RootNode { get; set; } - internal List Tags { get; private set; } = new List(); + internal List Tags { get; private set; } = new(); internal Uri BaseUrl { get; set; } internal List DefaultContentType { get; set; } @@ -52,7 +52,7 @@ public ParsingContext(OpenApiDiagnostic diagnostic) /// An OpenApiDocument populated based on the passed yamlDocument internal OpenApiDocument Parse(YamlDocument yamlDocument) { - RootNode = new RootNode(this, yamlDocument); + RootNode = new(this, yamlDocument); var inputVersion = GetVersion(RootNode); @@ -112,14 +112,14 @@ internal T ParseFragment(YamlDocument yamlDocument, OpenApiSpecVersion versio /// private static string GetVersion(RootNode rootNode) { - var versionNode = rootNode.Find(new JsonPointer("/openapi")); + var versionNode = rootNode.Find(new("/openapi")); if (versionNode != null) { return versionNode.GetScalarValue(); } - versionNode = rootNode.Find(new JsonPointer("/swagger")); + versionNode = rootNode.Find(new("/swagger")); return versionNode?.GetScalarValue(); } @@ -177,7 +177,7 @@ public void SetTempStorage(string key, object value, object scope = null) } else if (!_scopedTempStorage.TryGetValue(scope, out storage)) { - storage = _scopedTempStorage[scope] = new Dictionary(); + storage = _scopedTempStorage[scope] = new(); } if (value == null) @@ -208,7 +208,7 @@ public bool PushLoop(string loopId, string key) { if (!_loopStacks.TryGetValue(loopId, out var stack)) { - stack = new Stack(); + stack = new(); _loopStacks.Add(loopId, stack); } diff --git a/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs b/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs index 69f2a49de..5ef282156 100644 --- a/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Services/DefaultStreamLoader.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.Services internal class DefaultStreamLoader : IStreamLoader { private readonly Uri baseUrl; - private HttpClient _httpClient = new HttpClient(); + private HttpClient _httpClient = new(); public DefaultStreamLoader(Uri baseUrl) { diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs index c42d39690..90cd3632c 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.Services /// internal class OpenApiRemoteReferenceCollector : OpenApiVisitorBase { - private Dictionary _references = new Dictionary(); + private Dictionary _references = new(); /// /// List of external references collected from OpenApiDocument diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs index 847e73ce1..c2d1cfe3c 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiWorkspaceLoader.cs @@ -34,7 +34,7 @@ internal async Task LoadAsync(OpenApiReference reference, Ope if (diagnostic is null) { - diagnostic = new OpenApiDiagnostic(); + diagnostic = new(); } // Walk references @@ -43,7 +43,7 @@ internal async Task LoadAsync(OpenApiReference reference, Ope // If not already in workspace, load it and process references if (!_workspace.Contains(item.ExternalResource)) { - var input = await _loader.LoadAsync(new Uri(item.ExternalResource, UriKind.RelativeOrAbsolute)); + var input = await _loader.LoadAsync(new(item.ExternalResource, UriKind.RelativeOrAbsolute)); var result = await reader.ReadAsync(input, cancellationToken); // Merge diagnostics if (result.OpenApiDiagnostic != null) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs index c25f5d0c8..43824c244 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiContactDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static FixedFieldMap _contactFixedFields = new FixedFieldMap + private static FixedFieldMap _contactFixedFields = new() { { "name", (o, n) => @@ -25,7 +25,7 @@ internal static partial class OpenApiV2Deserializer { "url", (o, n) => { - o.Url = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { @@ -36,7 +36,7 @@ internal static partial class OpenApiV2Deserializer }, }; - private static PatternFieldMap _contactPatternFields = new PatternFieldMap + private static PatternFieldMap _contactPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 05e7b77c9..beba2e815 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -18,7 +18,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static FixedFieldMap _openApiFixedFields = new FixedFieldMap + private static FixedFieldMap _openApiFixedFields = new() { { "swagger", (o, n) => @@ -60,7 +60,7 @@ internal static partial class OpenApiV2Deserializer { if (o.Components == null) { - o.Components = new OpenApiComponents(); + o.Components = new(); } o.Components.Schemas = n.CreateMapWithReference( @@ -74,7 +74,7 @@ internal static partial class OpenApiV2Deserializer { if (o.Components == null) { - o.Components = new OpenApiComponents(); + o.Components = new(); } o.Components.Parameters = n.CreateMapWithReference( @@ -99,7 +99,7 @@ internal static partial class OpenApiV2Deserializer { if (o.Components == null) { - o.Components = new OpenApiComponents(); + o.Components = new(); } o.Components.Responses = n.CreateMapWithReference( @@ -112,7 +112,7 @@ internal static partial class OpenApiV2Deserializer { if (o.Components == null) { - o.Components = new OpenApiComponents(); + o.Components = new(); } o.Components.SecuritySchemes = n.CreateMapWithReference( @@ -126,7 +126,7 @@ internal static partial class OpenApiV2Deserializer {"externalDocs", (o, n) => o.ExternalDocs = LoadExternalDocs(n)} }; - private static PatternFieldMap _openApiPatternFields = new PatternFieldMap + private static PatternFieldMap _openApiPatternFields = new() { // We have no semantics to verify X- nodes, therefore treat them as just values. {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} @@ -154,7 +154,7 @@ private static void MakeServers(IList servers, ParsingContext con //Validate host if (host != null && !IsHostValid(host)) { - rootNode.Context.Diagnostic.Errors.Add(new OpenApiError(rootNode.Context.GetLocation(), "Invalid host")); + rootNode.Context.Diagnostic.Errors.Add(new(rootNode.Context.GetLocation(), "Invalid host")); return; } @@ -331,10 +331,10 @@ public override void Visit(OpenApiOperation operation) if (body != null) { operation.Parameters.Remove(body); - operation.RequestBody = new OpenApiRequestBody + operation.RequestBody = new() { UnresolvedReference = true, - Reference = new OpenApiReference + Reference = new() { Id = body.Reference.Id, Type = ReferenceType.RequestBody diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs index 2636bd48b..fd2a8f07d 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiExternalDocsDeserializer.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.V2 internal static partial class OpenApiV2Deserializer { private static readonly FixedFieldMap _externalDocsFixedFields = - new FixedFieldMap + new() { { OpenApiConstants.Description, (o, n) => @@ -26,13 +26,14 @@ internal static partial class OpenApiV2Deserializer { OpenApiConstants.Url, (o, n) => { - o.Url = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, }; private static readonly PatternFieldMap _externalDocsPatternFields = - new PatternFieldMap { + new() + { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs index 821e08a26..d1d6dab0b 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiHeaderDeserializer.cs @@ -16,7 +16,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static readonly FixedFieldMap _headerFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _headerFixedFields = new() { { "description", (o, n) => @@ -128,17 +128,17 @@ internal static partial class OpenApiV2Deserializer } }; - private static readonly PatternFieldMap _headerPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _headerPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; private static readonly AnyFieldMap _headerAnyFields = - new AnyFieldMap + new() { { OpenApiConstants.Default, - new AnyFieldMapParameter( + new( p => p.Schema?.Default, (p, v) => { @@ -150,11 +150,11 @@ internal static partial class OpenApiV2Deserializer }; private static readonly AnyListFieldMap _headerAnyListFields = - new AnyListFieldMap + new() { { OpenApiConstants.Enum, - new AnyListFieldMapParameter( + new( p => p.Schema?.Enum, (p, v) => { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs index 72f347c39..ffe9045d3 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiInfoDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static FixedFieldMap _infoFixedFields = new FixedFieldMap + private static FixedFieldMap _infoFixedFields = new() { { "title", (o, n) => @@ -31,7 +31,7 @@ internal static partial class OpenApiV2Deserializer { "termsOfService", (o, n) => { - o.TermsOfService = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.TermsOfService = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { @@ -54,7 +54,7 @@ internal static partial class OpenApiV2Deserializer } }; - private static PatternFieldMap _infoPatternFields = new PatternFieldMap + private static PatternFieldMap _infoPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs index 6a7445e73..965675143 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiLicenseDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static FixedFieldMap _licenseFixedFields = new FixedFieldMap + private static FixedFieldMap _licenseFixedFields = new() { { "name", (o, n) => @@ -25,12 +25,12 @@ internal static partial class OpenApiV2Deserializer { "url", (o, n) => { - o.Url = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, }; - private static PatternFieldMap _licensePatternFields = new PatternFieldMap + private static PatternFieldMap _licensePatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index e2be3ea6a..c7a7d723b 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -17,7 +17,7 @@ namespace Microsoft.OpenApi.Readers.V2 internal static partial class OpenApiV2Deserializer { private static readonly FixedFieldMap _operationFixedFields = - new FixedFieldMap + new() { { "tags", (o, n) => o.Tags = n.CreateSimpleList( @@ -93,16 +93,15 @@ internal static partial class OpenApiV2Deserializer }; private static readonly PatternFieldMap _operationPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; - private static readonly FixedFieldMap _responsesFixedFields = - new FixedFieldMap(); + private static readonly FixedFieldMap _responsesFixedFields = new(); private static readonly PatternFieldMap _responsesPatternFields = - new PatternFieldMap + new() { {s => !s.StartsWith("x-"), (o, p, n) => o.Add(p, LoadResponse(n))}, {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} @@ -163,7 +162,7 @@ private static OpenApiRequestBody CreateFormBody(ParsingContext context, List k.Name, @@ -224,7 +223,7 @@ private static OpenApiTag LoadTagByReference( var tagObject = new OpenApiTag { UnresolvedReference = true, - Reference = new OpenApiReference { Id = tagName, Type = ReferenceType.Tag } + Reference = new() { Id = tagName, Type = ReferenceType.Tag } }; return tagObject; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs index aea3b62df..b0013d9ae 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs @@ -17,7 +17,7 @@ namespace Microsoft.OpenApi.Readers.V2 internal static partial class OpenApiV2Deserializer { private static readonly FixedFieldMap _parameterFixedFields = - new FixedFieldMap + new() { { "name", (o, n) => @@ -136,17 +136,17 @@ internal static partial class OpenApiV2Deserializer }; private static readonly PatternFieldMap _parameterPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; private static readonly AnyFieldMap _parameterAnyFields = - new AnyFieldMap + new() { { OpenApiConstants.Default, - new AnyFieldMapParameter( + new( p => p.Schema?.Default, (p, v) => { if (p.Schema != null || v != null) @@ -159,11 +159,11 @@ internal static partial class OpenApiV2Deserializer }; private static readonly AnyListFieldMap _parameterAnyListFields = - new AnyListFieldMap + new() { { OpenApiConstants.Enum, - new AnyListFieldMapParameter( + new( p => p.Schema?.Enum, (p, v) => { if (p.Schema != null || v != null && v.Count > 0) @@ -208,7 +208,7 @@ private static OpenApiSchema GetOrCreateSchema(OpenApiParameter p) { if (p.Schema == null) { - p.Schema = new OpenApiSchema(); + p.Schema = new(); } return p.Schema; @@ -218,7 +218,7 @@ private static OpenApiSchema GetOrCreateSchema(OpenApiHeader p) { if (p.Schema == null) { - p.Schema = new OpenApiSchema(); + p.Schema = new(); } return p.Schema; @@ -238,7 +238,7 @@ private static void ProcessIn(OpenApiParameter o, ParseNode n) var formParameters = n.Context.GetFromTempStorage>("formParameters"); if (formParameters == null) { - formParameters = new List(); + formParameters = new(); n.Context.SetTempStorage("formParameters", formParameters); } diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs index 2eee6719a..d0dd4af8c 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathItemDeserializer.cs @@ -15,12 +15,12 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static readonly FixedFieldMap _pathItemFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _pathItemFixedFields = new() { { "$ref", (o, n) => { - o.Reference = new OpenApiReference { ExternalResource = n.GetScalarValue() }; + o.Reference = new() { ExternalResource = n.GetScalarValue() }; o.UnresolvedReference =true; } }, @@ -40,7 +40,7 @@ internal static partial class OpenApiV2Deserializer }; private static readonly PatternFieldMap _pathItemPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))}, }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs index 611eee485..8e026b7f7 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiPathsDeserializer.cs @@ -13,9 +13,9 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static FixedFieldMap _pathsFixedFields = new FixedFieldMap(); + private static FixedFieldMap _pathsFixedFields = new(); - private static PatternFieldMap _pathsPatternFields = new PatternFieldMap + private static PatternFieldMap _pathsPatternFields = new() { {s => s.StartsWith("/"), (o, k, n) => o.Add(k, LoadPathItem(n))}, {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs index ad361222f..5c6a4ebb7 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static readonly FixedFieldMap _responseFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _responseFixedFields = new() { { "description", (o, n) => @@ -43,17 +43,17 @@ internal static partial class OpenApiV2Deserializer }; private static readonly PatternFieldMap _responsePatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; private static readonly AnyFieldMap _mediaTypeAnyFields = - new AnyFieldMap + new() { { OpenApiConstants.Example, - new AnyFieldMapParameter( + new( m => m.Example, (m, v) => m.Example = v, m => m.Schema) @@ -128,7 +128,7 @@ private static void LoadExample(OpenApiResponse response, string mediaType, Pars } else { - mediaTypeObject = new OpenApiMediaType + mediaTypeObject = new() { Schema = node.Context.GetFromTempStorage(TempStorageKeys.ResponseSchema, response) }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs index 2a0c71a72..f1b787c2d 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSchemaDeserializer.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static readonly FixedFieldMap _schemaFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _schemaFixedFields = new() { { "title", (o, n) => @@ -172,7 +172,7 @@ internal static partial class OpenApiV2Deserializer { "discriminator", (o, n) => { - o.Discriminator = new OpenApiDiscriminator + o.Discriminator = new() { PropertyName = n.GetScalarValue() }; @@ -204,33 +204,33 @@ internal static partial class OpenApiV2Deserializer }, }; - private static readonly PatternFieldMap _schemaPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _schemaPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; - private static readonly AnyFieldMap _schemaAnyFields = new AnyFieldMap + private static readonly AnyFieldMap _schemaAnyFields = new() { { OpenApiConstants.Default, - new AnyFieldMapParameter( + new( s => s.Default, (s, v) => s.Default = v, s => s) }, { OpenApiConstants.Example, - new AnyFieldMapParameter( + new( s => s.Example, (s, v) => s.Example = v, s => s) } }; - private static readonly AnyListFieldMap _schemaAnyListFields = new AnyListFieldMap + private static readonly AnyListFieldMap _schemaAnyListFields = new() { { OpenApiConstants.Enum, - new AnyListFieldMapParameter( + new( s => s.Enum, (s, v) => s.Enum = v, s => s) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs index 5197b6e1e..b4e578aa1 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecurityRequirementDeserializer.cs @@ -33,7 +33,7 @@ public static OpenApiSecurityRequirement LoadSecurityRequirement(ParseNode node) else { mapNode.Context.Diagnostic.Errors.Add( - new OpenApiError(node.Context.GetLocation(), + new(node.Context.GetLocation(), $"Scheme {property.Name} is not found")); } } @@ -48,7 +48,7 @@ private static OpenApiSecurityScheme LoadSecuritySchemeByReference( var securitySchemeObject = new OpenApiSecurityScheme { UnresolvedReference = true, - Reference = new OpenApiReference + Reference = new() { Id = schemeName, Type = ReferenceType.SecurityScheme diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs index 20de9c880..3cb9efe52 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs @@ -19,7 +19,7 @@ internal static partial class OpenApiV2Deserializer private static OpenApiOAuthFlow _flow; private static readonly FixedFieldMap _securitySchemeFixedFields = - new FixedFieldMap + new() { { "type", @@ -56,14 +56,14 @@ internal static partial class OpenApiV2Deserializer "authorizationUrl", (o, n) => { - _flow.AuthorizationUrl = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { "tokenUrl", (o, n) => { - _flow.TokenUrl = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { @@ -75,7 +75,7 @@ internal static partial class OpenApiV2Deserializer }; private static readonly PatternFieldMap _securitySchemePatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; @@ -85,7 +85,7 @@ public static OpenApiSecurityScheme LoadSecurityScheme(ParseNode node) // Reset the local variables every time this method is called. // TODO: Change _flow to a tempStorage variable to make the deserializer thread-safe. _flowValue = null; - _flow = new OpenApiOAuthFlow(); + _flow = new(); var mapNode = node.CheckMapNode("securityScheme"); @@ -98,28 +98,28 @@ public static OpenApiSecurityScheme LoadSecurityScheme(ParseNode node) // Put the Flow object in the right Flows property based on the string in "flow" if (_flowValue == OpenApiConstants.Implicit) { - securityScheme.Flows = new OpenApiOAuthFlows + securityScheme.Flows = new() { Implicit = _flow }; } else if (_flowValue == OpenApiConstants.Password) { - securityScheme.Flows = new OpenApiOAuthFlows + securityScheme.Flows = new() { Password = _flow }; } else if (_flowValue == OpenApiConstants.Application) { - securityScheme.Flows = new OpenApiOAuthFlows + securityScheme.Flows = new() { ClientCredentials = _flow }; } else if (_flowValue == OpenApiConstants.AccessCode) { - securityScheme.Flows = new OpenApiOAuthFlows + securityScheme.Flows = new() { AuthorizationCode = _flow }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs index ecd6c96c3..6bdd60692 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiTagDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static readonly FixedFieldMap _tagFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _tagFixedFields = new() { { OpenApiConstants.Name, (o, n) => @@ -35,7 +35,7 @@ internal static partial class OpenApiV2Deserializer } }; - private static readonly PatternFieldMap _tagPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _tagPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs index 6b7aea308..8b10bb83f 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2Deserializer.cs @@ -6,7 +6,6 @@ using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Exceptions; using Microsoft.OpenApi.Interfaces; -using Microsoft.OpenApi.Models; using Microsoft.OpenApi.Readers.ParseNodes; namespace Microsoft.OpenApi.Readers.V2 @@ -57,7 +56,7 @@ private static void ProcessAnyFields( catch (OpenApiException exception) { exception.Pointer = mapNode.Context.GetLocation(); - mapNode.Context.Diagnostic.Errors.Add(new OpenApiError(exception)); + mapNode.Context.Diagnostic.Errors.Add(new(exception)); } finally { @@ -98,7 +97,7 @@ private static void ProcessAnyListFields( catch (OpenApiException exception) { exception.Pointer = mapNode.Context.GetLocation(); - mapNode.Context.Diagnostic.Errors.Add(new OpenApiError(exception)); + mapNode.Context.Diagnostic.Errors.Add(new(exception)); } finally { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index dfb975175..20490aca7 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -70,7 +70,7 @@ private static OpenApiReference ParseLocalReference(string localReference) var id = localReference.Substring( segments[0].Length + "/".Length + segments[1].Length + "/".Length); - return new OpenApiReference { Type = referenceType, Id = id }; + return new() { Type = referenceType, Id = id }; } throw new OpenApiException( @@ -145,7 +145,7 @@ public OpenApiReference ConvertToOpenApiReference(string reference, ReferenceTyp if (type == null) { // "$ref": "Pet.json" - return new OpenApiReference + return new() { ExternalResource = segments[0] }; @@ -153,7 +153,7 @@ public OpenApiReference ConvertToOpenApiReference(string reference, ReferenceTyp if (type is ReferenceType.Tag or ReferenceType.SecurityScheme) { - return new OpenApiReference + return new() { Type = type, Id = reference @@ -171,7 +171,7 @@ public OpenApiReference ConvertToOpenApiReference(string reference, ReferenceTyp } catch (OpenApiException ex) { - Diagnostic.Errors.Add(new OpenApiError(ex)); + Diagnostic.Errors.Add(new(ex)); return null; } } @@ -198,7 +198,7 @@ public OpenApiReference ConvertToOpenApiReference(string reference, ReferenceTyp } // $ref: externalSource.yaml#/Pet - return new OpenApiReference + return new() { ExternalResource = segments[0], Type = type, diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs index c251faaf4..3be5bfe7b 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiXmlDeserializer.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.V2 /// internal static partial class OpenApiV2Deserializer { - private static readonly FixedFieldMap _xmlFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _xmlFixedFields = new() { { "name", (o, n) => @@ -28,7 +28,7 @@ internal static partial class OpenApiV2Deserializer { if (Uri.IsWellFormedUriString(n.GetScalarValue(), UriKind.Absolute)) { - o.Namespace = new Uri(n.GetScalarValue(), UriKind.Absolute); + o.Namespace = new(n.GetScalarValue(), UriKind.Absolute); } else { @@ -57,7 +57,7 @@ internal static partial class OpenApiV2Deserializer }; private static readonly PatternFieldMap _xmlPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs index c400e8b5b..fc41e7daa 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiCallbackDeserializer.cs @@ -14,11 +14,10 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _callbackFixedFields = - new FixedFieldMap(); + private static readonly FixedFieldMap _callbackFixedFields = new(); private static readonly PatternFieldMap _callbackPatternFields = - new PatternFieldMap + new() { {s => !s.StartsWith("x-"), (o, p, n) => o.AddPathItem(RuntimeExpression.Build(p), LoadPathItem(n))}, {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))}, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs index cf62bc389..62ed95fda 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiComponentsDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static FixedFieldMap _componentsFixedFields = new FixedFieldMap + private static FixedFieldMap _componentsFixedFields = new() { { "schemas", (o, n) => o.Schemas = n.CreateMapWithReference(ReferenceType.Schema, LoadSchema) @@ -29,7 +29,7 @@ internal static partial class OpenApiV3Deserializer }; private static PatternFieldMap _componentsPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs index 2dfddfb3b..7d9f469f8 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiContactDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static FixedFieldMap _contactFixedFields = new FixedFieldMap + private static FixedFieldMap _contactFixedFields = new() { { "name", (o, n) => @@ -31,12 +31,12 @@ internal static partial class OpenApiV3Deserializer { "url", (o, n) => { - o.Url = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, }; - private static PatternFieldMap _contactPatternFields = new PatternFieldMap + private static PatternFieldMap _contactPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs index ec3267883..93258cffe 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDiscriminatorDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _discriminatorFixedFields = - new FixedFieldMap + new() { { "propertyName", (o, n) => @@ -29,8 +29,7 @@ internal static partial class OpenApiV3Deserializer } }; - private static readonly PatternFieldMap _discriminatorPatternFields = - new PatternFieldMap(); + private static readonly PatternFieldMap _discriminatorPatternFields = new(); public static OpenApiDiscriminator LoadDiscriminator(ParseNode node) { diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs index 70551cff3..88cd93000 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static FixedFieldMap _openApiFixedFields = new FixedFieldMap + private static FixedFieldMap _openApiFixedFields = new() { { "openapi", (o, n) => @@ -27,7 +27,7 @@ internal static partial class OpenApiV3Deserializer {"tags", (o, n) => {o.Tags = n.CreateList(LoadTag); foreach (var tag in o.Tags) { - tag.Reference = new OpenApiReference + tag.Reference = new() { Id = tag.Name, Type = ReferenceType.Tag @@ -38,7 +38,7 @@ internal static partial class OpenApiV3Deserializer {"security", (o, n) => o.SecurityRequirements = n.CreateList(LoadSecurityRequirement)} }; - private static PatternFieldMap _openApiPatternFields = new PatternFieldMap + private static PatternFieldMap _openApiPatternFields = new() { // We have no semantics to verify X- nodes, therefore treat them as just values. {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs index 8459f758b..6a275ff00 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiEncodingDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _encodingFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _encodingFixedFields = new() { { "contentType", (o, n) => @@ -48,7 +48,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _encodingPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs index bd20f677f..ea7e44aed 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiExampleDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _exampleFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _exampleFixedFields = new() { { "summary", (o, n) => @@ -42,7 +42,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _examplePatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs index 177611dff..f742fb1de 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiExternalDocsDeserializer.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _externalDocsFixedFields = - new FixedFieldMap + new() { // $ref { @@ -27,13 +27,14 @@ internal static partial class OpenApiV3Deserializer { "url", (o, n) => { - o.Url = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, }; private static readonly PatternFieldMap _externalDocsPatternFields = - new PatternFieldMap { + new() + { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs index f7cd90aca..4b296c046 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiHeaderDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _headerFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _headerFixedFields = new() { { "description", (o, n) => @@ -77,7 +77,7 @@ internal static partial class OpenApiV3Deserializer }, }; - private static readonly PatternFieldMap _headerPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _headerPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs index 8ccbf6d69..11fb88034 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiInfoDeserializer.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - public static FixedFieldMap InfoFixedFields = new FixedFieldMap + public static FixedFieldMap InfoFixedFields = new() { { "title", (o, n) => @@ -38,7 +38,7 @@ internal static partial class OpenApiV3Deserializer { "termsOfService", (o, n) => { - o.TermsOfService = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.TermsOfService = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { @@ -55,7 +55,7 @@ internal static partial class OpenApiV3Deserializer } }; - public static PatternFieldMap InfoPatternFields = new PatternFieldMap + public static PatternFieldMap InfoPatternFields = new() { {s => s.StartsWith("x-"), (o, k, n) => o.AddExtension(k,LoadExtension(k, n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs index 6a27b1286..1582d75b2 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiLicenseDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static FixedFieldMap _licenseFixedFields = new FixedFieldMap + private static FixedFieldMap _licenseFixedFields = new() { { "name", (o, n) => @@ -25,12 +25,12 @@ internal static partial class OpenApiV3Deserializer { "url", (o, n) => { - o.Url = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.Url = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, }; - private static PatternFieldMap _licensePatternFields = new PatternFieldMap + private static PatternFieldMap _licensePatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs index 9eae96b72..6db2a82fb 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiLinkDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _linkFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _linkFixedFields = new() { { "operationRef", (o, n) => @@ -48,7 +48,7 @@ internal static partial class OpenApiV3Deserializer {"server", (o, n) => o.Server = LoadServer(n)} }; - private static readonly PatternFieldMap _linkPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _linkPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))}, }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs index b0dbccd91..5ae07962d 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiMediaTypeDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _mediaTypeFixedFields = - new FixedFieldMap + new() { { OpenApiConstants.Schema, (o, n) => @@ -43,16 +43,16 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _mediaTypePatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; - private static readonly AnyFieldMap _mediaTypeAnyFields = new AnyFieldMap + private static readonly AnyFieldMap _mediaTypeAnyFields = new() { { OpenApiConstants.Example, - new AnyFieldMapParameter( + new( s => s.Example, (s, v) => s.Example = v, s => s.Schema) @@ -60,11 +60,11 @@ internal static partial class OpenApiV3Deserializer }; private static readonly AnyMapFieldMap _mediaTypeAnyMapOpenApiExampleFields = - new AnyMapFieldMap - { + new() + { { OpenApiConstants.Examples, - new AnyMapFieldMapParameter( + new( m => m.Examples, e => e.Value, (e, v) => e.Value = v, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs index 1679cdf75..0b5f6a3eb 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs @@ -15,31 +15,31 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _oAuthFlowFixedFileds = - new FixedFieldMap + new() { { "authorizationUrl", (o, n) => { - o.AuthorizationUrl = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { "tokenUrl", (o, n) => { - o.TokenUrl = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { "refreshUrl", (o, n) => { - o.RefreshUrl = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.RefreshUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, {"scopes", (o, n) => o.Scopes = n.CreateSimpleMap(LoadString)} }; private static readonly PatternFieldMap _oAuthFlowPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs index 9269048aa..9a80bed88 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _oAuthFlowsFixedFileds = - new FixedFieldMap + new() { {"implicit", (o, n) => o.Implicit = LoadOAuthFlow(n)}, {"password", (o, n) => o.Password = LoadOAuthFlow(n)}, @@ -23,7 +23,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _oAuthFlowsPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs index dee61cef6..c3ac122f1 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOperationDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _operationFixedFields = - new FixedFieldMap + new() { { "tags", (o, n) => o.Tags = n.CreateSimpleList( @@ -92,7 +92,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _operationPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))}, }; @@ -115,7 +115,7 @@ private static OpenApiTag LoadTagByReference( var tagObject = new OpenApiTag { UnresolvedReference = true, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Tag, Id = tagName diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs index c291132ca..c502d38b0 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiParameterDeserializer.cs @@ -16,7 +16,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _parameterFixedFields = - new FixedFieldMap + new() { { "name", (o, n) => @@ -110,16 +110,16 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _parameterPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; - private static readonly AnyFieldMap _parameterAnyFields = new AnyFieldMap + private static readonly AnyFieldMap _parameterAnyFields = new() { { OpenApiConstants.Example, - new AnyFieldMapParameter( + new( s => s.Example, (s, v) => s.Example = v, s => s.Schema) @@ -127,11 +127,11 @@ internal static partial class OpenApiV3Deserializer }; private static readonly AnyMapFieldMap _parameterAnyMapOpenApiExampleFields = - new AnyMapFieldMap - { + new() + { { OpenApiConstants.Examples, - new AnyMapFieldMapParameter( + new( m => m.Examples, e => e.Value, (e, v) => e.Value = v, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs index dd5a071f3..fcafcc786 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathItemDeserializer.cs @@ -13,11 +13,11 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _pathItemFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _pathItemFixedFields = new() { { "$ref", (o,n) => { - o.Reference = new OpenApiReference { ExternalResource = n.GetScalarValue() }; + o.Reference = new() { ExternalResource = n.GetScalarValue() }; o.UnresolvedReference =true; } }, @@ -46,7 +46,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _pathItemPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs index 5b0b9485b..8104cde7f 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiPathsDeserializer.cs @@ -13,9 +13,9 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static FixedFieldMap _pathsFixedFields = new FixedFieldMap(); + private static FixedFieldMap _pathsFixedFields = new(); - private static PatternFieldMap _pathsPatternFields = new PatternFieldMap + private static PatternFieldMap _pathsPatternFields = new() { {s => s.StartsWith("/"), (o, k, n) => o.Add(k, LoadPathItem(n))}, {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs index c5c2fab91..d65279788 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiRequestBodyDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _requestBodyFixedFields = - new FixedFieldMap + new() { { "description", (o, n) => @@ -37,7 +37,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _requestBodyPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs index 73f20791a..64515dc3b 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponseDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _responseFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _responseFixedFields = new() { { "description", (o, n) => @@ -43,7 +43,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _responsePatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs index 597e8a4b6..437553160 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiResponsesDeserializer.cs @@ -13,9 +13,9 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - public static FixedFieldMap ResponsesFixedFields = new FixedFieldMap(); + public static FixedFieldMap ResponsesFixedFields = new(); - public static PatternFieldMap ResponsesPatternFields = new PatternFieldMap + public static PatternFieldMap ResponsesPatternFields = new() { {s => !s.StartsWith("x-"), (o, p, n) => o.Add(p, LoadResponse(n))}, {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs index 3a961255f..fd375bfdf 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSchemaDeserializer.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _schemaFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _schemaFixedFields = new() { { "title", (o, n) => @@ -237,34 +237,34 @@ internal static partial class OpenApiV3Deserializer }, }; - private static readonly PatternFieldMap _schemaPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _schemaPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; - private static readonly AnyFieldMap _schemaAnyFields = new AnyFieldMap + private static readonly AnyFieldMap _schemaAnyFields = new() { { OpenApiConstants.Default, - new AnyFieldMapParameter( + new( s => s.Default, (s, v) => s.Default = v, s => s) }, { OpenApiConstants.Example, - new AnyFieldMapParameter( + new( s => s.Example, (s, v) => s.Example = v, s => s) } }; - private static readonly AnyListFieldMap _schemaAnyListFields = new AnyListFieldMap + private static readonly AnyListFieldMap _schemaAnyListFields = new() { { OpenApiConstants.Enum, - new AnyListFieldMapParameter( + new( s => s.Enum, (s, v) => s.Enum = v, s => s) @@ -279,7 +279,7 @@ public static OpenApiSchema LoadSchema(ParseNode node) if (pointer != null) { - return new OpenApiSchema + return new() { UnresolvedReference = true, Reference = node.Context.VersionService.ConvertToOpenApiReference(pointer, ReferenceType.Schema) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs index 4a609125e..fec3ec401 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecurityRequirementDeserializer.cs @@ -33,7 +33,7 @@ public static OpenApiSecurityRequirement LoadSecurityRequirement(ParseNode node) else { mapNode.Context.Diagnostic.Errors.Add( - new OpenApiError(node.Context.GetLocation(), $"Scheme {property.Name} is not found")); + new(node.Context.GetLocation(), $"Scheme {property.Name} is not found")); } } @@ -47,7 +47,7 @@ private static OpenApiSecurityScheme LoadSecuritySchemeByReference( var securitySchemeObject = new OpenApiSecurityScheme { UnresolvedReference = true, - Reference = new OpenApiReference + Reference = new() { Id = schemeName, Type = ReferenceType.SecurityScheme diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs index a5f50eb3f..e2ea91abe 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiSecuritySchemeDeserializer.cs @@ -15,7 +15,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _securitySchemeFixedFields = - new FixedFieldMap + new() { { "type", (o, n) => @@ -56,7 +56,7 @@ internal static partial class OpenApiV3Deserializer { "openIdConnectUrl", (o, n) => { - o.OpenIdConnectUrl = new Uri(n.GetScalarValue(), UriKind.RelativeOrAbsolute); + o.OpenIdConnectUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { @@ -68,7 +68,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _securitySchemePatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs index 81e92b979..b29c3b0bf 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _serverFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _serverFixedFields = new() { { "url", (o, n) => @@ -35,7 +35,7 @@ internal static partial class OpenApiV3Deserializer } }; - private static readonly PatternFieldMap _serverPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _serverPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs index fa4d07d72..c506930d3 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiServerVariableDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 internal static partial class OpenApiV3Deserializer { private static readonly FixedFieldMap _serverVariableFixedFields = - new FixedFieldMap + new() { { "enum", (o, n) => @@ -37,7 +37,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _serverVariablePatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs index 9de8bf610..b78cdfc60 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiTagDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _tagFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _tagFixedFields = new() { { OpenApiConstants.Name, (o, n) => @@ -35,7 +35,7 @@ internal static partial class OpenApiV3Deserializer } }; - private static readonly PatternFieldMap _tagPatternFields = new PatternFieldMap + private static readonly PatternFieldMap _tagPatternFields = new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs index 81ced4a53..79b5f0671 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3Deserializer.cs @@ -55,7 +55,7 @@ private static void ProcessAnyFields( catch (OpenApiException exception) { exception.Pointer = mapNode.Context.GetLocation(); - mapNode.Context.Diagnostic.Errors.Add(new OpenApiError(exception)); + mapNode.Context.Diagnostic.Errors.Add(new(exception)); } finally { @@ -90,7 +90,7 @@ private static void ProcessAnyListFields( catch (OpenApiException exception) { exception.Pointer = mapNode.Context.GetLocation(); - mapNode.Context.Diagnostic.Errors.Add(new OpenApiError(exception)); + mapNode.Context.Diagnostic.Errors.Add(new(exception)); } finally { @@ -131,7 +131,7 @@ private static void ProcessAnyMapFields( catch (OpenApiException exception) { exception.Pointer = mapNode.Context.GetLocation(); - mapNode.Context.Diagnostic.Errors.Add(new OpenApiError(exception)); + mapNode.Context.Diagnostic.Errors.Add(new(exception)); } finally { @@ -152,13 +152,13 @@ private static RuntimeExpressionAnyWrapper LoadRuntimeExpressionAnyWrapper(Parse if (value != null && value.StartsWith("$")) { - return new RuntimeExpressionAnyWrapper + return new() { Expression = RuntimeExpression.Build(value) }; } - return new RuntimeExpressionAnyWrapper + return new() { Any = OpenApiAnyConverter.GetSpecificOpenApiAny(node.CreateAny()) }; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index a6cb41970..011680d3d 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -80,7 +80,7 @@ public OpenApiReference ConvertToOpenApiReference( { if (type is ReferenceType.Tag or ReferenceType.SecurityScheme) { - return new OpenApiReference + return new() { Type = type, Id = reference @@ -89,7 +89,7 @@ public OpenApiReference ConvertToOpenApiReference( // Either this is an external reference as an entire file // or a simple string-style reference for tag and security scheme. - return new OpenApiReference + return new() { Type = type, ExternalResource = segments[0] @@ -106,7 +106,7 @@ public OpenApiReference ConvertToOpenApiReference( } catch (OpenApiException ex) { - Diagnostic.Errors.Add(new OpenApiError(ex)); + Diagnostic.Errors.Add(new(ex)); } } // Where fragments point into a non-OpenAPI document, the id will be the complete fragment identifier @@ -185,7 +185,7 @@ private OpenApiReference ParseLocalReference(string localReference) if (segments[1] == "components") { var referenceType = segments[2].GetEnumFromDisplayName(); - return new OpenApiReference { Type = referenceType, Id = segments[3] }; + return new() { Type = referenceType, Id = segments[3] }; } } diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs index 95cc2a585..866f38d01 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiXmlDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _xmlFixedFields = new FixedFieldMap + private static readonly FixedFieldMap _xmlFixedFields = new() { { "name", (o, n) => @@ -25,7 +25,7 @@ internal static partial class OpenApiV3Deserializer { "namespace", (o, n) => { - o.Namespace = new Uri(n.GetScalarValue(), UriKind.Absolute); + o.Namespace = new(n.GetScalarValue(), UriKind.Absolute); } }, { @@ -49,7 +49,7 @@ internal static partial class OpenApiV3Deserializer }; private static readonly PatternFieldMap _xmlPatternFields = - new PatternFieldMap + new() { {s => s.StartsWith("x-"), (o, p, n) => o.AddExtension(p, LoadExtension(p,n))} }; diff --git a/src/Microsoft.OpenApi.Workbench/MainModel.cs b/src/Microsoft.OpenApi.Workbench/MainModel.cs index ca47bbd48..52a34df81 100644 --- a/src/Microsoft.OpenApi.Workbench/MainModel.cs +++ b/src/Microsoft.OpenApi.Workbench/MainModel.cs @@ -13,7 +13,6 @@ using Microsoft.OpenApi.Readers; using Microsoft.OpenApi.Services; using Microsoft.OpenApi.Validations; -using Microsoft.OpenApi.Writers; namespace Microsoft.OpenApi.Workbench { @@ -49,7 +48,7 @@ public class MainModel : INotifyPropertyChanged /// private OpenApiSpecVersion _version = OpenApiSpecVersion.OpenApi3_0; - private HttpClient _httpClient = new HttpClient(); + private HttpClient _httpClient = new(); public string Input { @@ -194,7 +193,7 @@ protected void OnPropertyChanged(string propertyName) var handler = PropertyChanged; if (handler != null) { - handler(this, new PropertyChangedEventArgs(propertyName)); + handler(this, new(propertyName)); } } @@ -239,11 +238,11 @@ internal async Task ParseDocument() { if (_inputFile.StartsWith("http")) { - settings.BaseUrl = new Uri(_inputFile); + settings.BaseUrl = new(_inputFile); } else { - settings.BaseUrl = new Uri("file://" + Path.GetDirectoryName(_inputFile) + "/"); + settings.BaseUrl = new("file://" + Path.GetDirectoryName(_inputFile) + "/"); } } var readResult = await new OpenApiStreamReader(settings @@ -309,7 +308,7 @@ private string WriteContents(OpenApiDocument document) outputStream, Version, Format, - new OpenApiWriterSettings + new() { InlineLocalReferences = InlineLocal, InlineExternalReferences = InlineExternal diff --git a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs index 0d2f74582..5f3c3ec38 100644 --- a/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs +++ b/src/Microsoft.OpenApi.Workbench/MainWindow.xaml.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Workbench /// public partial class MainWindow : Window { - private readonly MainModel _mainModel = new MainModel(); + private readonly MainModel _mainModel = new(); public MainWindow() { diff --git a/src/Microsoft.OpenApi/Error.cs b/src/Microsoft.OpenApi/Error.cs index 9ad76ce54..29e1c7af2 100644 --- a/src/Microsoft.OpenApi/Error.cs +++ b/src/Microsoft.OpenApi/Error.cs @@ -31,7 +31,7 @@ internal static string Format(string format, params object[] args) /// The logged . internal static ArgumentException Argument(string messageFormat, params object[] messageArgs) { - return new ArgumentException(Format(messageFormat, messageArgs)); + return new(Format(messageFormat, messageArgs)); } /// @@ -46,7 +46,7 @@ internal static ArgumentException Argument( string messageFormat, params object[] messageArgs) { - return new ArgumentException(Format(messageFormat, messageArgs), parameterName); + return new(Format(messageFormat, messageArgs), parameterName); } /// @@ -56,7 +56,7 @@ internal static ArgumentException Argument( /// The logged . internal static ArgumentNullException ArgumentNull(string parameterName) { - return new ArgumentNullException(parameterName); + return new(parameterName); } /// @@ -71,7 +71,7 @@ internal static ArgumentNullException ArgumentNull( string messageFormat, params object[] messageArgs) { - return new ArgumentNullException(parameterName, Format(messageFormat, messageArgs)); + return new(parameterName, Format(messageFormat, messageArgs)); } /// @@ -92,7 +92,7 @@ internal static ArgumentException ArgumentNullOrWhiteSpace(string parameterName) /// The logged . internal static NotSupportedException NotSupported(string messageFormat, params object[] messageArgs) { - return new NotSupportedException(Format(messageFormat, messageArgs)); + return new(Format(messageFormat, messageArgs)); } } } diff --git a/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs b/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs index 98c5e069c..bbe0d3076 100644 --- a/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/CompositeExpression.cs @@ -13,12 +13,12 @@ namespace Microsoft.OpenApi.Expressions public class CompositeExpression : RuntimeExpression { private readonly string template; - private Regex expressionPattern = new Regex(@"{(?\$[^}]*)"); + private Regex expressionPattern = new(@"{(?\$[^}]*)"); /// /// Expressions embedded into string literal /// - public List ContainedExpressions = new List(); + public List ContainedExpressions = new(); /// /// Create a composite expression from a string literal with an embedded expression diff --git a/src/Microsoft.OpenApi/Expressions/SourceExpression.cs b/src/Microsoft.OpenApi/Expressions/SourceExpression.cs index 2e55ece90..8504a1e89 100644 --- a/src/Microsoft.OpenApi/Expressions/SourceExpression.cs +++ b/src/Microsoft.OpenApi/Expressions/SourceExpression.cs @@ -65,7 +65,7 @@ protected SourceExpression(string value) return new BodyExpression(); } - return new BodyExpression(new JsonPointer(subString)); + return new BodyExpression(new(subString)); } } diff --git a/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs b/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs index e7d668703..983474243 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenAPIWriterExtensions.cs @@ -15,7 +15,7 @@ internal static OpenApiWriterSettings GetSettings(this IOpenApiWriter openApiWri { return @base.Settings; } - return new OpenApiWriterSettings(); + return new(); } } } diff --git a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs index 176762dc6..712e7f5c7 100644 --- a/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs +++ b/src/Microsoft.OpenApi/Extensions/OpenApiTypeMapper.cs @@ -14,38 +14,38 @@ public static class OpenApiTypeMapper { private static readonly Dictionary> _simpleTypeToOpenApiSchema = new() { - [typeof(bool)] = () => new OpenApiSchema { Type = "boolean" }, - [typeof(byte)] = () => new OpenApiSchema { Type = "string", Format = "byte" }, - [typeof(int)] = () => new OpenApiSchema { Type = "integer", Format = "int32" }, - [typeof(uint)] = () => new OpenApiSchema { Type = "integer", Format = "int32" }, - [typeof(long)] = () => new OpenApiSchema { Type = "integer", Format = "int64" }, - [typeof(ulong)] = () => new OpenApiSchema { Type = "integer", Format = "int64" }, - [typeof(float)] = () => new OpenApiSchema { Type = "number", Format = "float" }, - [typeof(double)] = () => new OpenApiSchema { Type = "number", Format = "double" }, - [typeof(decimal)] = () => new OpenApiSchema { Type = "number", Format = "double" }, - [typeof(DateTime)] = () => new OpenApiSchema { Type = "string", Format = "date-time" }, - [typeof(DateTimeOffset)] = () => new OpenApiSchema { Type = "string", Format = "date-time" }, - [typeof(Guid)] = () => new OpenApiSchema { Type = "string", Format = "uuid" }, - [typeof(char)] = () => new OpenApiSchema { Type = "string" }, + [typeof(bool)] = () => new() { Type = "boolean" }, + [typeof(byte)] = () => new() { Type = "string", Format = "byte" }, + [typeof(int)] = () => new() { Type = "integer", Format = "int32" }, + [typeof(uint)] = () => new() { Type = "integer", Format = "int32" }, + [typeof(long)] = () => new() { Type = "integer", Format = "int64" }, + [typeof(ulong)] = () => new() { Type = "integer", Format = "int64" }, + [typeof(float)] = () => new() { Type = "number", Format = "float" }, + [typeof(double)] = () => new() { Type = "number", Format = "double" }, + [typeof(decimal)] = () => new() { Type = "number", Format = "double" }, + [typeof(DateTime)] = () => new() { Type = "string", Format = "date-time" }, + [typeof(DateTimeOffset)] = () => new() { Type = "string", Format = "date-time" }, + [typeof(Guid)] = () => new() { Type = "string", Format = "uuid" }, + [typeof(char)] = () => new() { Type = "string" }, // Nullable types - [typeof(bool?)] = () => new OpenApiSchema { Type = "boolean", Nullable = true }, - [typeof(byte?)] = () => new OpenApiSchema { Type = "string", Format = "byte", Nullable = true }, - [typeof(int?)] = () => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true }, - [typeof(uint?)] = () => new OpenApiSchema { Type = "integer", Format = "int32", Nullable = true }, - [typeof(long?)] = () => new OpenApiSchema { Type = "integer", Format = "int64", Nullable = true }, - [typeof(ulong?)] = () => new OpenApiSchema { Type = "integer", Format = "int64", Nullable = true }, - [typeof(float?)] = () => new OpenApiSchema { Type = "number", Format = "float", Nullable = true }, - [typeof(double?)] = () => new OpenApiSchema { Type = "number", Format = "double", Nullable = true }, - [typeof(decimal?)] = () => new OpenApiSchema { Type = "number", Format = "double", Nullable = true }, - [typeof(DateTime?)] = () => new OpenApiSchema { Type = "string", Format = "date-time", Nullable = true }, - [typeof(DateTimeOffset?)] = () => new OpenApiSchema { Type = "string", Format = "date-time", Nullable = true }, - [typeof(Guid?)] = () => new OpenApiSchema { Type = "string", Format = "uuid", Nullable = true }, - [typeof(char?)] = () => new OpenApiSchema { Type = "string", Nullable = true }, + [typeof(bool?)] = () => new() { Type = "boolean", Nullable = true }, + [typeof(byte?)] = () => new() { Type = "string", Format = "byte", Nullable = true }, + [typeof(int?)] = () => new() { Type = "integer", Format = "int32", Nullable = true }, + [typeof(uint?)] = () => new() { Type = "integer", Format = "int32", Nullable = true }, + [typeof(long?)] = () => new() { Type = "integer", Format = "int64", Nullable = true }, + [typeof(ulong?)] = () => new() { Type = "integer", Format = "int64", Nullable = true }, + [typeof(float?)] = () => new() { Type = "number", Format = "float", Nullable = true }, + [typeof(double?)] = () => new() { Type = "number", Format = "double", Nullable = true }, + [typeof(decimal?)] = () => new() { Type = "number", Format = "double", Nullable = true }, + [typeof(DateTime?)] = () => new() { Type = "string", Format = "date-time", Nullable = true }, + [typeof(DateTimeOffset?)] = () => new() { Type = "string", Format = "date-time", Nullable = true }, + [typeof(Guid?)] = () => new() { Type = "string", Format = "uuid", Nullable = true }, + [typeof(char?)] = () => new() { Type = "string", Nullable = true }, - [typeof(Uri)] = () => new OpenApiSchema { Type = "string", Format = "uri"}, // Uri is treated as simple string - [typeof(string)] = () => new OpenApiSchema { Type = "string" }, - [typeof(object)] = () => new OpenApiSchema { Type = "object" } + [typeof(Uri)] = () => new() { Type = "string", Format = "uri"}, // Uri is treated as simple string + [typeof(string)] = () => new() { Type = "string" }, + [typeof(object)] = () => new() { Type = "object" } }; /// @@ -79,7 +79,7 @@ public static OpenApiSchema MapTypeToOpenApiPrimitiveType(this Type type) return _simpleTypeToOpenApiSchema.TryGetValue(type, out var result) ? result() - : new OpenApiSchema { Type = "string" }; + : new() { Type = "string" }; } /// diff --git a/src/Microsoft.OpenApi/JsonPointer.cs b/src/Microsoft.OpenApi/JsonPointer.cs index 1ff843031..110cca81e 100644 --- a/src/Microsoft.OpenApi/JsonPointer.cs +++ b/src/Microsoft.OpenApi/JsonPointer.cs @@ -48,7 +48,7 @@ public JsonPointer ParentPointer return null; } - return new JsonPointer(Tokens.Take(Tokens.Length - 1).ToArray()); + return new(Tokens.Take(Tokens.Length - 1).ToArray()); } } diff --git a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs index ed328c433..fde7a54ea 100644 --- a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs +++ b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiPrimaryErrorMessageExtension.cs @@ -40,7 +40,7 @@ public void Write(IOpenApiWriter writer, OpenApiSpecVersion specVersion) public static OpenApiPrimaryErrorMessageExtension Parse(IOpenApiAny source) { if (source is not OpenApiBoolean rawObject) throw new ArgumentOutOfRangeException(nameof(source)); - return new OpenApiPrimaryErrorMessageExtension + return new() { IsPrimaryErrorMessage = rawObject.Value }; diff --git a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiReservedParameterExtension.cs b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiReservedParameterExtension.cs index 5cfa54082..77428e186 100644 --- a/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiReservedParameterExtension.cs +++ b/src/Microsoft.OpenApi/MicrosoftExtensions/OpenApiReservedParameterExtension.cs @@ -42,7 +42,7 @@ public bool? IsReserved public static OpenApiReservedParameterExtension Parse(IOpenApiAny source) { if (source is not OpenApiBoolean rawBoolean) throw new ArgumentOutOfRangeException(nameof(source)); - return new OpenApiReservedParameterExtension + return new() { IsReserved = rawBoolean.Value }; diff --git a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs index 4a5123e08..e945adc31 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiCallback.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiCallback.cs @@ -17,7 +17,7 @@ public class OpenApiCallback : IOpenApiReferenceable, IOpenApiExtensible, IEffec /// A Path Item Object used to define a callback request and expected responses. /// public Dictionary PathItems { get; set; } - = new Dictionary(); + = new(); /// /// Indicates if object is populated with data or is just a reference to the data @@ -69,7 +69,7 @@ public void AddPathItem(RuntimeExpression expression, OpenApiPathItem pathItem) if (PathItems == null) { - PathItems = new Dictionary(); + PathItems = new(); } PathItems.Add(expression, pathItem); diff --git a/src/Microsoft.OpenApi/Models/OpenApiConstants.cs b/src/Microsoft.OpenApi/Models/OpenApiConstants.cs index eccf3a616..40867d7e0 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiConstants.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiConstants.cs @@ -568,12 +568,12 @@ public static class OpenApiConstants /// /// Field: version3_0_0 /// - public static readonly Version version3_0_0 = new Version(3, 0, 0); + public static readonly Version version3_0_0 = new(3, 0, 0); /// /// Field: defaultUrl /// - public static readonly Uri defaultUrl = new Uri("http://localhost/"); + public static readonly Uri defaultUrl = new("http://localhost/"); #region V2.0 @@ -590,7 +590,7 @@ public static class OpenApiConstants /// /// Field: version2_0 /// - public static readonly Version version2_0 = new Version(2, 0); + public static readonly Version version2_0 = new(2, 0); /// /// Field: BasePath diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index c19de5e84..f55d9c205 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -209,7 +209,7 @@ public void SerializeAsV2(IOpenApiWriter writer) } // parameters var parameters = Components?.Parameters != null - ? new Dictionary(Components.Parameters) + ? new(Components.Parameters) : new Dictionary(); if (Components?.RequestBodies != null) @@ -417,7 +417,7 @@ public static string GenerateHashValue(OpenApiDocument doc) using var cryptoStream = new CryptoStream(Stream.Null, sha, CryptoStreamMode.Write); using var streamWriter = new StreamWriter(cryptoStream); - var openApiJsonWriter = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings { Terse = true }); + var openApiJsonWriter = new OpenApiJsonWriter(streamWriter, new() { Terse = true }); doc.SerializeAsV3(openApiJsonWriter); openApiJsonWriter.Flush(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiLink.cs b/src/Microsoft.OpenApi/Models/OpenApiLink.cs index 4f32dd6eb..773c06566 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiLink.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiLink.cs @@ -28,7 +28,7 @@ public class OpenApiLink : IOpenApiReferenceable, IOpenApiExtensible, IEffective /// A map representing parameters to pass to an operation as specified with operationId or identified via operationRef. /// public Dictionary Parameters { get; set; } = - new Dictionary(); + new(); /// /// A literal value or {expression} to use as a request body when calling the target operation. diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index 808e50aa0..a569c7d64 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -67,7 +67,7 @@ public class OpenApiOperation : IOpenApiSerializable, IOpenApiExtensible /// /// REQUIRED. The list of possible responses as they are returned from executing this operation. /// - public OpenApiResponses Responses { get; set; } = new OpenApiResponses(); + public OpenApiResponses Responses { get; set; } = new(); /// /// A map of possible out-of band callbacks related to the parent operation. @@ -226,11 +226,11 @@ public void SerializeAsV2(IOpenApiWriter writer) List parameters; if (Parameters == null) { - parameters = new List(); + parameters = new(); } else { - parameters = new List(Parameters); + parameters = new(Parameters); } if (RequestBody != null) @@ -253,7 +253,7 @@ public void SerializeAsV2(IOpenApiWriter writer) else if (RequestBody.Reference != null) { parameters.Add( - new OpenApiParameter + new() { UnresolvedReference = true, Reference = RequestBody.Reference diff --git a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs index 83da1e664..7ce175b2d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiRequestBody.cs @@ -182,7 +182,7 @@ internal IEnumerable ConvertToFormDataParameters() paramSchema.Type = "file"; paramSchema.Format = null; } - yield return new OpenApiFormDataParameter + yield return new() { Description = property.Value.Description, Name = property.Key, diff --git a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs index 95f913a2e..1eefee39b 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiServerVariable.cs @@ -26,7 +26,7 @@ public class OpenApiServerVariable : IOpenApiSerializable, IOpenApiExtensible /// /// An enumeration of string values to be used if the substitution options are from a limited set. /// - public List Enum { get; set; } = new List(); + public List Enum { get; set; } = new(); /// /// This object MAY be extended with Specification Extensions. @@ -45,7 +45,7 @@ public OpenApiServerVariable(OpenApiServerVariable serverVariable) { Description = serverVariable?.Description; Default = serverVariable?.Default; - Enum = serverVariable?.Enum != null ? new List(serverVariable?.Enum) : serverVariable?.Enum; + Enum = serverVariable?.Enum != null ? new(serverVariable?.Enum) : serverVariable?.Enum; Extensions = serverVariable?.Extensions != null ? new Dictionary(serverVariable?.Extensions) : serverVariable?.Extensions; } diff --git a/src/Microsoft.OpenApi/Services/CopyReferences.cs b/src/Microsoft.OpenApi/Services/CopyReferences.cs index 6307ed072..757471466 100644 --- a/src/Microsoft.OpenApi/Services/CopyReferences.cs +++ b/src/Microsoft.OpenApi/Services/CopyReferences.cs @@ -91,7 +91,7 @@ private void EnsureComponentsExists() { if (_target.Components == null) { - _target.Components = new OpenApiComponents(); + _target.Components = new(); } } diff --git a/src/Microsoft.OpenApi/Services/LoopDetector.cs b/src/Microsoft.OpenApi/Services/LoopDetector.cs index 2c9618213..904361f97 100644 --- a/src/Microsoft.OpenApi/Services/LoopDetector.cs +++ b/src/Microsoft.OpenApi/Services/LoopDetector.cs @@ -5,7 +5,7 @@ namespace Microsoft.OpenApi.Services { internal class LoopDetector { - private readonly Dictionary> _loopStacks = new Dictionary>(); + private readonly Dictionary> _loopStacks = new(); /// /// Maintain history of traversals to avoid stack overflows from cycles @@ -16,7 +16,7 @@ public bool PushLoop(T key) { if (!_loopStacks.TryGetValue(typeof(T), out var stack)) { - stack = new Stack(); + stack = new(); _loopStacks.Add(typeof(T), stack); } @@ -46,7 +46,7 @@ public void SaveLoop(T loop) { if (!Loops.ContainsKey(typeof(T))) { - Loops[typeof(T)] = new List(); + Loops[typeof(T)] = new(); } Loops[typeof(T)].Add(loop); } @@ -54,7 +54,7 @@ public void SaveLoop(T loop) /// /// List of Loops detected /// - public Dictionary> Loops { get; } = new Dictionary>(); + public Dictionary> Loops { get; } = new(); /// /// Reset loop tracking stack diff --git a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs index 5de121380..94bd995c4 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiFilterService.cs @@ -63,7 +63,7 @@ public static OpenApiDocument CreateFilteredDocument(OpenApiDocument source, Fun // Fetch and copy title, graphVersion and server info from OpenApiDoc var subset = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = source.Info.Title + " - Subset", Description = source.Info.Description, @@ -74,7 +74,7 @@ public static OpenApiDocument CreateFilteredDocument(OpenApiDocument source, Fun Extensions = source.Info.Extensions }, - Components = new OpenApiComponents { SecuritySchemes = source.Components.SecuritySchemes }, + Components = new() { SecuritySchemes = source.Components.SecuritySchemes }, SecurityRequirements = source.SecurityRequirements, Servers = source.Servers }; @@ -87,15 +87,15 @@ public static OpenApiDocument CreateFilteredDocument(OpenApiDocument source, Fun if (subset.Paths == null) { - subset.Paths = new OpenApiPaths(); - pathItem = new OpenApiPathItem(); + subset.Paths = new(); + pathItem = new(); subset.Paths.Add(pathKey, pathItem); } else { if (!subset.Paths.TryGetValue(pathKey, out pathItem)) { - pathItem = new OpenApiPathItem(); + pathItem = new(); subset.Paths.Add(pathKey, pathItem); } } @@ -284,7 +284,7 @@ private static string ExtractPath(string url, IList serverList) .FirstOrDefault(c => url.Contains(c)); return baseUrl == null ? - new Uri(new Uri(SRResource.DefaultBaseUri), url).GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.Unescaped) + new Uri(new(SRResource.DefaultBaseUri), url).GetComponents(UriComponents.Path | UriComponents.KeepDelimiter, UriFormat.Unescaped) : url.Split(new[] { baseUrl }, StringSplitOptions.None)[1]; } diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index cca475914..19e463e36 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -17,7 +17,7 @@ public class OpenApiReferenceResolver : OpenApiVisitorBase { private OpenApiDocument _currentDocument; private readonly bool _resolveRemoteReferences; - private List _errors = new List(); + private List _errors = new(); /// /// Initializes the class. @@ -205,7 +205,7 @@ private void ResolveTags(IList tags) if (resolvedTag == null) { - resolvedTag = new OpenApiTag + resolvedTag = new() { Name = tag.Reference.Id }; @@ -290,7 +290,7 @@ private void ResolveTags(IList tags) else { // Leave as unresolved reference - return new T + return new() { UnresolvedReference = true, Reference = reference diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index dbef8414b..2d55e7038 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -76,7 +76,7 @@ private OpenApiUrlTreeNode(string segment) /// The root node of the created directory structure. public static OpenApiUrlTreeNode Create() { - return new OpenApiUrlTreeNode(RootPathSegment); + return new(RootPathSegment); } /// diff --git a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs index 15cf7713c..87dd07b81 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs @@ -14,12 +14,12 @@ namespace Microsoft.OpenApi.Services /// public abstract class OpenApiVisitorBase { - private readonly Stack _path = new Stack(); + private readonly Stack _path = new(); /// /// Properties available to identify context of where an object is within OpenAPI Document /// - public CurrentKeys CurrentKeys { get; } = new CurrentKeys(); + public CurrentKeys CurrentKeys { get; } = new(); /// /// Allow Rule to indicate validation error occured at a deeper context level. diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index c123dbaa8..ddda44218 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -16,8 +16,8 @@ namespace Microsoft.OpenApi.Services public class OpenApiWalker { private readonly OpenApiVisitorBase _visitor; - private readonly Stack _schemaLoop = new Stack(); - private readonly Stack _pathItemLoop = new Stack(); + private readonly Stack _schemaLoop = new(); + private readonly Stack _pathItemLoop = new(); /// /// Initializes the class. diff --git a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs index 1d0636dec..dc7ae75d3 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -15,9 +15,9 @@ namespace Microsoft.OpenApi.Services /// public class OpenApiWorkspace { - private Dictionary _documents = new Dictionary(); - private Dictionary _fragments = new Dictionary(); - private Dictionary _artifacts = new Dictionary(); + private Dictionary _documents = new(); + private Dictionary _fragments = new(); + private Dictionary _artifacts = new(); /// /// A list of OpenApiDocuments contained in the workspace @@ -57,7 +57,7 @@ public OpenApiWorkspace(Uri baseUrl) /// public OpenApiWorkspace() { - BaseUrl = new Uri("file://" + Environment.CurrentDirectory + $"{Path.DirectorySeparatorChar}" ); + BaseUrl = new("file://" + Environment.CurrentDirectory + $"{Path.DirectorySeparatorChar}" ); } /// @@ -117,11 +117,11 @@ public void AddArtifact(string location, Stream artifact) /// public IOpenApiReferenceable ResolveReference(OpenApiReference reference) { - if (_documents.TryGetValue(new Uri(BaseUrl, reference.ExternalResource), out var doc)) + if (_documents.TryGetValue(new(BaseUrl, reference.ExternalResource), out var doc)) { return doc.ResolveReference(reference, false); } - else if (_fragments.TryGetValue(new Uri(BaseUrl, reference.ExternalResource), out var fragment)) + else if (_fragments.TryGetValue(new(BaseUrl, reference.ExternalResource), out var fragment)) { var jsonPointer = new JsonPointer($"/{reference.Id ?? string.Empty}"); return fragment.ResolveReference(jsonPointer); @@ -141,7 +141,7 @@ public Stream GetArtifact(string location) private Uri ToLocationUrl(string location) { - return new Uri(BaseUrl, location); + return new(BaseUrl, location); } } } diff --git a/src/Microsoft.OpenApi/Services/OperationSearch.cs b/src/Microsoft.OpenApi/Services/OperationSearch.cs index 8d251ec71..49cdac49c 100644 --- a/src/Microsoft.OpenApi/Services/OperationSearch.cs +++ b/src/Microsoft.OpenApi/Services/OperationSearch.cs @@ -43,7 +43,7 @@ public override void Visit(OpenApiPathItem pathItem) if (_predicate(CurrentKeys.Path, operationType, operation)) { - _searchResults.Add(new SearchResult + _searchResults.Add(new() { Operation = operation, Parameters = pathItem.Parameters, @@ -74,7 +74,7 @@ public override void Visit(IList parameters) private static CurrentKeys CopyCurrentKeys(CurrentKeys currentKeys, OperationType operationType) { - return new CurrentKeys + return new() { Path = currentKeys.Path, Operation = operationType, diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs index 468e97447..f2f3a649c 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiComponentsRules.cs @@ -17,14 +17,14 @@ public static class OpenApiComponentsRules /// /// The key regex. /// - public static Regex KeyRegex = new Regex(@"^[a-zA-Z0-9\.\-_]+$"); + public static Regex KeyRegex = new(@"^[a-zA-Z0-9\.\-_]+$"); /// /// All the fixed fields declared above are objects /// that MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$. /// public static ValidationRule KeyMustBeRegularExpression => - new ValidationRule( + new( (context, components) => { ValidateKeys(context, components.Schemas?.Keys, "schemas"); diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs index 0c949f8a7..b64704375 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs @@ -17,7 +17,7 @@ public static class OpenApiContactRules /// Email field MUST be email address. /// public static ValidationRule EmailMustBeEmailFormat => - new ValidationRule( + new( (context, item) => { context.Enter("email"); diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs index 7d01f1319..be0dc1538 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiDocumentRules.cs @@ -17,7 +17,7 @@ public static class OpenApiDocumentRules /// The Info field is required. /// public static ValidationRule OpenApiDocumentFieldIsMissing => - new ValidationRule( + new( (context, item) => { // info diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs index ea7086257..5d124e8de 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExtensionRules.cs @@ -17,7 +17,7 @@ public static class OpenApiExtensibleRules /// Extension name MUST start with "x-". /// public static ValidationRule ExtensionNameMustStartWithXDash => - new ValidationRule( + new( (context, item) => { context.Enter("extensions"); diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs index 8556eaa32..ff4fde4a2 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiExternalDocsRules.cs @@ -17,7 +17,7 @@ public static class OpenApiExternalDocsRules /// Validate the field is required. /// public static ValidationRule UrlIsRequired => - new ValidationRule( + new( (context, item) => { // url diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs index 6f76d9d91..c446a7b56 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiHeaderRules.cs @@ -16,7 +16,7 @@ public static class OpenApiHeaderRules /// Validate the data matches with the given data type. /// public static ValidationRule HeaderMismatchedDataType => - new ValidationRule( + new( (context, header) => { // example diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs index b3b533e32..88b534c02 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiInfoRules.cs @@ -17,7 +17,7 @@ public static class OpenApiInfoRules /// Validate the field is required. /// public static ValidationRule InfoRequiredFields => - new ValidationRule( + new( (context, item) => { // title diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs index 89b88ca9d..edbf19bf5 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiLicenseRules.cs @@ -17,7 +17,7 @@ public static class OpenApiLicenseRules /// REQUIRED. /// public static ValidationRule LicenseRequiredFields => - new ValidationRule( + new( (context, license) => { context.Enter("name"); diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs index 347b80e6d..0e78b38de 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs @@ -24,7 +24,7 @@ public static class OpenApiMediaTypeRules /// Validate the data matches with the given data type. /// public static ValidationRule MediaTypeMismatchedDataType => - new ValidationRule( + new( (context, mediaType) => { // example diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs index 95444fb9a..de31d933d 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiOAuthFlowRules.cs @@ -17,7 +17,7 @@ public static class OpenApiOAuthFlowRules /// Validate the field is required. /// public static ValidationRule OAuthFlowRequiredFields => - new ValidationRule( + new( (context, flow) => { // authorizationUrl diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs index 878e2db10..5c19ce1d9 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiParameterRules.cs @@ -17,7 +17,7 @@ public static class OpenApiParameterRules /// Validate the field is required. /// public static ValidationRule ParameterRequiredFields => - new ValidationRule( + new( (context, item) => { // name @@ -43,7 +43,7 @@ public static class OpenApiParameterRules /// Validate the "required" field is true when "in" is path. /// public static ValidationRule RequiredMustBeTrueWhenInIsPath => - new ValidationRule( + new( (context, item) => { // required @@ -62,7 +62,7 @@ public static class OpenApiParameterRules /// Validate the data matches with the given data type. /// public static ValidationRule ParameterMismatchedDataType => - new ValidationRule( + new( (context, parameter) => { // example @@ -100,7 +100,7 @@ public static class OpenApiParameterRules /// Validate that a path parameter should always appear in the path /// public static ValidationRule PathParameterShouldBeInThePath => - new ValidationRule( + new( (context, parameter) => { if (parameter.In == ParameterLocation.Path && diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs index f6232f15d..d4e4f5727 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs @@ -16,7 +16,7 @@ public static class OpenApiPathsRules /// A relative path to an individual endpoint. The field name MUST begin with a slash. /// public static ValidationRule PathNameMustBeginWithSlash => - new ValidationRule( + new( (context, item) => { foreach (var pathName in item.Keys) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs index 11b228e74..0f725c90e 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponseRules.cs @@ -17,7 +17,7 @@ public static class OpenApiResponseRules /// Validate the field is required. /// public static ValidationRule ResponseRequiredFields => - new ValidationRule( + new( (context, response) => { // description diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs index 5df74c2e9..1afe9a388 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiResponsesRules.cs @@ -17,7 +17,7 @@ public static class OpenApiResponsesRules /// An OpenAPI operation must contain at least one response /// public static ValidationRule ResponsesMustContainAtLeastOneResponse => - new ValidationRule( + new( (context, responses) => { if (!responses.Keys.Any()) @@ -31,7 +31,7 @@ public static class OpenApiResponsesRules /// The response key must either be "default" or an HTTP status code (1xx, 2xx, 3xx, 4xx, 5xx). /// public static ValidationRule ResponsesMustBeIdentifiedByDefaultOrStatusCode => - new ValidationRule( + new( (context, responses) => { foreach (var key in responses.Keys) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs index 6753a3e65..493341acf 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiSchemaRules.cs @@ -17,7 +17,7 @@ public static class OpenApiSchemaRules /// Validate the data matches with the given data type. /// public static ValidationRule SchemaMismatchedDataType => - new ValidationRule( + new( (context, schema) => { // default @@ -60,7 +60,7 @@ public static class OpenApiSchemaRules /// Validates Schema Discriminator /// public static ValidationRule ValidateSchemaDiscriminator => - new ValidationRule( + new( (context, schema) => { // discriminator diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs index 67fc5eef2..292fd1fd0 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiServerRules.cs @@ -17,7 +17,7 @@ public static class OpenApiServerRules /// Validate the field is required. /// public static ValidationRule ServerRequiredFields => - new ValidationRule( + new( (context, server) => { context.Enter("url"); diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs index 9dac45966..f28732e1e 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiTagRules.cs @@ -17,7 +17,7 @@ public static class OpenApiTagRules /// Validate the field is required. /// public static ValidationRule TagRequiredFields => - new ValidationRule( + new( (context, tag) => { context.Enter("name"); diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index 5199f82bc..6cc4d3a05 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -52,7 +52,7 @@ public static ValidationRuleSet GetDefaultRuleSet() // We create a new instance of ValidationRuleSet per call as a safeguard // against unintentional modification of the private _defaultRuleSet. - return new ValidationRuleSet(_defaultRuleSet); + return new(_defaultRuleSet); } /// @@ -62,7 +62,7 @@ public static ValidationRuleSet GetEmptyRuleSet() { // We create a new instance of ValidationRuleSet per call as a safeguard // against unintentional modification of the private _defaultRuleSet. - return new ValidationRuleSet(); + return new(); } /// diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs index 99cc75841..c39244745 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs @@ -52,10 +52,10 @@ public OpenApiWriterBase(TextWriter textWriter, OpenApiWriterSettings settings) Writer = textWriter; Writer.NewLine = "\n"; - Scopes = new Stack(); + Scopes = new(); if (settings == null) { - settings = new OpenApiWriterSettings(); + settings = new(); } Settings = settings; } diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs index 7c143d456..dda995b0f 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterSettings.cs @@ -33,7 +33,7 @@ public class OpenApiWriterSettings [Obsolete("Use InlineLocalReference and InlineExternalReference settings instead")] private ReferenceInlineSetting referenceInline = ReferenceInlineSetting.DoNotInlineReferences; - internal LoopDetector LoopDetector { get; } = new LoopDetector(); + internal LoopDetector LoopDetector { get; } = new(); /// /// Indicates how references in the source document should be handled. /// diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs index c261a8e46..a5bf74219 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Formatters/PowerShellFormatterTests.cs @@ -93,7 +93,7 @@ public void ResolveFunctionParameters() private static OpenApiDocument GetSampleOpenApiDocument() { - return new OpenApiDocument + return new() { Info = new() { Title = "Test", Version = "1.0" }, Servers = new List { new() { Url = "https://localhost/" } }, @@ -108,7 +108,7 @@ private static OpenApiDocument GetSampleOpenApiDocument() OperationId = "Foo.GetFoo", Parameters = new List { - new OpenApiParameter + new() { Name = "ids", In = ParameterLocation.Query, @@ -118,10 +118,10 @@ private static OpenApiDocument GetSampleOpenApiDocument() "application/json", new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } @@ -157,8 +157,8 @@ private static OpenApiDocument GetSampleOpenApiDocument() { AnyOf = new List { - new OpenApiSchema { Type = "number" }, - new OpenApiSchema { Type = "string" } + new() { Type = "number" }, + new() { Type = "string" } }, Format = "float", Nullable = true @@ -169,8 +169,8 @@ private static OpenApiDocument GetSampleOpenApiDocument() { OneOf = new List { - new OpenApiSchema { Type = "number", Format = "double" }, - new OpenApiSchema { Type = "string" } + new() { Type = "number", Format = "double" }, + new() { Type = "string" } } } } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs index 03c611583..0f353b326 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiFilterServiceTests.cs @@ -19,7 +19,7 @@ public class OpenApiFilterServiceTests public OpenApiFilterServiceTests() { _openApiDocumentMock = OpenApiDocumentMock.CreateOpenApiDocument(); - _mockLogger = new Mock>(); + _mockLogger = new(); _logger = _mockLogger.Object; } diff --git a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index d4e97ed9b..b2b6b6c9b 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -92,7 +92,7 @@ public void ShowCommandGeneratesMermaidDiagramAsMarkdown() { var openApiDoc = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Test", Version = "1.0.0" @@ -113,7 +113,7 @@ public void ShowCommandGeneratesMermaidDiagramAsHtml() { var openApiDoc = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Test", Version = "1.0.0" @@ -136,7 +136,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileWithMermaidDiagram() var options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml"), - Output = new FileInfo("sample.md") + Output = new("sample.md") }; await OpenApiService.ShowOpenApiDocument(options, _logger); @@ -163,7 +163,7 @@ public async Task ShowCommandGeneratesMermaidMarkdownFileFromCsdlWithMermaidDiag { Csdl = Path.Combine("UtilityFiles", "Todo.xml"), CsdlFilter = "todos", - Output = new FileInfo("sample.md") + Output = new("sample.md") }; // create a dummy ILogger instance for testing @@ -211,7 +211,7 @@ public async Task TransformCommandConvertsOpenApi() HidiOptions options = new HidiOptions { OpenApi = Path.Combine("UtilityFiles", "SampleOpenApi.yml"), - Output = new FileInfo("sample.json"), + Output = new("sample.json"), CleanOutput = true, TerseOutput = false, InlineLocal = false, diff --git a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs index 106509a3d..67b06f72a 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/UtilityFiles/OpenApiDocumentMock.cs @@ -22,21 +22,21 @@ public static OpenApiDocument CreateOpenApiDocument() var document = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "People", Version = "v1.0" }, Servers = new List { - new OpenApiServer + new() { Url = "https://graph.microsoft.com/v1.0" } }, - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem() // root path + ["/"] = new() // root path { Operations = new Dictionary { @@ -44,10 +44,10 @@ public static OpenApiDocument CreateOpenApiDocument() OperationType.Get, new OpenApiOperation { OperationId = "graphService.GetGraphService", - Responses = new OpenApiResponses + Responses = new() { { - "200",new OpenApiResponse + "200",new() { Description = "OK" } @@ -57,7 +57,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/reports/microsoft.graph.getTeamsUserActivityCounts(period={period})"] = new OpenApiPathItem + ["/reports/microsoft.graph.getTeamsUserActivityCounts(period={period})"] = new() { Operations = new Dictionary { @@ -67,7 +67,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "reports.Functions" } @@ -78,22 +78,22 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter + new() { Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } } }, - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Success", Content = new Dictionary @@ -102,7 +102,7 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Type = "array" } @@ -118,12 +118,12 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter + new() { Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -131,7 +131,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/reports/microsoft.graph.getTeamsUserActivityUserDetail(date={date})"] = new OpenApiPathItem + ["/reports/microsoft.graph.getTeamsUserActivityUserDetail(date={date})"] = new() { Operations = new Dictionary { @@ -141,7 +141,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "reports.Functions" } @@ -152,22 +152,22 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter + new() { Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } } }, - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Success", Content = new Dictionary @@ -176,7 +176,7 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Type = "array" } @@ -191,19 +191,19 @@ public static OpenApiDocument CreateOpenApiDocument() }, Parameters = new List { - new OpenApiParameter + new() { Name = "period", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } } }, - ["/users"] = new OpenApiPathItem + ["/users"] = new() { Operations = new Dictionary { @@ -213,7 +213,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "users.user" } @@ -221,10 +221,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "users.user.ListUser", Summary = "Get entities from users", - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved entities", Content = new Dictionary @@ -233,7 +233,7 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Title = "Collection of user", Type = "object", @@ -244,9 +244,9 @@ public static OpenApiDocument CreateOpenApiDocument() new OpenApiSchema { Type = "array", - Items = new OpenApiSchema + Items = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "microsoft.graph.user" @@ -266,7 +266,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/users/{user-id}"] = new OpenApiPathItem + ["/users/{user-id}"] = new() { Operations = new Dictionary { @@ -276,7 +276,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "users.user" } @@ -284,10 +284,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "users.user.GetUser", Summary = "Get entity from users by key", - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved entity", Content = new Dictionary @@ -296,9 +296,9 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "microsoft.graph.user" @@ -318,7 +318,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "users.user" } @@ -326,10 +326,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "users.user.UpdateUser", Summary = "Update entity in users", - Responses = new OpenApiResponses + Responses = new() { { - "204", new OpenApiResponse + "204", new() { Description = "Success" } @@ -339,7 +339,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/users/{user-id}/messages/{message-id}"] = new OpenApiPathItem + ["/users/{user-id}/messages/{message-id}"] = new() { Operations = new Dictionary { @@ -349,7 +349,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "users.message" } @@ -360,23 +360,23 @@ public static OpenApiDocument CreateOpenApiDocument() Description = "The messages in a mailbox or folder. Read-only. Nullable.", Parameters = new List { - new OpenApiParameter + new() { Name = "$select", In = ParameterLocation.Query, Required = true, Description = "Select properties to be returned", - Schema = new OpenApiSchema + Schema = new() { Type = "array" } // missing explode parameter } }, - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved navigation property", Content = new Dictionary @@ -385,9 +385,9 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "microsoft.graph.message" @@ -403,7 +403,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/administrativeUnits/{administrativeUnit-id}/microsoft.graph.restore"] = new OpenApiPathItem + ["/administrativeUnits/{administrativeUnit-id}/microsoft.graph.restore"] = new() { Operations = new Dictionary { @@ -413,7 +413,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "administrativeUnits.Actions" } @@ -424,23 +424,23 @@ public static OpenApiDocument CreateOpenApiDocument() Parameters = new List { { - new OpenApiParameter + new() { Name = "administrativeUnit-id", In = ParameterLocation.Path, Required = true, Description = "key: id of administrativeUnit", - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } } }, - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Success", Content = new Dictionary @@ -449,11 +449,11 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { AnyOf = new List { - new OpenApiSchema + new() { Type = "string" } @@ -470,7 +470,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/applications/{application-id}/logo"] = new OpenApiPathItem + ["/applications/{application-id}/logo"] = new() { Operations = new Dictionary { @@ -480,7 +480,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "applications.application" } @@ -488,10 +488,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "applications.application.UpdateLogo", Summary = "Update media content for application in applications", - Responses = new OpenApiResponses + Responses = new() { { - "204", new OpenApiResponse + "204", new() { Description = "Success" } @@ -501,7 +501,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/security/hostSecurityProfiles"] = new OpenApiPathItem + ["/security/hostSecurityProfiles"] = new() { Operations = new Dictionary { @@ -511,7 +511,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "security.hostSecurityProfile" } @@ -519,10 +519,10 @@ public static OpenApiDocument CreateOpenApiDocument() }, OperationId = "security.ListHostSecurityProfiles", Summary = "Get hostSecurityProfiles from security", - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved navigation property", Content = new Dictionary @@ -531,7 +531,7 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Title = "Collection of hostSecurityProfile", Type = "object", @@ -542,9 +542,9 @@ public static OpenApiDocument CreateOpenApiDocument() new OpenApiSchema { Type = "array", - Items = new OpenApiSchema + Items = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "microsoft.graph.networkInterface" @@ -564,7 +564,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/communications/calls/{call-id}/microsoft.graph.keepAlive"] = new OpenApiPathItem + ["/communications/calls/{call-id}/microsoft.graph.keepAlive"] = new() { Operations = new Dictionary { @@ -574,7 +574,7 @@ public static OpenApiDocument CreateOpenApiDocument() Tags = new List { { - new OpenApiTag + new() { Name = "communications.Actions" } @@ -584,13 +584,13 @@ public static OpenApiDocument CreateOpenApiDocument() Summary = "Invoke action keepAlive", Parameters = new List { - new OpenApiParameter + new() { Name = "call-id", In = ParameterLocation.Path, Description = "key: id of call", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" }, @@ -602,10 +602,10 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - Responses = new OpenApiResponses + Responses = new() { { - "204", new OpenApiResponse + "204", new() { Description = "Success" } @@ -621,7 +621,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/groups/{group-id}/events/{event-id}/calendar/events/microsoft.graph.delta"] = new OpenApiPathItem + ["/groups/{group-id}/events/{event-id}/calendar/events/microsoft.graph.delta"] = new() { Operations = new Dictionary { @@ -630,7 +630,7 @@ public static OpenApiDocument CreateOpenApiDocument() { Tags = new List { - new OpenApiTag + new() { Name = "groups.Functions" } @@ -639,13 +639,13 @@ public static OpenApiDocument CreateOpenApiDocument() Summary = "Invoke function delta", Parameters = new List { - new OpenApiParameter + new() { Name = "group-id", In = ParameterLocation.Path, Description = "key: id of group", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" }, @@ -656,13 +656,13 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - new OpenApiParameter + new() { Name = "event-id", In = ParameterLocation.Path, Description = "key: id of event", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" }, @@ -674,10 +674,10 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Success", Content = new Dictionary @@ -686,10 +686,10 @@ public static OpenApiDocument CreateOpenApiDocument() applicationJsonMediaType, new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "microsoft.graph.event" @@ -711,7 +711,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - ["/applications/{application-id}/createdOnBehalfOf/$ref"] = new OpenApiPathItem + ["/applications/{application-id}/createdOnBehalfOf/$ref"] = new() { Operations = new Dictionary { @@ -720,7 +720,7 @@ public static OpenApiDocument CreateOpenApiDocument() { Tags = new List { - new OpenApiTag + new() { Name = "applications.directoryObject" } @@ -732,7 +732,7 @@ public static OpenApiDocument CreateOpenApiDocument() } } }, - Components = new OpenApiComponents + Components = new() { Schemas = new Dictionary { diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs index 4231ae4b7..4d1b6675d 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs @@ -40,11 +40,11 @@ public void DetectedSpecificationVersionShouldBeV3_0() public async Task DiagnosticReportMergedForExternalReference() { // Create a reader that will resolve all references - var reader = new OpenApiStreamReader(new OpenApiReaderSettings + var reader = new OpenApiStreamReader(new() { LoadExternalRefs = true, CustomExternalLoader = new ResourceLoader(), - BaseUrl = new Uri("fie://c:\\") + BaseUrl = new("fie://c:\\") }); ReadResult result; @@ -57,7 +57,7 @@ public async Task DiagnosticReportMergedForExternalReference() Assert.NotNull(result.OpenApiDocument.Workspace); Assert.True(result.OpenApiDocument.Workspace.Contains("TodoReference.yaml")); result.OpenApiDiagnostic.Errors.Should().BeEquivalentTo(new List { - new OpenApiError( new OpenApiException("[File: ./TodoReference.yaml] Invalid Reference identifier 'object-not-existing'.")) }); + new( new OpenApiException("[File: ./TodoReference.yaml] Invalid Reference identifier 'object-not-existing'.")) }); } } @@ -70,7 +70,7 @@ public Stream Load(Uri uri) public Task LoadAsync(Uri uri) { - var path = new Uri(new Uri("http://example.org/OpenApiReaderTests/Samples/OpenApiDiagnosticReportMerged/"), uri).AbsolutePath; + var path = new Uri(new("http://example.org/OpenApiReaderTests/Samples/OpenApiDiagnosticReportMerged/"), uri).AbsolutePath; path = path.Substring(1); // remove leading slash return Task.FromResult(Resources.GetStream(path)); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs index 0f6bbce15..91e271549 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiStreamReaderTests.cs @@ -14,7 +14,7 @@ public class OpenApiStreamReaderTests public void StreamShouldCloseIfLeaveStreamOpenSettingEqualsFalse() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); - var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LeaveStreamOpen = false }); + var reader = new OpenApiStreamReader(new() { LeaveStreamOpen = false }); reader.Read(stream, out _); Assert.False(stream.CanRead); } @@ -23,7 +23,7 @@ public void StreamShouldCloseIfLeaveStreamOpenSettingEqualsFalse() public void StreamShouldNotCloseIfLeaveStreamOpenSettingEqualsTrue() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "petStore.yaml")); - var reader = new OpenApiStreamReader(new OpenApiReaderSettings { LeaveStreamOpen = true}); + var reader = new OpenApiStreamReader(new() { LeaveStreamOpen = true}); reader.Read(stream, out _); Assert.True(stream.CanRead); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index 21e2ec759..8f9430a87 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -18,11 +18,11 @@ public class OpenApiWorkspaceStreamTests public async Task LoadingDocumentWithResolveAllReferencesShouldLoadDocumentIntoWorkspace() { // Create a reader that will resolve all references - var reader = new OpenApiStreamReader(new OpenApiReaderSettings + var reader = new OpenApiStreamReader(new() { LoadExternalRefs = true, CustomExternalLoader = new MockLoader(), - BaseUrl = new Uri("file://c:\\") + BaseUrl = new("file://c:\\") }); // Todo: this should be ReadAsync @@ -48,11 +48,11 @@ public async Task LoadingDocumentWithResolveAllReferencesShouldLoadDocumentIntoW public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWorkspace() { // Create a reader that will resolve all references - var reader = new OpenApiStreamReader(new OpenApiReaderSettings + var reader = new OpenApiStreamReader(new() { LoadExternalRefs = true, CustomExternalLoader = new ResourceLoader(), - BaseUrl = new Uri("fie://c:\\") + BaseUrl = new("fie://c:\\") }); ReadResult result; @@ -107,7 +107,7 @@ public Stream Load(Uri uri) public Task LoadAsync(Uri uri) { - var path = new Uri(new Uri("http://example.org/V3Tests/Samples/OpenApiWorkspace/"), uri).AbsolutePath; + var path = new Uri(new("http://example.org/V3Tests/Samples/OpenApiWorkspace/"), uri).AbsolutePath; path = path.Substring(1); // remove leading slash return Task.FromResult(Resources.GetStream(path)); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs index 829cecaff..f1af6f933 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ParseNodeTests.cs @@ -30,7 +30,7 @@ public void BrokenSimpleList() diagnostic.Errors.Should().BeEquivalentTo(new List { - new OpenApiError(new OpenApiReaderException("Expected a value.") { + new(new OpenApiReaderException("Expected a value.") { Pointer = "#line=4" }) }); @@ -60,7 +60,7 @@ public void BadSchema() diagnostic.Errors.Should().BeEquivalentTo(new List { - new OpenApiError(new OpenApiReaderException("schema must be a map/object") { + new(new OpenApiReaderException("schema must be a map/object") { Pointer = "#/paths/~1foo/get/responses/200/content/application~1json/schema" }) }); diff --git a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs index 884bd28fc..0f36d7d89 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ParseNodes/OpenApiAnyConverterTests.cs @@ -44,26 +44,26 @@ public void ParseObjectAsAnyShouldSucceed() Type = "object", Properties = { - ["aString"] = new OpenApiSchema + ["aString"] = new() { Type = "string" }, - ["aInteger"] = new OpenApiSchema + ["aInteger"] = new() { Type = "integer", Format = "int32" }, - ["aDouble"] = new OpenApiSchema + ["aDouble"] = new() { Type = "number", Format = "double" }, - ["aDateTime"] = new OpenApiSchema + ["aDateTime"] = new() { Type = "string", Format = "date-time" }, - ["aDate"] = new OpenApiSchema + ["aDate"] = new() { Type = "string", Format = "date" @@ -130,54 +130,54 @@ public void ParseNestedObjectAsAnyShouldSucceed() Type = "object", Properties = { - ["aString"] = new OpenApiSchema + ["aString"] = new() { Type = "string" }, - ["aInteger"] = new OpenApiSchema + ["aInteger"] = new() { Type = "integer", Format = "int32" }, - ["aArray"] = new OpenApiSchema + ["aArray"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "integer", Format = "int64" } }, - ["aNestedArray"] = new OpenApiSchema + ["aNestedArray"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "object", Properties = { - ["aFloat"] = new OpenApiSchema + ["aFloat"] = new() { Type = "number", Format = "float" }, - ["aPassword"] = new OpenApiSchema + ["aPassword"] = new() { Type = "string", Format = "password" }, - ["aArray"] = new OpenApiSchema + ["aArray"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string", } }, - ["aDictionary"] = new OpenApiSchema + ["aDictionary"] = new() { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "integer", Format = "int64" @@ -186,24 +186,24 @@ public void ParseNestedObjectAsAnyShouldSucceed() } } }, - ["aObject"] = new OpenApiSchema + ["aObject"] = new() { Type = "array", Properties = { - ["aDate"] = new OpenApiSchema + ["aDate"] = new() { Type = "string", Format = "date" } } }, - ["aDouble"] = new OpenApiSchema + ["aDouble"] = new() { Type = "number", Format = "double" }, - ["aDateTime"] = new OpenApiSchema + ["aDateTime"] = new() { Type = "string", Format = "date-time" @@ -310,36 +310,36 @@ public void ParseNestedObjectAsAnyWithPartialSchemaShouldSucceed() Type = "object", Properties = { - ["aString"] = new OpenApiSchema + ["aString"] = new() { Type = "string" }, - ["aArray"] = new OpenApiSchema + ["aArray"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "integer" } }, - ["aNestedArray"] = new OpenApiSchema + ["aNestedArray"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "object", Properties = { - ["aFloat"] = new OpenApiSchema + ["aFloat"] = new() { }, - ["aPassword"] = new OpenApiSchema + ["aPassword"] = new() { }, - ["aArray"] = new OpenApiSchema + ["aArray"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string", } @@ -347,21 +347,21 @@ public void ParseNestedObjectAsAnyWithPartialSchemaShouldSucceed() } } }, - ["aObject"] = new OpenApiSchema + ["aObject"] = new() { Type = "array", Properties = { - ["aDate"] = new OpenApiSchema + ["aDate"] = new() { Type = "string" } } }, - ["aDouble"] = new OpenApiSchema + ["aDouble"] = new() { }, - ["aDateTime"] = new OpenApiSchema + ["aDateTime"] = new() { } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs index 9bd42a0e3..737f4310c 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV2Tests.cs @@ -14,7 +14,7 @@ public class ConvertToOpenApiReferenceV2Tests public ConvertToOpenApiReferenceV2Tests() { - Diagnostic = new OpenApiDiagnostic(); + Diagnostic = new(); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs index b8555a890..2f00de3c2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/ConvertToOpenApiReferenceV3Tests.cs @@ -14,7 +14,7 @@ public class ConvertToOpenApiReferenceV3Tests public ConvertToOpenApiReferenceV3Tests() { - Diagnostic = new OpenApiDiagnostic(); + Diagnostic = new(); } [Fact] diff --git a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs index 546b2c1a8..b51f696e0 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/ReferenceService/TryLoadReferenceV2Tests.cs @@ -46,21 +46,21 @@ public void LoadSchemaReference() }, Properties = { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "SampleObject" @@ -98,12 +98,12 @@ public void LoadParameterReference() In = ParameterLocation.Query, Description = "number of items to skip", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Parameter, Id = "skipParam" @@ -140,7 +140,7 @@ public void LoadSecuritySchemeReference() Type = SecuritySchemeType.ApiKey, Name = "api_key", In = ParameterLocation.Header, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "api_key_sample" @@ -175,14 +175,14 @@ public void LoadResponseReference() new OpenApiResponse { Description = "Entity not found.", - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Response, Id = "NotFound" }, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType() + ["application/json"] = new() } } ); @@ -216,24 +216,24 @@ public void LoadResponseAndSchemaReference() Description = "General Error", Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Description = "Sample description", Required = new HashSet {"name" }, Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "SampleObject2", @@ -242,7 +242,7 @@ public void LoadResponseAndSchemaReference() } } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Response, Id = "GeneralError" diff --git a/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs b/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs index 654be0858..fa8b939e2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/TestHelper.cs @@ -16,9 +16,9 @@ public static MapNode CreateYamlMapNode(Stream stream) yamlStream.Load(new StreamReader(stream)); var yamlNode = yamlStream.Documents.First().RootNode; - var context = new ParsingContext(new OpenApiDiagnostic()); + var context = new ParsingContext(new()); - return new MapNode(context, (YamlMappingNode)yamlNode); + return new(context, (YamlMappingNode)yamlNode); } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs index d3197476f..a7d586bf2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiContactTests.cs @@ -3,7 +3,6 @@ using FluentAssertions; using Microsoft.OpenApi.Models; -using System; using Xunit; namespace Microsoft.OpenApi.Readers.Tests.V2Tests @@ -34,7 +33,7 @@ public void ParseStringContactFragmentShouldSucceed() { Email = "support@swagger.io", Name = "API Support", - Url = new Uri("http://www.swagger.io/support") + Url = new("http://www.swagger.io/support") }); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs index 6f0b7da9a..9e76f6491 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiDocumentTests.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Threading; using FluentAssertions; @@ -40,7 +39,7 @@ public void ShouldThrowWhenReferenceTypeIsInvalid() var doc = reader.Read(input, out var diagnostic); diagnostic.Errors.Should().BeEquivalentTo(new List { - new OpenApiError( new OpenApiException("Unknown reference type 'defi888nition'")) }); + new( new OpenApiException("Unknown reference type 'defi888nition'")) }); doc.Should().NotBeNull(); } @@ -69,7 +68,7 @@ public void ShouldThrowWhenReferenceDoesNotExist() var doc = reader.Read(input, out var diagnostic); diagnostic.Errors.Should().BeEquivalentTo(new List { - new OpenApiError( new OpenApiException("Invalid Reference identifier 'doesnotexist'.")) }); + new( new OpenApiException("Invalid Reference identifier 'doesnotexist'.")) }); doc.Should().NotBeNull(); } @@ -81,8 +80,8 @@ public void ShouldThrowWhenReferenceDoesNotExist() [InlineData("da-DK")] public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) { - Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); - Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture); + Thread.CurrentThread.CurrentCulture = new(culture); + Thread.CurrentThread.CurrentUICulture = new(culture); var openApiDoc = new OpenApiStringReader().Read( """ @@ -108,7 +107,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) openApiDoc.Should().BeEquivalentTo( new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Simple Document", Version = "0.9.1", @@ -117,16 +116,16 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) ["x-extension"] = new OpenApiDouble(2.335) } }, - Components = new OpenApiComponents + Components = new() { Schemas = { - ["sampleSchema"] = new OpenApiSchema + ["sampleSchema"] = new() { Type = "object", Properties = { - ["sampleProperty"] = new OpenApiSchema + ["sampleProperty"] = new() { Type = "double", Minimum = (decimal)100.54, @@ -135,7 +134,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) ExclusiveMinimum = false } }, - Reference = new OpenApiReference + Reference = new() { Id = "sampleSchema", Type = ReferenceType.Schema @@ -143,7 +142,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) } } }, - Paths = new OpenApiPaths() + Paths = new() }); context.Should().BeEquivalentTo( @@ -159,7 +158,7 @@ public void ShouldParseProducesInAnyOrder() var okSchema = new OpenApiSchema { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "Item", @@ -178,7 +177,7 @@ public void ShouldParseProducesInAnyOrder() var errorSchema = new OpenApiSchema { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "Error", @@ -207,7 +206,7 @@ public void ShouldParseProducesInAnyOrder() var okMediaType = new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = okSchema @@ -221,7 +220,7 @@ public void ShouldParseProducesInAnyOrder() doc.Should().BeEquivalentTo(new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Two responses", Version = "1.0.0" @@ -233,17 +232,17 @@ public void ShouldParseProducesInAnyOrder() Url = "https://" } }, - Paths = new OpenApiPaths + Paths = new() { - ["/items"] = new OpenApiPathItem + ["/items"] = new() { Operations = { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Responses = { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "An OK response", Content = @@ -252,7 +251,7 @@ public void ShouldParseProducesInAnyOrder() ["application/xml"] = okMediaType, } }, - ["default"] = new OpenApiResponse + ["default"] = new() { Description = "An error response", Content = @@ -263,11 +262,11 @@ public void ShouldParseProducesInAnyOrder() } } }, - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { Responses = { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "An OK response", Content = @@ -275,7 +274,7 @@ public void ShouldParseProducesInAnyOrder() ["html/text"] = okMediaType } }, - ["default"] = new OpenApiResponse + ["default"] = new() { Description = "An error response", Content = @@ -285,11 +284,11 @@ public void ShouldParseProducesInAnyOrder() } } }, - [OperationType.Patch] = new OpenApiOperation + [OperationType.Patch] = new() { Responses = { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "An OK response", Content = @@ -298,7 +297,7 @@ public void ShouldParseProducesInAnyOrder() ["application/xml"] = okMediaType, } }, - ["default"] = new OpenApiResponse + ["default"] = new() { Description = "An error response", Content = @@ -312,7 +311,7 @@ public void ShouldParseProducesInAnyOrder() } } }, - Components = new OpenApiComponents + Components = new() { Schemas = { @@ -338,7 +337,7 @@ public void ShouldAssignSchemaToAllResponses() var successSchema = new OpenApiSchema { Type = "array", - Items = new OpenApiSchema + Items = new() { Properties = { { "id", new OpenApiSchema @@ -348,7 +347,7 @@ public void ShouldAssignSchemaToAllResponses() } } }, - Reference = new OpenApiReference + Reference = new() { Id = "Item", Type = ReferenceType.Schema, @@ -376,7 +375,7 @@ public void ShouldAssignSchemaToAllResponses() } } }, - Reference = new OpenApiReference + Reference = new() { Id = "Error", Type = ReferenceType.Schema, @@ -418,7 +417,7 @@ public void ShouldAllowComponentsThatJustContainAReference() public void ParseDocumentWithDefaultContentTypeSettingShouldSucceed() { using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "docWithEmptyProduces.yaml")); - var doc = new OpenApiStreamReader(new OpenApiReaderSettings { DefaultContentType = new List { "application/json" } }) + var doc = new OpenApiStreamReader(new() { DefaultContentType = new() { "application/json" } }) .Read(stream, out OpenApiDiagnostic 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/V2Tests/OpenApiHeaderTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs index 830f0aa9c..39dff183f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiHeaderTests.cs @@ -33,7 +33,7 @@ public void ParseHeaderWithDefaultShouldSucceed() header.Should().BeEquivalentTo( new OpenApiHeader { - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float", @@ -59,7 +59,7 @@ public void ParseHeaderWithEnumShouldSucceed() header.Should().BeEquivalentTo( new OpenApiHeader { - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float", diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs index 726bbd03c..d33aa5be2 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs @@ -19,75 +19,75 @@ public class OpenApiOperationTests { private const string SampleFolderPath = "V2Tests/Samples/OpenApiOperation/"; - private static readonly OpenApiOperation _basicOperation = new OpenApiOperation + private static readonly OpenApiOperation _basicOperation = new() { Summary = "Updates a pet in the store", Description = "", OperationId = "updatePet", Parameters = new List { - new OpenApiParameter + new() { Name = "petId", In = ParameterLocation.Path, Description = "ID of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Pet updated.", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } } } }; private static readonly OpenApiOperation _operationWithFormData = - new OpenApiOperation + new() { Summary = "Updates a pet in the store with form data", Description = "", OperationId = "updatePetWithForm", Parameters = new List { - new OpenApiParameter + new() { Name = "petId", In = ParameterLocation.Path, Description = "ID of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } }, - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/x-www-form-urlencoded"] = new OpenApiMediaType + ["application/x-www-form-urlencoded"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" @@ -99,18 +99,18 @@ public class OpenApiOperationTests } } }, - ["multipart/form-data"] = new OpenApiMediaType + ["multipart/form-data"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" @@ -124,58 +124,58 @@ public class OpenApiOperationTests } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Pet updated.", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } }, - ["405"] = new OpenApiResponse + ["405"] = new() { Description = "Invalid input", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } } } }; - private static readonly OpenApiOperation _operationWithBody = new OpenApiOperation + private static readonly OpenApiOperation _operationWithBody = new() { Summary = "Updates a pet in the store with request body", Description = "", OperationId = "updatePetWithBody", Parameters = new List { - new OpenApiParameter + new() { Name = "petId", In = ParameterLocation.Path, Description = "ID of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } }, }, - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "Pet to update with", Required = true, Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "object" } @@ -185,24 +185,24 @@ public class OpenApiOperationTests [OpenApiConstants.BodyName] = new OpenApiString("petObject") } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Pet updated.", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } }, - ["405"] = new OpenApiResponse + ["405"] = new() { Description = "Invalid input", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } } @@ -331,19 +331,19 @@ public void ParseOperationWithResponseExamplesShouldSucceed() operation.Should().BeEquivalentTo( new OpenApiOperation { - Responses = new OpenApiResponses + Responses = new() { - { "200", new OpenApiResponse + { "200", new() { Description = "An array of float response", Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "number", Format = "float" @@ -356,12 +356,12 @@ public void ParseOperationWithResponseExamplesShouldSucceed() new OpenApiFloat(7), } }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "number", Format = "float" @@ -390,16 +390,16 @@ public void ParseOperationWithEmptyProducesArraySetsResponseSchemaIfExists() operation.Should().BeEquivalentTo( new OpenApiOperation { - Responses = new OpenApiResponses + Responses = new() { - { "200", new OpenApiResponse + { "200", new() { Description = "OK", Content = { - ["application/octet-stream"] = new OpenApiMediaType + ["application/octet-stream"] = new() { - Schema = new OpenApiSchema + Schema = new() { Format = "binary", Description = "The content of the file.", diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs index 7239139c1..9eb20df4f 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiParameterTests.cs @@ -57,7 +57,7 @@ public void ParsePathParameterShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -85,10 +85,10 @@ public void ParseQueryParameterShouldSucceed() Name = "id", Description = "ID of the object to fetch", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } @@ -140,10 +140,10 @@ public void ParseHeaderParameterShouldSucceed() Required = true, Style = ParameterStyle.Simple, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "integer", Format = "int64", @@ -193,10 +193,10 @@ public void ParseHeaderParameterWithIncorrectDataTypeShouldSucceed() Required = true, Style = ParameterStyle.Simple, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string", Format = "date-time", @@ -244,7 +244,7 @@ public void ParseParameterWithNullLocationShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -272,7 +272,7 @@ public void ParseParameterWithNoLocationShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -324,7 +324,7 @@ public void ParseParameterWithUnknownLocationShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -352,7 +352,7 @@ public void ParseParameterWithDefaultShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float", @@ -382,7 +382,7 @@ public void ParseParameterWithEnumShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float", diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs index 57cf71302..177109131 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs @@ -17,20 +17,20 @@ public class OpenApiPathItemTests { private const string SampleFolderPath = "V2Tests/Samples/OpenApiPathItem/"; - private static readonly OpenApiPathItem _basicPathItemWithFormData = new OpenApiPathItem + private static readonly OpenApiPathItem _basicPathItemWithFormData = new() { Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to use", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } @@ -40,41 +40,41 @@ public class OpenApiPathItemTests }, Operations = { - [OperationType.Put] = new OpenApiOperation + [OperationType.Put] = new() { Summary = "Puts a pet in the store with form data", Description = "", OperationId = "putPetWithForm", Parameters = new List { - new OpenApiParameter + new() { Name = "petId", In = ParameterLocation.Path, Description = "ID of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } }, - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/x-www-form-urlencoded"] = new OpenApiMediaType + ["application/x-www-form-urlencoded"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" @@ -86,18 +86,18 @@ public class OpenApiPathItemTests } } }, - ["multipart/form-data"] = new OpenApiMediaType + ["multipart/form-data"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" @@ -111,79 +111,79 @@ public class OpenApiPathItemTests } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Pet updated.", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } }, - ["405"] = new OpenApiResponse + ["405"] = new() { Description = "Invalid input", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } } } }, - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { Summary = "Posts a pet in the store with form data", Description = "", OperationId = "postPetWithForm", Parameters = new List { - new OpenApiParameter + new() { Name = "petId", In = ParameterLocation.Path, Description = "ID of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } }, - new OpenApiParameter + new() { Name = "petName", In = ParameterLocation.Path, Description = "Name of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } }, - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/x-www-form-urlencoded"] = new OpenApiMediaType + ["application/x-www-form-urlencoded"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" }, - ["skill"] = new OpenApiSchema + ["skill"] = new() { Description = "Updated skill of the pet", Type = "string" @@ -195,23 +195,23 @@ public class OpenApiPathItemTests } } }, - ["multipart/form-data"] = new OpenApiMediaType + ["multipart/form-data"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" }, - ["skill"] = new OpenApiSchema + ["skill"] = new() { Description = "Updated skill of the pet", Type = "string" @@ -225,15 +225,15 @@ public class OpenApiPathItemTests } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Pet updated.", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType(), - ["application/xml"] = new OpenApiMediaType() + ["application/json"] = new(), + ["application/xml"] = new() } } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs index 6fa65252d..80539af75 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiSecuritySchemeTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.IO; using System.Linq; using FluentAssertions; @@ -82,11 +81,11 @@ public void ParseOAuth2ImplicitSecuritySchemeShouldSucceed() new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + AuthorizationUrl = new("http://swagger.io/api/oauth/dialog"), Scopes = { ["write:pets"] = "modify pets in your account", @@ -115,11 +114,11 @@ public void ParseOAuth2PasswordSecuritySchemeShouldSucceed() new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - Password = new OpenApiOAuthFlow + Password = new() { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + AuthorizationUrl = new("http://swagger.io/api/oauth/dialog"), Scopes = { ["write:pets"] = "modify pets in your account", @@ -148,11 +147,11 @@ public void ParseOAuth2ApplicationSecuritySchemeShouldSucceed() new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - ClientCredentials = new OpenApiOAuthFlow + ClientCredentials = new() { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + AuthorizationUrl = new("http://swagger.io/api/oauth/dialog"), Scopes = { ["write:pets"] = "modify pets in your account", @@ -182,11 +181,11 @@ public void ParseOAuth2AccessCodeSecuritySchemeShouldSucceed() new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - AuthorizationCode = new OpenApiOAuthFlow + AuthorizationCode = new() { - AuthorizationUrl = new Uri("http://swagger.io/api/oauth/dialog"), + AuthorizationUrl = new("http://swagger.io/api/oauth/dialog"), Scopes = { ["write:pets"] = "modify pets in your account", diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs index 64c7c00fb..f254800b9 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiServerTests.cs @@ -1,6 +1,5 @@ using FluentAssertions; using Microsoft.OpenApi.Models; -using System; using System.Linq; using Xunit; @@ -19,7 +18,7 @@ public void NoServer() version: 1.0.0 paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { }); @@ -41,7 +40,7 @@ public void JustSchemeNoDefault() - http paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { }); @@ -62,7 +61,7 @@ public void JustHostNoDefault() host: www.foo.com paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { }); @@ -87,9 +86,9 @@ public void NoBasePath() - http paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://www.foo.com/spec.yaml") + BaseUrl = new("https://www.foo.com/spec.yaml") }); var doc = reader.Read(input, out var diagnostic); @@ -111,7 +110,7 @@ public void JustBasePathNoDefault() basePath: /baz paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { }); @@ -135,9 +134,9 @@ public void JustSchemeWithCustomHost() - http paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://bing.com/foo") + BaseUrl = new("https://bing.com/foo") }); var doc = reader.Read(input, out var diagnostic); @@ -160,9 +159,9 @@ public void JustSchemeWithCustomHostWithEmptyPath() - http paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://bing.com") + BaseUrl = new("https://bing.com") }); var doc = reader.Read(input, out var diagnostic); @@ -184,9 +183,9 @@ public void JustBasePathWithCustomHost() basePath: /api paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://bing.com") + BaseUrl = new("https://bing.com") }); var doc = reader.Read(input, out var diagnostic); @@ -208,9 +207,9 @@ public void JustHostWithCustomHost() host: www.example.com paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://bing.com") + BaseUrl = new("https://bing.com") }); var doc = reader.Read(input, out var diagnostic); @@ -232,9 +231,9 @@ public void JustHostWithCustomHostWithApi() host: prod.bing.com paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://dev.bing.com/api/description.yaml") + BaseUrl = new("https://dev.bing.com/api/description.yaml") }); var doc = reader.Read(input, out var _); @@ -258,9 +257,9 @@ public void MultipleServers() - https paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://dev.bing.com/api") + BaseUrl = new("https://dev.bing.com/api") }); var doc = reader.Read(input, out var diagnostic); @@ -283,9 +282,9 @@ public void LocalHostWithCustomHost() host: localhost:23232 paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://bing.com") + BaseUrl = new("https://bing.com") }); var doc = reader.Read(input, out var diagnostic); @@ -307,9 +306,9 @@ public void InvalidHostShouldYieldError() host: http://test.microsoft.com paths: {} """; - var reader = new OpenApiStringReader(new OpenApiReaderSettings + var reader = new OpenApiStringReader(new() { - BaseUrl = new Uri("https://bing.com") + BaseUrl = new("https://bing.com") }); var doc = reader.Read(input, out var diagnostic); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs index 38d9cf1d1..3bddf695c 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiCallbackTests.cs @@ -44,23 +44,23 @@ public void ParseBasicCallbackShouldSucceed() PathItems = { [RuntimeExpression.Build("$request.body#/url")] - = new OpenApiPathItem + = new() { Operations = { [OperationType.Post] = - new OpenApiOperation + new() { - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { ["application/json"] = null } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Success" } @@ -93,17 +93,18 @@ public void ParseCallbackWithReferenceShouldSucceed() { PathItems = { - [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { + [RuntimeExpression.Build("$request.body#/url")]= new() + { Operations = { - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "object" } @@ -111,7 +112,7 @@ public void ParseCallbackWithReferenceShouldSucceed() } }, Responses = { - ["200"]= new OpenApiResponse + ["200"]= new() { Description = "Success" } @@ -120,7 +121,7 @@ public void ParseCallbackWithReferenceShouldSucceed() } } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Callback, Id = "simpleHook", @@ -150,17 +151,18 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { PathItems = { - [RuntimeExpression.Build("$request.body#/url")]= new OpenApiPathItem { + [RuntimeExpression.Build("$request.body#/url")]= new() + { Operations = { - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "object" } @@ -168,7 +170,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } }, Responses = { - ["200"]= new OpenApiResponse + ["200"]= new() { Description = "Success" } @@ -177,7 +179,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Callback, Id = "simpleHook", @@ -191,18 +193,19 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { PathItems = { - [RuntimeExpression.Build("/simplePath")]= new OpenApiPathItem { + [RuntimeExpression.Build("/simplePath")]= new() + { Operations = { - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "Callback 2", Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -210,7 +213,7 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } }, Responses = { - ["400"]= new OpenApiResponse + ["400"]= new() { Description = "Callback Response" } @@ -227,17 +230,18 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() { PathItems = { - [RuntimeExpression.Build(@"http://example.com?transactionId={$request.body#/id}&email={$request.body#/email}")] = new OpenApiPathItem { + [RuntimeExpression.Build(@"http://example.com?transactionId={$request.body#/id}&email={$request.body#/email}")] = new() + { Operations = { - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "object" } @@ -245,15 +249,15 @@ public void ParseMultipleCallbacksWithReferenceShouldSucceed() } }, Responses = { - ["200"]= new OpenApiResponse + ["200"]= new() { Description = "Success" }, - ["401"]= new OpenApiResponse + ["401"]= new() { Description = "Unauthorized" }, - ["404"]= new OpenApiResponse + ["404"]= new() { Description = "Not Found" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs index c4f08f389..3f6b4a320 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiContactTests.cs @@ -3,7 +3,6 @@ using FluentAssertions; using Microsoft.OpenApi.Models; -using System; using Xunit; namespace Microsoft.OpenApi.Readers.Tests.V3Tests @@ -34,7 +33,7 @@ public void ParseStringContactFragmentShouldSucceed() { Email = "support@swagger.io", Name = "API Support", - Url = new Uri("http://www.swagger.io/support") + Url = new("http://www.swagger.io/support") }); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs index f50f7e01f..4505ce33a 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiDocumentTests.cs @@ -15,7 +15,6 @@ using Microsoft.OpenApi.Validations.Rules; using Microsoft.OpenApi.Writers; using Xunit; -using Xunit.Abstractions; namespace Microsoft.OpenApi.Readers.Tests.V3Tests { @@ -29,7 +28,7 @@ public T Clone(T element) where T : IOpenApiSerializable using var stream = new MemoryStream(); IOpenApiWriter writer; var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings + writer = new OpenApiJsonWriter(streamWriter, new() { InlineLocalReferences = true }); @@ -47,7 +46,7 @@ public OpenApiSecurityScheme CloneSecurityScheme(OpenApiSecurityScheme element) using var stream = new MemoryStream(); IOpenApiWriter writer; var streamWriter = new FormattingStreamWriter(stream, CultureInfo.InvariantCulture); - writer = new OpenApiJsonWriter(streamWriter, new OpenApiJsonWriterSettings + writer = new OpenApiJsonWriter(streamWriter, new() { InlineLocalReferences = true }); @@ -77,12 +76,12 @@ public void ParseDocumentFromInlineStringShouldSucceed() openApiDoc.Should().BeEquivalentTo( new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Simple Document", Version = "0.9.1" }, - Paths = new OpenApiPaths() + Paths = new() }); context.Should().BeEquivalentTo( @@ -97,8 +96,8 @@ public void ParseDocumentFromInlineStringShouldSucceed() [InlineData("da-DK")] public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) { - Thread.CurrentThread.CurrentCulture = new CultureInfo(culture); - Thread.CurrentThread.CurrentUICulture = new CultureInfo(culture); + Thread.CurrentThread.CurrentCulture = new(culture); + Thread.CurrentThread.CurrentUICulture = new(culture); var openApiDoc = new OpenApiStringReader().Read( """ @@ -124,21 +123,21 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) openApiDoc.Should().BeEquivalentTo( new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Simple Document", Version = "0.9.1" }, - Components = new OpenApiComponents + Components = new() { Schemas = { - ["sampleSchema"] = new OpenApiSchema + ["sampleSchema"] = new() { Type = "object", Properties = { - ["sampleProperty"] = new OpenApiSchema + ["sampleProperty"] = new() { Type = "double", Minimum = (decimal)100.54, @@ -147,7 +146,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) ExclusiveMinimum = false } }, - Reference = new OpenApiReference + Reference = new() { Id = "sampleSchema", Type = ReferenceType.Schema @@ -155,7 +154,7 @@ public void ParseDocumentWithDifferentCultureShouldSucceed(string culture) } } }, - Paths = new OpenApiPaths() + Paths = new() }); context.Should().BeEquivalentTo( @@ -174,7 +173,7 @@ public void ParseBasicDocumentWithMultipleServersShouldSucceed() openApiDoc.Should().BeEquivalentTo( new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "The API", Version = "0.9.1", @@ -192,7 +191,7 @@ public void ParseBasicDocumentWithMultipleServersShouldSucceed() Description = "The https endpoint" } }, - Paths = new OpenApiPaths() + Paths = new() }); } @@ -205,11 +204,11 @@ public void ParseBrokenMinimalDocumentShouldYieldExpectedDiagnostic() openApiDoc.Should().BeEquivalentTo( new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Version = "0.9" }, - Paths = new OpenApiPaths() + Paths = new() }); diagnostic.Should().BeEquivalentTo( @@ -232,12 +231,12 @@ public void ParseMinimalDocumentShouldSucceed() openApiDoc.Should().BeEquivalentTo( new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Simple Document", Version = "0.9.1" }, - Paths = new OpenApiPaths() + Paths = new() }); diagnostic.Should().BeEquivalentTo( @@ -256,7 +255,7 @@ public void ParseStandardPetStoreDocumentShouldSucceed() { Schemas = new Dictionary { - ["pet"] = new OpenApiSchema + ["pet"] = new() { Type = "object", Required = new HashSet @@ -266,28 +265,28 @@ public void ParseStandardPetStoreDocumentShouldSucceed() }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "pet", HostDocument = actual } }, - ["newPet"] = new OpenApiSchema + ["newPet"] = new() { Type = "object", Required = new HashSet @@ -296,28 +295,28 @@ public void ParseStandardPetStoreDocumentShouldSucceed() }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "newPet", HostDocument = actual } }, - ["errorModel"] = new OpenApiSchema + ["errorModel"] = new() { Type = "object", Required = new HashSet @@ -327,17 +326,17 @@ public void ParseStandardPetStoreDocumentShouldSucceed() }, Properties = new Dictionary { - ["code"] = new OpenApiSchema + ["code"] = new() { Type = "integer", Format = "int32" }, - ["message"] = new OpenApiSchema + ["message"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "errorModel", @@ -350,7 +349,7 @@ public void ParseStandardPetStoreDocumentShouldSucceed() // Create a clone of the schema to avoid modifying things in components. var petSchema = Clone(components.Schemas["pet"]); - petSchema.Reference = new OpenApiReference + petSchema.Reference = new() { Id = "pet", Type = ReferenceType.Schema, @@ -359,7 +358,7 @@ public void ParseStandardPetStoreDocumentShouldSucceed() var newPetSchema = Clone(components.Schemas["newPet"]); - newPetSchema.Reference = new OpenApiReference + newPetSchema.Reference = new() { Id = "newPet", Type = ReferenceType.Schema, @@ -368,7 +367,7 @@ public void ParseStandardPetStoreDocumentShouldSucceed() var errorModelSchema = Clone(components.Schemas["errorModel"]); - errorModelSchema.Reference = new OpenApiReference + errorModelSchema.Reference = new() { Id = "errorModel", Type = ReferenceType.Schema, @@ -377,90 +376,90 @@ public void ParseStandardPetStoreDocumentShouldSucceed() var expected = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0", Title = "Swagger Petstore (Simple)", Description = "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - TermsOfService = new Uri("http://helloreverb.com/terms/"), - Contact = new OpenApiContact + TermsOfService = new("http://helloreverb.com/terms/"), + Contact = new() { Name = "Swagger API team", Email = "foo@example.com", - Url = new Uri("http://swagger.io") + Url = new("http://swagger.io") }, - License = new OpenApiLicense + License = new() { Name = "MIT", - Url = new Uri("http://opensource.org/licenses/MIT") + Url = new("http://opensource.org/licenses/MIT") } }, Servers = new List { - new OpenApiServer + new() { Url = "http://petstore.swagger.io/api" } }, - Paths = new OpenApiPaths + Paths = new() { - ["/pets"] = new OpenApiPathItem + ["/pets"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns all pets from the system that the user has access to", OperationId = "findPets", Parameters = new List { - new OpenApiParameter + new() { Name = "tags", In = ParameterLocation.Query, Description = "tags to filter by", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } } }, - new OpenApiParameter + new() { Name = "limit", In = ParameterLocation.Query, Description = "maximum number of results to return", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = petSchema } }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = petSchema @@ -468,23 +467,23 @@ public void ParseStandardPetStoreDocumentShouldSucceed() } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -492,52 +491,52 @@ public void ParseStandardPetStoreDocumentShouldSucceed() } } }, - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { Description = "Creates a new pet in the store. Duplicates are allowed", OperationId = "addPet", - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "Pet to add to the store", Required = true, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = newPetSchema } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = petSchema }, } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -547,64 +546,64 @@ public void ParseStandardPetStoreDocumentShouldSucceed() } } }, - ["/pets/{id}"] = new OpenApiPathItem + ["/pets/{id}"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns a user based on a single ID, if the user does not have access to the pet", OperationId = "findPetById", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = petSchema }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { Schema = petSchema } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -612,48 +611,48 @@ public void ParseStandardPetStoreDocumentShouldSucceed() } } }, - [OperationType.Delete] = new OpenApiOperation + [OperationType.Delete] = new() { Description = "deletes a single pet based on the ID supplied", OperationId = "deletePet", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to delete", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["204"] = new OpenApiResponse + ["204"] = new() { Description = "pet deleted" }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -686,7 +685,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() { Schemas = new Dictionary { - ["pet"] = new OpenApiSchema + ["pet"] = new() { Type = "object", Required = new HashSet @@ -696,28 +695,28 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "pet", HostDocument = actual } }, - ["newPet"] = new OpenApiSchema + ["newPet"] = new() { Type = "object", Required = new HashSet @@ -726,28 +725,28 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "newPet", HostDocument = actual } }, - ["errorModel"] = new OpenApiSchema + ["errorModel"] = new() { Type = "object", Required = new HashSet @@ -757,17 +756,17 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() }, Properties = new Dictionary { - ["code"] = new OpenApiSchema + ["code"] = new() { Type = "integer", Format = "int32" }, - ["message"] = new OpenApiSchema + ["message"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "errorModel" @@ -776,12 +775,12 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() }, SecuritySchemes = new Dictionary { - ["securitySchemeName1"] = new OpenApiSecurityScheme + ["securitySchemeName1"] = new() { Type = SecuritySchemeType.ApiKey, Name = "apiKeyName1", In = ParameterLocation.Header, - Reference = new OpenApiReference + Reference = new() { Id = "securitySchemeName1", Type = ReferenceType.SecurityScheme, @@ -789,11 +788,11 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } }, - ["securitySchemeName2"] = new OpenApiSecurityScheme + ["securitySchemeName2"] = new() { Type = SecuritySchemeType.OpenIdConnect, - OpenIdConnectUrl = new Uri("http://example.com"), - Reference = new OpenApiReference + OpenIdConnectUrl = new("http://example.com"), + Reference = new() { Id = "securitySchemeName2", Type = ReferenceType.SecurityScheme, @@ -805,7 +804,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() // Create a clone of the schema to avoid modifying things in components. var petSchema = Clone(components.Schemas["pet"]); - petSchema.Reference = new OpenApiReference + petSchema.Reference = new() { Id = "pet", Type = ReferenceType.Schema @@ -813,7 +812,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() var newPetSchema = Clone(components.Schemas["newPet"]); - newPetSchema.Reference = new OpenApiReference + newPetSchema.Reference = new() { Id = "newPet", Type = ReferenceType.Schema @@ -821,7 +820,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() var errorModelSchema = Clone(components.Schemas["errorModel"]); - errorModelSchema.Reference = new OpenApiReference + errorModelSchema.Reference = new() { Id = "errorModel", Type = ReferenceType.Schema @@ -831,7 +830,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() { Name = "tagName1", Description = "tagDescription1", - Reference = new OpenApiReference + Reference = new() { Id = "tagName1", Type = ReferenceType.Tag @@ -845,7 +844,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() var securityScheme1 = CloneSecurityScheme(components.SecuritySchemes["securitySchemeName1"]); - securityScheme1.Reference = new OpenApiReference + securityScheme1.Reference = new() { Id = "securitySchemeName1", Type = ReferenceType.SecurityScheme @@ -853,7 +852,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() var securityScheme2 = CloneSecurityScheme(components.SecuritySchemes["securitySchemeName2"]); - securityScheme2.Reference = new OpenApiReference + securityScheme2.Reference = new() { Id = "securitySchemeName2", Type = ReferenceType.SecurityScheme @@ -861,39 +860,39 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() var expected = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0", Title = "Swagger Petstore (Simple)", Description = "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - TermsOfService = new Uri("http://helloreverb.com/terms/"), - Contact = new OpenApiContact + TermsOfService = new("http://helloreverb.com/terms/"), + Contact = new() { Name = "Swagger API team", Email = "foo@example.com", - Url = new Uri("http://swagger.io") + Url = new("http://swagger.io") }, - License = new OpenApiLicense + License = new() { Name = "MIT", - Url = new Uri("http://opensource.org/licenses/MIT") + Url = new("http://opensource.org/licenses/MIT") } }, Servers = new List { - new OpenApiServer + new() { Url = "http://petstore.swagger.io/api" } }, - Paths = new OpenApiPaths + Paths = new() { - ["/pets"] = new OpenApiPathItem + ["/pets"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Tags = new List { @@ -904,52 +903,52 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() OperationId = "findPets", Parameters = new List { - new OpenApiParameter + new() { Name = "tags", In = ParameterLocation.Query, Description = "tags to filter by", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } } }, - new OpenApiParameter + new() { Name = "limit", In = ParameterLocation.Query, Description = "maximum number of results to return", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = petSchema } }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = petSchema @@ -957,23 +956,23 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -981,7 +980,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } } }, - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { Tags = new List { @@ -990,48 +989,48 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() }, Description = "Creates a new pet in the store. Duplicates are allowed", OperationId = "addPet", - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "Pet to add to the store", Required = true, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = newPetSchema } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = petSchema }, } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -1040,7 +1039,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() }, Security = new List { - new OpenApiSecurityRequirement + new() { [securityScheme1] = new List(), [securityScheme2] = new List @@ -1053,64 +1052,64 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } } }, - ["/pets/{id}"] = new OpenApiPathItem + ["/pets/{id}"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns a user based on a single ID, if the user does not have access to the pet", OperationId = "findPetById", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = petSchema }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { Schema = petSchema } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -1118,48 +1117,48 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() } } }, - [OperationType.Delete] = new OpenApiOperation + [OperationType.Delete] = new() { Description = "deletes a single pet based on the ID supplied", OperationId = "deletePet", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to delete", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["204"] = new OpenApiResponse + ["204"] = new() { Description = "pet deleted" }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = errorModelSchema } @@ -1173,11 +1172,11 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() Components = components, Tags = new List { - new OpenApiTag + new() { Name = "tagName1", Description = "tagDescription1", - Reference = new OpenApiReference + Reference = new() { Id = "tagName1", Type = ReferenceType.Tag @@ -1186,7 +1185,7 @@ public void ParseModifiedPetStoreDocumentWithTagAndSecurityShouldSucceed() }, SecurityRequirements = new List { - new OpenApiSecurityRequirement + new() { [securityScheme1] = new List(), [securityScheme2] = new List @@ -1252,12 +1251,12 @@ public void HeaderParameterShouldAllowExample() Style = ParameterStyle.Simple, Explode = true, Example = new OpenApiString("99391c7e-ad88-49ec-a2ad-99ddcb1f7721"), - Schema = new OpenApiSchema + Schema = new() { Type = "string", Format = "uuid" }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Header, Id = "example-header" @@ -1289,12 +1288,12 @@ public void HeaderParameterShouldAllowExample() } } }, - Schema = new OpenApiSchema + Schema = new() { Type = "string", Format = "uuid" }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Header, Id = "examples-header" @@ -1310,7 +1309,7 @@ public void DoesNotChangeExternalReferences() // Act var doc = new OpenApiStreamReader( - new OpenApiReaderSettings { ReferenceResolution = ReferenceResolutionSetting.DoNotResolveReferences }) + new() { ReferenceResolution = ReferenceResolutionSetting.DoNotResolveReferences }) .Read(stream, out var diagnostic); var externalRef = doc.Components.Schemas["Nested"].Properties["AnyOf"].AnyOf.First().Reference.ReferenceV3; @@ -1328,7 +1327,7 @@ public void ParseDocumentWithReferencedSecuritySchemeWorks() using var stream = Resources.GetStream(Path.Combine(SampleFolderPath, "docWithSecuritySchemeReference.yaml")); // Act - var doc = new OpenApiStreamReader(new OpenApiReaderSettings + var doc = new OpenApiStreamReader(new() { ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences }).Read(stream, out var diagnostic); diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs index d3cea2d6b..2b9c23fe1 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiEncodingTests.cs @@ -65,10 +65,10 @@ public void ParseAdvancedEncodingShouldSucceed() Headers = { ["X-Rate-Limit-Limit"] = - new OpenApiHeader + new() { Description = "The number of allowed requests in the current period", - Schema = new OpenApiSchema + Schema = new() { Type = "integer" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs index 34d821a72..c21789ccf 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiInfoTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.IO; using System.Linq; using FluentAssertions; @@ -42,8 +41,8 @@ public void ParseAdvancedInfoShouldSucceed() Title = "Advanced Info", Description = "Sample Description", Version = "1.0.0", - TermsOfService = new Uri("http://example.org/termsOfService"), - Contact = new OpenApiContact + TermsOfService = new("http://example.org/termsOfService"), + Contact = new() { Email = "example@example.com", Extensions = @@ -51,13 +50,13 @@ public void ParseAdvancedInfoShouldSucceed() ["x-twitter"] = new OpenApiString("@exampleTwitterHandler") }, Name = "John Doe", - Url = new Uri("http://www.example.com/url1") + Url = new("http://www.example.com/url1") }, - License = new OpenApiLicense + License = new() { Extensions = { ["x-disclaimer"] = new OpenApiString("Sample Extension String Disclaimer") }, Name = "licenseName", - Url = new Uri("http://www.example.com/url2") + Url = new("http://www.example.com/url2") }, Extensions = { @@ -100,17 +99,17 @@ public void ParseBasicInfoShouldSucceed() Title = "Basic Info", Description = "Sample Description", Version = "1.0.1", - TermsOfService = new Uri("http://swagger.io/terms/"), - Contact = new OpenApiContact + TermsOfService = new("http://swagger.io/terms/"), + Contact = new() { Email = "support@swagger.io", Name = "API Support", - Url = new Uri("http://www.swagger.io/support") + Url = new("http://www.swagger.io/support") }, - License = new OpenApiLicense + License = new() { Name = "Apache 2.0", - Url = new Uri("http://www.apache.org/licenses/LICENSE-2.0.html") + Url = new("http://www.apache.org/licenses/LICENSE-2.0.html") } }); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs index f9835bfbb..8e3a6c864 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiMediaTypeTests.cs @@ -34,7 +34,7 @@ public void ParseMediaTypeWithExampleShouldSucceed() new OpenApiMediaType { Example = new OpenApiFloat(5), - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float" @@ -61,16 +61,16 @@ public void ParseMediaTypeWithExamplesShouldSucceed() { Examples = { - ["example1"] = new OpenApiExample + ["example1"] = new() { Value = new OpenApiFloat(5), }, - ["example2"] = new OpenApiExample + ["example2"] = new() { Value = new OpenApiFloat((float)7.5), } }, - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float" diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs index db2f3907c..ced80c348 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiOperationTests.cs @@ -47,7 +47,7 @@ public void ParseOperationWithParameterWithNoLocationShouldSucceed() new OpenApiTag { UnresolvedReference = true, - Reference = new OpenApiReference + Reference = new() { Id = "user", Type = ReferenceType.Tag @@ -64,7 +64,7 @@ public void ParseOperationWithParameterWithNoLocationShouldSucceed() Name = "username", Description = "The user name for login", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -75,7 +75,7 @@ public void ParseOperationWithParameterWithNoLocationShouldSucceed() Description = "The password for login in clear text", In = ParameterLocation.Query, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs index 13188dba1..1439cea2e 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiParameterTests.cs @@ -37,7 +37,7 @@ public void ParsePathParameterShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -65,10 +65,10 @@ public void ParseQueryParameterShouldSucceed() Name = "id", Description = "ID of the object to fetch", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } @@ -97,10 +97,10 @@ public void ParseQueryParameterWithObjectTypeShouldSucceed() { In = ParameterLocation.Query, Name = "freeForm", - Schema = new OpenApiSchema + Schema = new() { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "integer" } @@ -130,9 +130,9 @@ public void ParseQueryParameterWithObjectTypeAndContentShouldSucceed() Name = "coordinates", Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "object", Required = @@ -142,11 +142,11 @@ public void ParseQueryParameterWithObjectTypeAndContentShouldSucceed() }, Properties = { - ["lat"] = new OpenApiSchema + ["lat"] = new() { Type = "number" }, - ["long"] = new OpenApiSchema + ["long"] = new() { Type = "number" } @@ -180,10 +180,10 @@ public void ParseHeaderParameterShouldSucceed() Required = true, Style = ParameterStyle.Simple, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "integer", Format = "int64", @@ -213,7 +213,7 @@ public void ParseParameterWithNullLocationShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -241,7 +241,7 @@ public void ParseParameterWithNoLocationShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -269,7 +269,7 @@ public void ParseParameterWithUnknownLocationShouldSucceed() Name = "username", Description = "username to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -298,7 +298,7 @@ public void ParseParameterWithExampleShouldSucceed() Description = "username to fetch", Required = true, Example = new OpenApiFloat(5), - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float" @@ -329,16 +329,16 @@ public void ParseParameterWithExamplesShouldSucceed() Required = true, Examples = { - ["example1"] = new OpenApiExample + ["example1"] = new() { Value = new OpenApiFloat(5), }, - ["example2"] = new OpenApiExample + ["example2"] = new() { Value = new OpenApiFloat((float)7.5), } }, - Schema = new OpenApiSchema + Schema = new() { Type = "number", Format = "float" diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs index e84b8cbc5..109997bb6 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSchemaTests.cs @@ -179,15 +179,15 @@ public void ParseSimpleSchemaShouldSucceed() }, Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["address"] = new OpenApiSchema + ["address"] = new() { Type = "string" }, - ["age"] = new OpenApiSchema + ["age"] = new() { Type = "integer", Format = "int32", @@ -223,11 +223,11 @@ public void ParsePathFragmentShouldSucceed() Summary = "externally referenced path item", Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Ok" } @@ -260,7 +260,7 @@ public void ParseDictionarySchemaShouldSucceed() new OpenApiSchema { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "string" } @@ -292,12 +292,12 @@ public void ParseBasicSchemaWithExampleShouldSucceed() Type = "object", Properties = { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" } @@ -332,23 +332,23 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() { Schemas = { - ["ErrorModel"] = new OpenApiSchema + ["ErrorModel"] = new() { Type = "object", Properties = { - ["code"] = new OpenApiSchema + ["code"] = new() { Type = "integer", Minimum = 100, Maximum = 600 }, - ["message"] = new OpenApiSchema + ["message"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "ErrorModel", @@ -360,9 +360,9 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() "code" } }, - ["ExtendedErrorModel"] = new OpenApiSchema + ["ExtendedErrorModel"] = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "ExtendedErrorModel", @@ -372,7 +372,7 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() { new OpenApiSchema { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "ErrorModel", @@ -383,13 +383,13 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() Type = "object", Properties = { - ["code"] = new OpenApiSchema + ["code"] = new() { Type = "integer", Minimum = 100, Maximum = 600 }, - ["message"] = new OpenApiSchema + ["message"] = new() { Type = "string" } @@ -406,7 +406,7 @@ public void ParseBasicSchemaWithReferenceShouldSucceed() Required = {"rootCause"}, Properties = { - ["rootCause"] = new OpenApiSchema + ["rootCause"] = new() { Type = "string" } @@ -436,20 +436,20 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() { Schemas = { - ["Pet"] = new OpenApiSchema + ["Pet"] = new() { Type = "object", - Discriminator = new OpenApiDiscriminator + Discriminator = new() { PropertyName = "petType" }, Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["petType"] = new OpenApiSchema + ["petType"] = new() { Type = "string" } @@ -459,21 +459,21 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() "name", "petType" }, - Reference = new OpenApiReference + Reference = new() { Id= "Pet", Type = ReferenceType.Schema, HostDocument = openApiDoc } }, - ["Cat"] = new OpenApiSchema + ["Cat"] = new() { Description = "A representation of a cat", AllOf = { new OpenApiSchema { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "Pet", @@ -482,17 +482,17 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() // Schema should be dereferenced in our model, so all the properties // from the Pet above should be propagated here. Type = "object", - Discriminator = new OpenApiDiscriminator + Discriminator = new() { PropertyName = "petType" }, Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["petType"] = new OpenApiSchema + ["petType"] = new() { Type = "string" } @@ -509,7 +509,7 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() Required = {"huntingSkill"}, Properties = { - ["huntingSkill"] = new OpenApiSchema + ["huntingSkill"] = new() { Type = "string", Description = "The measured skill for hunting", @@ -524,21 +524,21 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() } } }, - Reference = new OpenApiReference + Reference = new() { Id= "Cat", Type = ReferenceType.Schema, HostDocument = openApiDoc } }, - ["Dog"] = new OpenApiSchema + ["Dog"] = new() { Description = "A representation of a dog", AllOf = { new OpenApiSchema { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "Pet", @@ -547,17 +547,17 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() // Schema should be dereferenced in our model, so all the properties // from the Pet above should be propagated here. Type = "object", - Discriminator = new OpenApiDiscriminator + Discriminator = new() { PropertyName = "petType" }, Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["petType"] = new OpenApiSchema + ["petType"] = new() { Type = "string" } @@ -574,7 +574,7 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() Required = {"packSize"}, Properties = { - ["packSize"] = new OpenApiSchema + ["packSize"] = new() { Type = "integer", Format = "int32", @@ -585,7 +585,7 @@ public void ParseAdvancedSchemaWithReferenceShouldSucceed() } } }, - Reference = new OpenApiReference + Reference = new() { Id= "Dog", Type = ReferenceType.Schema, @@ -616,22 +616,22 @@ public void ParseSelfReferencingSchemaShouldNotStackOverflow() Title = "schemaExtension", Type = "object", Properties = { - ["description"] = new OpenApiSchema { Type = "string", Nullable = true}, - ["targetTypes"] = new OpenApiSchema + ["description"] = new() { Type = "string", Nullable = true}, + ["targetTypes"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } }, - ["status"] = new OpenApiSchema { Type = "string"}, - ["owner"] = new OpenApiSchema { Type = "string"}, + ["status"] = new() { Type = "string"}, + ["owner"] = new() { Type = "string"}, ["child"] = null } } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "microsoft.graph.schemaExtension" diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs index fdeb9734d..0e462c2eb 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiSecuritySchemeTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.IO; using System.Linq; using FluentAssertions; @@ -116,11 +115,11 @@ public void ParseOAuth2SecuritySchemeShouldSucceed() new OpenApiSecurityScheme { Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { - AuthorizationUrl = new Uri("https://example.com/api/oauth/dialog"), + AuthorizationUrl = new("https://example.com/api/oauth/dialog"), Scopes = { ["write:pets"] = "modify pets in your account", @@ -153,7 +152,7 @@ public void ParseOpenIdConnectSecuritySchemeShouldSucceed() { Type = SecuritySchemeType.OpenIdConnect, Description = "Sample Description", - OpenIdConnectUrl = new Uri("http://www.example.com") + OpenIdConnectUrl = new("http://www.example.com") }); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs index ebba38c35..4f7de222b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V3Tests/OpenApiXmlTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.IO; using System.Linq; using FluentAssertions; @@ -39,7 +38,7 @@ public void ParseBasicXmlShouldSucceed() new OpenApiXml { Name = "name1", - Namespace = new Uri("http://example.com/schema/namespaceSample"), + Namespace = new("http://example.com/schema/namespaceSample"), Prefix = "samplePrefix", Wrapped = true }); diff --git a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs index 079ab6569..efc79b133 100644 --- a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs +++ b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs @@ -28,12 +28,12 @@ public ApisGuruTests(ITestOutputHelper output) static ApisGuruTests() { System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - _httpClient = new HttpClient(new HttpClientHandler + _httpClient = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); - _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip")); - _httpClient.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("OpenApi.Net.Tests", "1.0")); + _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new("gzip")); + _httpClient.DefaultRequestHeaders.UserAgent.Add(new("OpenApi.Net.Tests", "1.0")); } public static IEnumerable GetSchemas() diff --git a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs index 9bfebed25..77b4d2525 100644 --- a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs +++ b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs @@ -20,11 +20,11 @@ public GraphTests(ITestOutputHelper output) { _output = output; System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; - _httpClient = new HttpClient(new HttpClientHandler + _httpClient = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); - _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip")); - _httpClient.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("OpenApi.Net.Tests", "1.0")); + _httpClient.DefaultRequestHeaders.AcceptEncoding.Add(new("gzip")); + _httpClient.DefaultRequestHeaders.UserAgent.Add(new("OpenApi.Net.Tests", "1.0")); var response = _httpClient.GetAsync(graphOpenApiUrl) .GetAwaiter().GetResult(); diff --git a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs index b48a574f3..5f4cd74fa 100644 --- a/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs +++ b/test/Microsoft.OpenApi.Tests/MicrosoftExtensions/OpenApiDeprecationExtensionTests.cs @@ -74,8 +74,8 @@ public void Parses() { var oaiValue = new OpenApiObject { - { "date", new OpenApiDateTime(new DateTimeOffset(2023,05,04, 16, 0, 0, 0, 0, new TimeSpan(4, 0, 0)))}, - { "removalDate", new OpenApiDateTime(new DateTimeOffset(2023,05,04, 16, 0, 0, 0, 0, new TimeSpan(4, 0, 0)))}, + { "date", new OpenApiDateTime(new(2023,05,04, 16, 0, 0, 0, 0, new(4, 0, 0)))}, + { "removalDate", new OpenApiDateTime(new(2023,05,04, 16, 0, 0, 0, 0, new(4, 0, 0)))}, { "version", new OpenApiString("v1.0")}, { "description", new OpenApiString("removing")} }; @@ -83,16 +83,16 @@ public void Parses() Assert.NotNull(value); Assert.Equal("v1.0", value.Version); Assert.Equal("removing", value.Description); - Assert.Equal(new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new TimeSpan(4, 0, 0)), value.Date); - Assert.Equal(new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new TimeSpan(4, 0, 0)), value.RemovalDate); + Assert.Equal(new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new(4, 0, 0)), value.Date); + Assert.Equal(new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new(4, 0, 0)), value.RemovalDate); } [Fact] public void Serializes() { var value = new OpenApiDeprecationExtension { - Date = new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new TimeSpan(4, 0, 0)), - RemovalDate = new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new TimeSpan(4, 0, 0)), + Date = new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new(4, 0, 0)), + RemovalDate = new DateTimeOffset(2023, 05, 04, 16, 0, 0, 0, 0, new(4, 0, 0)), Version = "v1.0", Description = "removing" }; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs index 05f6f3f00..6b6a8d734 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiCallbackTests.cs @@ -16,34 +16,34 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiCallbackTests { - public static OpenApiCallback AdvancedCallback = new OpenApiCallback + public static OpenApiCallback AdvancedCallback = new() { PathItems = { [RuntimeExpression.Build("$request.body#/url")] - = new OpenApiPathItem + = new() { Operations = { [OperationType.Post] = - new OpenApiOperation + new() { - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "object" } } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Success" } @@ -54,9 +54,9 @@ public class OpenApiCallbackTests } }; - public static OpenApiCallback ReferencedCallback = new OpenApiCallback + public static OpenApiCallback ReferencedCallback = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Callback, Id = "simpleHook", @@ -64,29 +64,29 @@ public class OpenApiCallbackTests PathItems = { [RuntimeExpression.Build("$request.body#/url")] - = new OpenApiPathItem + = new() { Operations = { [OperationType.Post] = - new OpenApiOperation + new() { - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "object" } } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Success" } @@ -104,7 +104,7 @@ public async Task SerializeAdvancedCallbackAsV3JsonWorks(bool produceTerseOutput { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedCallback.SerializeAsV3(writer); @@ -121,7 +121,7 @@ public async Task SerializeReferencedCallbackAsV3JsonWorks(bool produceTerseOutp { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedCallback.SerializeAsV3(writer); @@ -138,7 +138,7 @@ public async Task SerializeReferencedCallbackAsV3JsonWithoutReferenceWorks(bool { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedCallback.SerializeAsV3WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs index 371f95e25..b361d6c6c 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiComponentsTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Extensions; @@ -13,19 +12,19 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiComponentsTests { - public static OpenApiComponents AdvancedComponents = new OpenApiComponents + public static OpenApiComponents AdvancedComponents = new() { Schemas = new Dictionary { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { Properties = new Dictionary { - ["property2"] = new OpenApiSchema + ["property2"] = new() { Type = "integer" }, - ["property3"] = new OpenApiSchema + ["property3"] = new() { Type = "string", MaxLength = 15 @@ -35,65 +34,65 @@ public class OpenApiComponentsTests }, SecuritySchemes = new Dictionary { - ["securityScheme1"] = new OpenApiSecurityScheme + ["securityScheme1"] = new() { Description = "description1", Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { Scopes = new Dictionary { ["operation1:object1"] = "operation 1 on object 1", ["operation2:object2"] = "operation 2 on object 2" }, - AuthorizationUrl = new Uri("https://example.com/api/oauth") + AuthorizationUrl = new("https://example.com/api/oauth") } } }, - ["securityScheme2"] = new OpenApiSecurityScheme + ["securityScheme2"] = new() { Description = "description1", Type = SecuritySchemeType.OpenIdConnect, Scheme = OpenApiConstants.Bearer, - OpenIdConnectUrl = new Uri("https://example.com/openIdConnect") + OpenIdConnectUrl = new("https://example.com/openIdConnect") } } }; - public static OpenApiComponents AdvancedComponentsWithReference = new OpenApiComponents + public static OpenApiComponents AdvancedComponentsWithReference = new() { Schemas = new Dictionary { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { Properties = new Dictionary { - ["property2"] = new OpenApiSchema + ["property2"] = new() { Type = "integer" }, - ["property3"] = new OpenApiSchema + ["property3"] = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema2" } } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema1" } }, - ["schema2"] = new OpenApiSchema + ["schema2"] = new() { Properties = new Dictionary { - ["property2"] = new OpenApiSchema + ["property2"] = new() { Type = "integer" } @@ -102,35 +101,35 @@ public class OpenApiComponentsTests }, SecuritySchemes = new Dictionary { - ["securityScheme1"] = new OpenApiSecurityScheme + ["securityScheme1"] = new() { Description = "description1", Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { Scopes = new Dictionary { ["operation1:object1"] = "operation 1 on object 1", ["operation2:object2"] = "operation 2 on object 2" }, - AuthorizationUrl = new Uri("https://example.com/api/oauth") + AuthorizationUrl = new("https://example.com/api/oauth") } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "securityScheme1" } }, - ["securityScheme2"] = new OpenApiSecurityScheme + ["securityScheme2"] = new() { Description = "description1", Type = SecuritySchemeType.OpenIdConnect, Scheme = OpenApiConstants.Bearer, - OpenIdConnectUrl = new Uri("https://example.com/openIdConnect"), - Reference = new OpenApiReference + OpenIdConnectUrl = new("https://example.com/openIdConnect"), + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "securityScheme2" @@ -139,26 +138,26 @@ public class OpenApiComponentsTests } }; - public static OpenApiComponents BasicComponents = new OpenApiComponents(); + public static OpenApiComponents BasicComponents = new(); - public static OpenApiComponents BrokenComponents = new OpenApiComponents + public static OpenApiComponents BrokenComponents = new() { Schemas = new Dictionary { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { Type = "string" }, ["schema2"] = null, ["schema3"] = null, - ["schema4"] = new OpenApiSchema + ["schema4"] = new() { Type = "string", AllOf = new List { null, null, - new OpenApiSchema + new() { Type = "string" }, @@ -169,24 +168,24 @@ public class OpenApiComponentsTests } }; - public static OpenApiComponents TopLevelReferencingComponents = new OpenApiComponents + public static OpenApiComponents TopLevelReferencingComponents = new() { Schemas = { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema2" } }, - ["schema2"] = new OpenApiSchema + ["schema2"] = new() { Type = "object", Properties = { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "string" } @@ -195,32 +194,32 @@ public class OpenApiComponentsTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiComponents + public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new() { Schemas = { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { Type = "object", Properties = { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema1" } }, - ["schema2"] = new OpenApiSchema + ["schema2"] = new() { Type = "object", Properties = { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "string" } @@ -229,13 +228,13 @@ public class OpenApiComponentsTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponents = new OpenApiComponents + public static OpenApiComponents TopLevelSelfReferencingComponents = new() { Schemas = { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema1" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs index 477b0fa67..b33029261 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiContactTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Any; @@ -15,12 +14,12 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiContactTests { - public static OpenApiContact BasicContact = new OpenApiContact(); + public static OpenApiContact BasicContact = new(); - public static OpenApiContact AdvanceContact = new OpenApiContact + public static OpenApiContact AdvanceContact = new() { Name = "API Support", - Url = new Uri("http://www.example.com/support"), + Url = new("http://www.example.com/support"), Email = "support@example.com", Extensions = new Dictionary { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs index 75903049c..1538aa2fb 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiDocumentTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -14,7 +13,6 @@ using Microsoft.OpenApi.Writers; using VerifyXunit; using Xunit; -using Xunit.Abstractions; namespace Microsoft.OpenApi.Tests.Models { @@ -22,24 +20,24 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiDocumentTests { - public static OpenApiComponents TopLevelReferencingComponents = new OpenApiComponents + public static OpenApiComponents TopLevelReferencingComponents = new() { Schemas = { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema2" } }, - ["schema2"] = new OpenApiSchema + ["schema2"] = new() { Type = "object", Properties = { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "string" } @@ -48,32 +46,32 @@ public class OpenApiDocumentTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiComponents + public static OpenApiComponents TopLevelSelfReferencingComponentsWithOtherProperties = new() { Schemas = { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { Type = "object", Properties = { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema1" } }, - ["schema2"] = new OpenApiSchema + ["schema2"] = new() { Type = "object", Properties = { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "string" } @@ -82,13 +80,13 @@ public class OpenApiDocumentTests } }; - public static OpenApiComponents TopLevelSelfReferencingComponents = new OpenApiComponents + public static OpenApiComponents TopLevelSelfReferencingComponents = new() { Schemas = { - ["schema1"] = new OpenApiSchema + ["schema1"] = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schema1" @@ -97,38 +95,38 @@ public class OpenApiDocumentTests } }; - public static OpenApiDocument SimpleDocumentWithTopLevelReferencingComponents = new OpenApiDocument + public static OpenApiDocument SimpleDocumentWithTopLevelReferencingComponents = new() { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0" }, Components = TopLevelReferencingComponents }; - public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponentsWithOtherProperties = new OpenApiDocument + public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponentsWithOtherProperties = new() { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0" }, Components = TopLevelSelfReferencingComponentsWithOtherProperties }; - public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponents = new OpenApiDocument + public static OpenApiDocument SimpleDocumentWithTopLevelSelfReferencingComponents = new() { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0" }, Components = TopLevelSelfReferencingComponents }; - public static OpenApiComponents AdvancedComponentsWithReference = new OpenApiComponents + public static OpenApiComponents AdvancedComponentsWithReference = new() { Schemas = new Dictionary { - ["pet"] = new OpenApiSchema + ["pet"] = new() { Type = "object", Required = new HashSet @@ -138,27 +136,27 @@ public class OpenApiDocumentTests }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, }, - Reference = new OpenApiReference + Reference = new() { Id = "pet", Type = ReferenceType.Schema } }, - ["newPet"] = new OpenApiSchema + ["newPet"] = new() { Type = "object", Required = new HashSet @@ -167,27 +165,27 @@ public class OpenApiDocumentTests }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, }, - Reference = new OpenApiReference + Reference = new() { Id = "newPet", Type = ReferenceType.Schema } }, - ["errorModel"] = new OpenApiSchema + ["errorModel"] = new() { Type = "object", Required = new HashSet @@ -197,17 +195,17 @@ public class OpenApiDocumentTests }, Properties = new Dictionary { - ["code"] = new OpenApiSchema + ["code"] = new() { Type = "integer", Format = "int32" }, - ["message"] = new OpenApiSchema + ["message"] = new() { Type = "string" } }, - Reference = new OpenApiReference + Reference = new() { Id = "errorModel", Type = ReferenceType.Schema @@ -223,92 +221,92 @@ public class OpenApiDocumentTests public static OpenApiSchema ErrorModelSchemaWithReference = AdvancedComponentsWithReference.Schemas["errorModel"]; - public static OpenApiDocument AdvancedDocumentWithReference = new OpenApiDocument + public static OpenApiDocument AdvancedDocumentWithReference = new() { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0", Title = "Swagger Petstore (Simple)", Description = "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - TermsOfService = new Uri("http://helloreverb.com/terms/"), - Contact = new OpenApiContact + TermsOfService = new("http://helloreverb.com/terms/"), + Contact = new() { Name = "Swagger API team", Email = "foo@example.com", - Url = new Uri("http://swagger.io") + Url = new("http://swagger.io") }, - License = new OpenApiLicense + License = new() { Name = "MIT", - Url = new Uri("http://opensource.org/licenses/MIT") + Url = new("http://opensource.org/licenses/MIT") } }, Servers = new List { - new OpenApiServer + new() { Url = "http://petstore.swagger.io/api" } }, - Paths = new OpenApiPaths + Paths = new() { - ["/pets"] = new OpenApiPathItem + ["/pets"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns all pets from the system that the user has access to", OperationId = "findPets", Parameters = new List { - new OpenApiParameter + new() { Name = "tags", In = ParameterLocation.Query, Description = "tags to filter by", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } } }, - new OpenApiParameter + new() { Name = "limit", In = ParameterLocation.Query, Description = "maximum number of results to return", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = PetSchemaWithReference } }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = PetSchemaWithReference @@ -316,23 +314,23 @@ public class OpenApiDocumentTests } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } @@ -340,52 +338,52 @@ public class OpenApiDocumentTests } } }, - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { Description = "Creates a new pet in the store. Duplicates are allowed", OperationId = "addPet", - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "Pet to add to the store", Required = true, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = NewPetSchemaWithReference } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = PetSchemaWithReference }, } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } @@ -395,64 +393,64 @@ public class OpenApiDocumentTests } } }, - ["/pets/{id}"] = new OpenApiPathItem + ["/pets/{id}"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns a user based on a single ID, if the user does not have access to the pet", OperationId = "findPetById", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = PetSchemaWithReference }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { Schema = PetSchemaWithReference } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } @@ -460,48 +458,48 @@ public class OpenApiDocumentTests } } }, - [OperationType.Delete] = new OpenApiOperation + [OperationType.Delete] = new() { Description = "deletes a single pet based on the ID supplied", OperationId = "deletePet", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to delete", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["204"] = new OpenApiResponse + ["204"] = new() { Description = "pet deleted" }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchemaWithReference } @@ -515,11 +513,11 @@ public class OpenApiDocumentTests Components = AdvancedComponentsWithReference }; - public static OpenApiComponents AdvancedComponents = new OpenApiComponents + public static OpenApiComponents AdvancedComponents = new() { Schemas = new Dictionary { - ["pet"] = new OpenApiSchema + ["pet"] = new() { Type = "object", Required = new HashSet @@ -529,22 +527,22 @@ public class OpenApiDocumentTests }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, } }, - ["newPet"] = new OpenApiSchema + ["newPet"] = new() { Type = "object", Required = new HashSet @@ -553,22 +551,22 @@ public class OpenApiDocumentTests }, Properties = new Dictionary { - ["id"] = new OpenApiSchema + ["id"] = new() { Type = "integer", Format = "int64" }, - ["name"] = new OpenApiSchema + ["name"] = new() { Type = "string" }, - ["tag"] = new OpenApiSchema + ["tag"] = new() { Type = "string" }, } }, - ["errorModel"] = new OpenApiSchema + ["errorModel"] = new() { Type = "object", Required = new HashSet @@ -578,12 +576,12 @@ public class OpenApiDocumentTests }, Properties = new Dictionary { - ["code"] = new OpenApiSchema + ["code"] = new() { Type = "integer", Format = "int32" }, - ["message"] = new OpenApiSchema + ["message"] = new() { Type = "string" } @@ -598,92 +596,92 @@ public class OpenApiDocumentTests public static OpenApiSchema ErrorModelSchema = AdvancedComponents.Schemas["errorModel"]; - public OpenApiDocument AdvancedDocument = new OpenApiDocument + public OpenApiDocument AdvancedDocument = new() { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0", Title = "Swagger Petstore (Simple)", Description = "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - TermsOfService = new Uri("http://helloreverb.com/terms/"), - Contact = new OpenApiContact + TermsOfService = new("http://helloreverb.com/terms/"), + Contact = new() { Name = "Swagger API team", Email = "foo@example.com", - Url = new Uri("http://swagger.io") + Url = new("http://swagger.io") }, - License = new OpenApiLicense + License = new() { Name = "MIT", - Url = new Uri("http://opensource.org/licenses/MIT") + Url = new("http://opensource.org/licenses/MIT") } }, Servers = new List { - new OpenApiServer + new() { Url = "http://petstore.swagger.io/api" } }, - Paths = new OpenApiPaths + Paths = new() { - ["/pets"] = new OpenApiPathItem + ["/pets"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns all pets from the system that the user has access to", OperationId = "findPets", Parameters = new List { - new OpenApiParameter + new() { Name = "tags", In = ParameterLocation.Query, Description = "tags to filter by", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } } }, - new OpenApiParameter + new() { Name = "limit", In = ParameterLocation.Query, Description = "maximum number of results to return", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = PetSchema } }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = PetSchema @@ -691,23 +689,23 @@ public class OpenApiDocumentTests } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -715,52 +713,52 @@ public class OpenApiDocumentTests } } }, - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { Description = "Creates a new pet in the store. Duplicates are allowed", OperationId = "addPet", - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "Pet to add to the store", Required = true, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = NewPetSchema } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = PetSchema }, } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -770,64 +768,64 @@ public class OpenApiDocumentTests } } }, - ["/pets/{id}"] = new OpenApiPathItem + ["/pets/{id}"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns a user based on a single ID, if the user does not have access to the pet", OperationId = "findPetById", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = PetSchema }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { Schema = PetSchema } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -835,48 +833,48 @@ public class OpenApiDocumentTests } } }, - [OperationType.Delete] = new OpenApiOperation + [OperationType.Delete] = new() { Description = "deletes a single pet based on the ID supplied", OperationId = "deletePet", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to delete", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["204"] = new OpenApiResponse + ["204"] = new() { Description = "pet deleted" }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -890,9 +888,9 @@ public class OpenApiDocumentTests Components = AdvancedComponents }; - public static OpenApiDocument DuplicateExtensions = new OpenApiDocument + public static OpenApiDocument DuplicateExtensions = new() { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0", Title = "Swagger Petstore (Simple)", @@ -900,29 +898,29 @@ public class OpenApiDocumentTests }, Servers = new List { - new OpenApiServer + new() { Url = "http://petstore.swagger.io/api" } }, - Paths = new OpenApiPaths + Paths = new() { - ["/add/{operand1}/{operand2}"] = new OpenApiPathItem + ["/add/{operand1}/{operand2}"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { OperationId = "addByOperand1AndByOperand2", Parameters = new List { - new OpenApiParameter + new() { Name = "operand1", In = ParameterLocation.Path, Description = "The first operand", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Extensions = new Dictionary @@ -935,13 +933,13 @@ public class OpenApiDocumentTests ["my-extension"] = new Any.OpenApiInteger(4), } }, - new OpenApiParameter + new() { Name = "operand2", In = ParameterLocation.Path, Description = "The second operand", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Extensions = new Dictionary @@ -955,16 +953,16 @@ public class OpenApiDocumentTests } }, }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = PetSchema @@ -979,99 +977,99 @@ public class OpenApiDocumentTests } }; - public OpenApiDocument AdvancedDocumentWithServerVariable = new OpenApiDocument + public OpenApiDocument AdvancedDocumentWithServerVariable = new() { - Info = new OpenApiInfo + Info = new() { Version = "1.0.0", Title = "Swagger Petstore (Simple)", Description = "A sample API that uses a petstore as an example to demonstrate features in the swagger-2.0 specification", - TermsOfService = new Uri("http://helloreverb.com/terms/"), - Contact = new OpenApiContact + TermsOfService = new("http://helloreverb.com/terms/"), + Contact = new() { Name = "Swagger API team", Email = "foo@example.com", - Url = new Uri("http://swagger.io") + Url = new("http://swagger.io") }, - License = new OpenApiLicense + License = new() { Name = "MIT", - Url = new Uri("http://opensource.org/licenses/MIT") + Url = new("http://opensource.org/licenses/MIT") } }, Servers = new List { - new OpenApiServer + new() { Url = "https://{endpoint}/openai", Variables = new Dictionary { - ["endpoint"] = new OpenApiServerVariable + ["endpoint"] = new() { Default = "your-resource-name.openai.azure.com" } } } }, - Paths = new OpenApiPaths + Paths = new() { - ["/pets"] = new OpenApiPathItem + ["/pets"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns all pets from the system that the user has access to", OperationId = "findPets", Parameters = new List { - new OpenApiParameter + new() { Name = "tags", In = ParameterLocation.Query, Description = "tags to filter by", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "string" } } }, - new OpenApiParameter + new() { Name = "limit", In = ParameterLocation.Query, Description = "maximum number of results to return", Required = false, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = PetSchema } }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", Items = PetSchema @@ -1079,23 +1077,23 @@ public class OpenApiDocumentTests } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -1103,52 +1101,52 @@ public class OpenApiDocumentTests } } }, - [OperationType.Post] = new OpenApiOperation + [OperationType.Post] = new() { Description = "Creates a new pet in the store. Duplicates are allowed", OperationId = "addPet", - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "Pet to add to the store", Required = true, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = NewPetSchema } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = PetSchema }, } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -1158,64 +1156,64 @@ public class OpenApiDocumentTests } } }, - ["/pets/{id}"] = new OpenApiPathItem + ["/pets/{id}"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Description = "Returns a user based on a single ID, if the user does not have access to the pet", OperationId = "findPetById", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to fetch", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "pet response", Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = PetSchema }, - ["application/xml"] = new OpenApiMediaType + ["application/xml"] = new() { Schema = PetSchema } } }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -1223,48 +1221,48 @@ public class OpenApiDocumentTests } } }, - [OperationType.Delete] = new OpenApiOperation + [OperationType.Delete] = new() { Description = "deletes a single pet based on the ID supplied", OperationId = "deletePet", Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Path, Description = "ID of pet to delete", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int64" } } }, - Responses = new OpenApiResponses + Responses = new() { - ["204"] = new OpenApiResponse + ["204"] = new() { Description = "pet deleted" }, - ["4XX"] = new OpenApiResponse + ["4XX"] = new() { Description = "unexpected client error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } } }, - ["5XX"] = new OpenApiResponse + ["5XX"] = new() { Description = "unexpected server error", Content = new Dictionary { - ["text/html"] = new OpenApiMediaType + ["text/html"] = new() { Schema = ErrorModelSchema } @@ -1285,7 +1283,7 @@ public async Task SerializeAdvancedDocumentAsV3JsonWorks(bool produceTerseOutput { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedDocument.SerializeAsV3(writer); @@ -1302,7 +1300,7 @@ public async Task SerializeAdvancedDocumentWithReferenceAsV3JsonWorks(bool produ { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedDocumentWithReference.SerializeAsV3(writer); @@ -1319,7 +1317,7 @@ public async Task SerializeAdvancedDocumentWithServerVariableAsV2JsonWorks(bool { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedDocumentWithServerVariable.SerializeAsV2(writer); @@ -1336,7 +1334,7 @@ public async Task SerializeAdvancedDocumentAsV2JsonWorks(bool produceTerseOutput { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedDocument.SerializeAsV2(writer); @@ -1353,7 +1351,7 @@ public async Task SerializeDuplicateExtensionsAsV3JsonWorks(bool produceTerseOut { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act DuplicateExtensions.SerializeAsV3(writer); @@ -1370,7 +1368,7 @@ public async Task SerializeDuplicateExtensionsAsV2JsonWorks(bool produceTerseOut { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act DuplicateExtensions.SerializeAsV2(writer); @@ -1387,7 +1385,7 @@ public async Task SerializeAdvancedDocumentWithReferenceAsV2JsonWorks(bool produ { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedDocumentWithReference.SerializeAsV2(writer); @@ -1487,30 +1485,30 @@ public void SerializeDocumentWithReferenceButNoComponents() // Arrange var document = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Test", Version = "1.0.0" }, - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { - Reference = new OpenApiReference + Reference = new() { Id = "test", Type = ReferenceType.Schema @@ -1549,10 +1547,10 @@ public void SerializeRelativePathAsV2JsonWorks() """; var doc = new OpenApiDocument { - Info = new OpenApiInfo { Version = "1.0.0" }, + Info = new() { Version = "1.0.0" }, Servers = new List { - new OpenApiServer + new() { Url = "/server1" } @@ -1583,10 +1581,10 @@ public void SerializeRelativePathWithHostAsV2JsonWorks() """; var doc = new OpenApiDocument { - Info = new OpenApiInfo { Version = "1.0.0" }, + Info = new() { Version = "1.0.0" }, Servers = new List { - new OpenApiServer + new() { Url = "//example.org/server1" } @@ -1616,10 +1614,10 @@ public void SerializeRelativeRootPathWithHostAsV2JsonWorks() """; var doc = new OpenApiDocument { - Info = new OpenApiInfo { Version = "1.0.0" }, + Info = new() { Version = "1.0.0" }, Servers = new List { - new OpenApiServer + new() { Url = "//example.org/" } @@ -1703,27 +1701,27 @@ public void SerializeV2DocumentWithNonArraySchemaTypeDoesNotWriteOutCollectionFo var doc = new OpenApiDocument { - Info = new OpenApiInfo(), - Paths = new OpenApiPaths + Info = new(), + Paths = new() { - ["/foo"] = new OpenApiPathItem + ["/foo"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Parameters = new List { - new OpenApiParameter + new() { In = ParameterLocation.Query, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } }, - Responses = new OpenApiResponses() + Responses = new() } } } @@ -1770,45 +1768,45 @@ public void SerializeV2DocumentWithStyleAsNullDoesNotWriteOutStyleValue() var doc = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "magic style", Version = "1.0.0" }, - Paths = new OpenApiPaths + Paths = new() { - ["/foo"] = new OpenApiPathItem + ["/foo"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Parameters = new List { - new OpenApiParameter + new() { Name = "id", In = ParameterLocation.Query, - Schema = new OpenApiSchema + Schema = new() { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "integer" } } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "foo", Content = new Dictionary { - ["text/plain"] = new OpenApiMediaType + ["text/plain"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "string" } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs index bf0561367..fe699f7aa 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiEncodingTests.cs @@ -11,9 +11,9 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiEncodingTests { - public static OpenApiEncoding BasicEncoding = new OpenApiEncoding(); + public static OpenApiEncoding BasicEncoding = new(); - public static OpenApiEncoding AdvanceEncoding = new OpenApiEncoding + public static OpenApiEncoding AdvanceEncoding = new() { ContentType = "image/png, image/jpeg", Style = ParameterStyle.Simple, diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs index b725f99a6..14561debd 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExampleTests.cs @@ -18,7 +18,7 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiExampleTests { - public static OpenApiExample AdvancedExample = new OpenApiExample + public static OpenApiExample AdvancedExample = new() { Value = new OpenApiObject { @@ -57,9 +57,9 @@ public class OpenApiExampleTests } }; - public static OpenApiExample ReferencedExample = new OpenApiExample + public static OpenApiExample ReferencedExample = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Example, Id = "example1", @@ -107,7 +107,7 @@ public async Task SerializeAdvancedExampleAsV3JsonWorks(bool produceTerseOutput) { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedExample.SerializeAsV3(writer); @@ -124,7 +124,7 @@ public async Task SerializeReferencedExampleAsV3JsonWorks(bool produceTerseOutpu { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedExample.SerializeAsV3(writer); @@ -141,7 +141,7 @@ public async Task SerializeReferencedExampleAsV3JsonWithoutReferenceWorks(bool p { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedExample.SerializeAsV3WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs index 52a916d58..25bf6315d 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiExternalDocsTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using FluentAssertions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; @@ -12,11 +11,11 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiExternalDocsTests { - public static OpenApiExternalDocs BasicExDocs = new OpenApiExternalDocs(); + public static OpenApiExternalDocs BasicExDocs = new(); - public static OpenApiExternalDocs AdvanceExDocs = new OpenApiExternalDocs + public static OpenApiExternalDocs AdvanceExDocs = new() { - Url = new Uri("https://example.com"), + Url = new("https://example.com"), Description = "Find more info here" }; diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs index adc0848b5..b54c2457e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiHeaderTests.cs @@ -8,7 +8,6 @@ using Microsoft.OpenApi.Writers; using VerifyXunit; using Xunit; -using Xunit.Abstractions; namespace Microsoft.OpenApi.Tests.Models { @@ -16,25 +15,25 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiHeaderTests { - public static OpenApiHeader AdvancedHeader = new OpenApiHeader + public static OpenApiHeader AdvancedHeader = new() { Description = "sampleHeader", - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" } }; - public static OpenApiHeader ReferencedHeader = new OpenApiHeader + public static OpenApiHeader ReferencedHeader = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Header, Id = "example1", }, Description = "sampleHeader", - Schema = new OpenApiSchema + Schema = new() { Type = "integer", Format = "int32" @@ -48,7 +47,7 @@ public async Task SerializeAdvancedHeaderAsV3JsonWorks(bool produceTerseOutput) { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedHeader.SerializeAsV3(writer); @@ -65,7 +64,7 @@ public async Task SerializeReferencedHeaderAsV3JsonWorks(bool produceTerseOutput { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedHeader.SerializeAsV3(writer); @@ -82,7 +81,7 @@ public async Task SerializeReferencedHeaderAsV3JsonWithoutReferenceWorks(bool pr { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedHeader.SerializeAsV3WithoutReference(writer); @@ -100,7 +99,7 @@ public async Task SerializeAdvancedHeaderAsV2JsonWorks(bool produceTerseOutput) { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedHeader.SerializeAsV2(writer); @@ -117,7 +116,7 @@ public async Task SerializeReferencedHeaderAsV2JsonWorks(bool produceTerseOutput { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedHeader.SerializeAsV2(writer); @@ -134,7 +133,7 @@ public async Task SerializeReferencedHeaderAsV2JsonWithoutReferenceWorks(bool pr { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedHeader.SerializeAsV2WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs index dd744b079..aed69a7a8 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiInfoTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Any; @@ -15,11 +14,11 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiInfoTests { - public static OpenApiInfo AdvanceInfo = new OpenApiInfo + public static OpenApiInfo AdvanceInfo = new() { Title = "Sample Pet Store App", Description = "This is a sample server for a pet store.", - TermsOfService = new Uri("http://example.com/terms/"), + TermsOfService = new("http://example.com/terms/"), Contact = OpenApiContactTests.AdvanceContact, License = OpenApiLicenseTests.AdvanceLicense, Version = "1.1.1", @@ -29,7 +28,7 @@ public class OpenApiInfoTests } }; - public static OpenApiInfo BasicInfo = new OpenApiInfo + public static OpenApiInfo BasicInfo = new() { Title = "Sample Pet Store App", Version = "1.0" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs index 113ea8440..e5620427b 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLicenseTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Any; @@ -15,15 +14,15 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiLicenseTests { - public static OpenApiLicense BasicLicense = new OpenApiLicense + public static OpenApiLicense BasicLicense = new() { Name = "Apache 2.0" }; - public static OpenApiLicense AdvanceLicense = new OpenApiLicense + public static OpenApiLicense AdvanceLicense = new() { Name = "Apache 2.0", - Url = new Uri("http://www.apache.org/licenses/LICENSE-2.0.html"), + Url = new("http://www.apache.org/licenses/LICENSE-2.0.html"), Extensions = new Dictionary { {"x-copyright", new OpenApiString("Abc")} @@ -123,7 +122,7 @@ public void ShouldCopyFromOriginalObjectWithoutMutating() // Act licenseCopy.Name = ""; - licenseCopy.Url = new Uri("https://exampleCopy.com"); + licenseCopy.Url = new("https://exampleCopy.com"); // Assert Assert.NotEqual(AdvanceLicense.Name, licenseCopy.Name); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs index 3281c62b5..3f95fb9e3 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs @@ -17,17 +17,17 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiLinkTests { - public static OpenApiLink AdvancedLink = new OpenApiLink + public static OpenApiLink AdvancedLink = new() { OperationId = "operationId1", Parameters = { - ["parameter1"] = new RuntimeExpressionAnyWrapper + ["parameter1"] = new() { Expression = RuntimeExpression.Build("$request.path.id") } }, - RequestBody = new RuntimeExpressionAnyWrapper + RequestBody = new() { Any = new OpenApiObject { @@ -35,15 +35,15 @@ public class OpenApiLinkTests } }, Description = "description1", - Server = new OpenApiServer + Server = new() { Description = "serverDescription1" } }; - public static OpenApiLink ReferencedLink = new OpenApiLink + public static OpenApiLink ReferencedLink = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Link, Id = "example1", @@ -51,12 +51,12 @@ public class OpenApiLinkTests OperationId = "operationId1", Parameters = { - ["parameter1"] = new RuntimeExpressionAnyWrapper + ["parameter1"] = new() { Expression = RuntimeExpression.Build("$request.path.id") } }, - RequestBody = new RuntimeExpressionAnyWrapper + RequestBody = new() { Any = new OpenApiObject { @@ -64,7 +64,7 @@ public class OpenApiLinkTests } }, Description = "description1", - Server = new OpenApiServer + Server = new() { Description = "serverDescription1" } @@ -77,7 +77,7 @@ public async Task SerializeAdvancedLinkAsV3JsonWorksAsync(bool produceTerseOutpu { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedLink.SerializeAsV3(writer); @@ -94,7 +94,7 @@ public async Task SerializeReferencedLinkAsV3JsonWorksAsync(bool produceTerseOut { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedLink.SerializeAsV3(writer); @@ -111,7 +111,7 @@ public async Task SerializeReferencedLinkAsV3JsonWithoutReferenceWorksAsync(bool { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedLink.SerializeAsV3WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs index 9a4e62818..97addbb1e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiMediaTypeTests.cs @@ -14,9 +14,9 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiMediaTypeTests { - public static OpenApiMediaType BasicMediaType = new OpenApiMediaType(); + public static OpenApiMediaType BasicMediaType = new(); - public static OpenApiMediaType AdvanceMediaType = new OpenApiMediaType + public static OpenApiMediaType AdvanceMediaType = new() { Example = new OpenApiInteger(42), Encoding = new Dictionary @@ -25,7 +25,7 @@ public class OpenApiMediaTypeTests } }; - public static OpenApiMediaType MediaTypeWithObjectExample = new OpenApiMediaType + public static OpenApiMediaType MediaTypeWithObjectExample = new() { Example = new OpenApiObject { @@ -66,7 +66,7 @@ public class OpenApiMediaTypeTests } }; - public static OpenApiMediaType MediaTypeWithXmlExample = new OpenApiMediaType + public static OpenApiMediaType MediaTypeWithXmlExample = new() { Example = new OpenApiString("123"), Encoding = new Dictionary @@ -75,10 +75,10 @@ public class OpenApiMediaTypeTests } }; - public static OpenApiMediaType MediaTypeWithObjectExamples = new OpenApiMediaType + public static OpenApiMediaType MediaTypeWithObjectExamples = new() { Examples = { - ["object1"] = new OpenApiExample + ["object1"] = new() { Value = new OpenApiObject { diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs index 0237068a3..3327887c9 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Extensions; @@ -13,11 +12,11 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiOAuthFlowTests { - public static OpenApiOAuthFlow BasicOAuthFlow = new OpenApiOAuthFlow(); + public static OpenApiOAuthFlow BasicOAuthFlow = new(); - public static OpenApiOAuthFlow PartialOAuthFlow = new OpenApiOAuthFlow + public static OpenApiOAuthFlow PartialOAuthFlow = new() { - AuthorizationUrl = new Uri("http://example.com/authorization"), + AuthorizationUrl = new("http://example.com/authorization"), Scopes = new Dictionary { ["scopeName3"] = "description3", @@ -25,11 +24,11 @@ public class OpenApiOAuthFlowTests } }; - public static OpenApiOAuthFlow CompleteOAuthFlow = new OpenApiOAuthFlow + public static OpenApiOAuthFlow CompleteOAuthFlow = new() { - AuthorizationUrl = new Uri("http://example.com/authorization"), - TokenUrl = new Uri("http://example.com/token"), - RefreshUrl = new Uri("http://example.com/refresh"), + AuthorizationUrl = new("http://example.com/authorization"), + TokenUrl = new("http://example.com/token"), + RefreshUrl = new("http://example.com/refresh"), Scopes = new Dictionary { ["scopeName3"] = "description3", diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs index d4b2364a7..1bb473a89 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOAuthFlowsTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Extensions; @@ -13,13 +12,13 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiOAuthFlowsTests { - public static OpenApiOAuthFlows BasicOAuthFlows = new OpenApiOAuthFlows(); + public static OpenApiOAuthFlows BasicOAuthFlows = new(); - public static OpenApiOAuthFlows OAuthFlowsWithSingleFlow = new OpenApiOAuthFlows + public static OpenApiOAuthFlows OAuthFlowsWithSingleFlow = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { - AuthorizationUrl = new Uri("http://example.com/authorization"), + AuthorizationUrl = new("http://example.com/authorization"), Scopes = new Dictionary { ["scopeName1"] = "description1", @@ -28,21 +27,21 @@ public class OpenApiOAuthFlowsTests } }; - public static OpenApiOAuthFlows OAuthFlowsWithMultipleFlows = new OpenApiOAuthFlows + public static OpenApiOAuthFlows OAuthFlowsWithMultipleFlows = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { - AuthorizationUrl = new Uri("http://example.com/authorization"), + AuthorizationUrl = new("http://example.com/authorization"), Scopes = new Dictionary { ["scopeName1"] = "description1", ["scopeName2"] = "description2" } }, - Password = new OpenApiOAuthFlow + Password = new() { - TokenUrl = new Uri("http://example.com/token"), - RefreshUrl = new Uri("http://example.com/refresh"), + TokenUrl = new("http://example.com/token"), + RefreshUrl = new("http://example.com/refresh"), Scopes = new Dictionary { ["scopeName3"] = "description3", diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs index e871735f3..ec6ca8326 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiOperationTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Extensions; @@ -13,40 +12,40 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiOperationTests { - private static readonly OpenApiOperation _basicOperation = new OpenApiOperation(); + private static readonly OpenApiOperation _basicOperation = new(); - private static readonly OpenApiOperation _operationWithBody = new OpenApiOperation + private static readonly OpenApiOperation _operationWithBody = new() { Summary = "summary1", Description = "operationDescription", - ExternalDocs = new OpenApiExternalDocs + ExternalDocs = new() { Description = "externalDocsDescription", - Url = new Uri("http://external.com") + Url = new("http://external.com") }, OperationId = "operationId1", Parameters = new List { - new OpenApiParameter + new() { In = ParameterLocation.Path, Name = "parameter1", }, - new OpenApiParameter + new() { In = ParameterLocation.Header, Name = "parameter2" } }, - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "description2", Required = true, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "number", Minimum = 5, @@ -55,23 +54,23 @@ public class OpenApiOperationTests } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { - Reference = new OpenApiReference + Reference = new() { Id = "response1", Type = ReferenceType.Response } }, - ["400"] = new OpenApiResponse + ["400"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "number", Minimum = 5, @@ -83,7 +82,7 @@ public class OpenApiOperationTests }, Servers = new List { - new OpenApiServer + new() { Url = "http://server.com", Description = "serverDescription" @@ -91,18 +90,18 @@ public class OpenApiOperationTests } }; - private static readonly OpenApiOperation _advancedOperationWithTagsAndSecurity = new OpenApiOperation + private static readonly OpenApiOperation _advancedOperationWithTagsAndSecurity = new() { Tags = new List { - new OpenApiTag + new() { Name = "tagName1", Description = "tagDescription1", }, - new OpenApiTag + new() { - Reference = new OpenApiReference + Reference = new() { Id = "tagId1", Type = ReferenceType.Tag @@ -111,34 +110,34 @@ public class OpenApiOperationTests }, Summary = "summary1", Description = "operationDescription", - ExternalDocs = new OpenApiExternalDocs + ExternalDocs = new() { Description = "externalDocsDescription", - Url = new Uri("http://external.com") + Url = new("http://external.com") }, OperationId = "operationId1", Parameters = new List { - new OpenApiParameter + new() { In = ParameterLocation.Path, Name = "parameter1" }, - new OpenApiParameter + new() { In = ParameterLocation.Header, Name = "parameter2" } }, - RequestBody = new OpenApiRequestBody + RequestBody = new() { Description = "description2", Required = true, Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "number", Minimum = 5, @@ -147,23 +146,23 @@ public class OpenApiOperationTests } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { - Reference = new OpenApiReference + Reference = new() { Id = "response1", Type = ReferenceType.Response } }, - ["400"] = new OpenApiResponse + ["400"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "number", Minimum = 5, @@ -175,19 +174,19 @@ public class OpenApiOperationTests }, Security = new List { - new OpenApiSecurityRequirement + new() { - [new OpenApiSecurityScheme + [new() { - Reference = new OpenApiReference + Reference = new() { Id = "securitySchemeId1", Type = ReferenceType.SecurityScheme } }] = new List(), - [new OpenApiSecurityScheme + [new() { - Reference = new OpenApiReference + Reference = new() { Id = "securitySchemeId2", Type = ReferenceType.SecurityScheme @@ -201,7 +200,7 @@ [new OpenApiSecurityScheme }, Servers = new List { - new OpenApiServer + new() { Url = "http://server.com", Description = "serverDescription" @@ -210,41 +209,41 @@ [new OpenApiSecurityScheme }; private static readonly OpenApiOperation _operationWithFormData = - new OpenApiOperation + new() { Summary = "Updates a pet in the store with form data", Description = "", OperationId = "updatePetWithForm", Parameters = new List { - new OpenApiParameter + new() { Name = "petId", In = ParameterLocation.Path, Description = "ID of pet that needs to be updated", Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string" } } }, - RequestBody = new OpenApiRequestBody + RequestBody = new() { Content = { - ["application/x-www-form-urlencoded"] = new OpenApiMediaType + ["application/x-www-form-urlencoded"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" @@ -256,18 +255,18 @@ [new OpenApiSecurityScheme } } }, - ["multipart/form-data"] = new OpenApiMediaType + ["multipart/form-data"] = new() { - Schema = new OpenApiSchema + Schema = new() { Properties = { - ["name"] = new OpenApiSchema + ["name"] = new() { Description = "Updated name of the pet", Type = "string" }, - ["status"] = new OpenApiSchema + ["status"] = new() { Description = "Updated status of the pet", Type = "string" @@ -281,13 +280,13 @@ [new OpenApiSecurityScheme } } }, - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Description = "Pet updated." }, - ["405"] = new OpenApiResponse + ["405"] = new() { Description = "Invalid input" } diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs index a39a276d1..a49f415e3 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiParameterTests.cs @@ -19,24 +19,24 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiParameterTests { - public static OpenApiParameter BasicParameter = new OpenApiParameter + public static OpenApiParameter BasicParameter = new() { Name = "name1", In = ParameterLocation.Path }; - public static OpenApiParameter ReferencedParameter = new OpenApiParameter + public static OpenApiParameter ReferencedParameter = new() { Name = "name1", In = ParameterLocation.Path, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Parameter, Id = "example1" } }; - public static OpenApiParameter AdvancedPathParameterWithSchema = new OpenApiParameter + public static OpenApiParameter AdvancedPathParameterWithSchema = new() { Name = "name1", In = ParameterLocation.Path, @@ -46,19 +46,19 @@ public class OpenApiParameterTests Style = ParameterStyle.Simple, Explode = true, - Schema = new OpenApiSchema + Schema = new() { Title = "title2", Description = "description2", OneOf = new List { - new OpenApiSchema { Type = "number", Format = "double" }, - new OpenApiSchema { Type = "string" } + new() { Type = "number", Format = "double" }, + new() { Type = "string" } } }, Examples = new Dictionary { - ["test"] = new OpenApiExample + ["test"] = new() { Summary = "summary3", Description = "description3" @@ -66,17 +66,17 @@ public class OpenApiParameterTests } }; - public static OpenApiParameter ParameterWithFormStyleAndExplodeFalse = new OpenApiParameter + public static OpenApiParameter ParameterWithFormStyleAndExplodeFalse = new() { Name = "name1", In = ParameterLocation.Query, Description = "description1", Style = ParameterStyle.Form, Explode = false, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Enum = new List { @@ -87,17 +87,17 @@ public class OpenApiParameterTests } }; - public static OpenApiParameter ParameterWithFormStyleAndExplodeTrue = new OpenApiParameter + public static OpenApiParameter ParameterWithFormStyleAndExplodeTrue = new() { Name = "name1", In = ParameterLocation.Query, Description = "description1", Style = ParameterStyle.Form, Explode = true, - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Enum = new List { @@ -108,7 +108,7 @@ public class OpenApiParameterTests } }; - public static OpenApiParameter AdvancedHeaderParameterWithSchemaReference = new OpenApiParameter + public static OpenApiParameter AdvancedHeaderParameterWithSchemaReference = new() { Name = "name1", In = ParameterLocation.Header, @@ -118,9 +118,9 @@ public class OpenApiParameterTests Style = ParameterStyle.Simple, Explode = true, - Schema = new OpenApiSchema + Schema = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schemaObject1" @@ -129,7 +129,7 @@ public class OpenApiParameterTests }, Examples = new Dictionary { - ["test"] = new OpenApiExample + ["test"] = new() { Summary = "summary3", Description = "description3" @@ -137,7 +137,7 @@ public class OpenApiParameterTests } }; - public static OpenApiParameter AdvancedHeaderParameterWithSchemaTypeObject = new OpenApiParameter + public static OpenApiParameter AdvancedHeaderParameterWithSchemaTypeObject = new() { Name = "name1", In = ParameterLocation.Header, @@ -147,13 +147,13 @@ public class OpenApiParameterTests Style = ParameterStyle.Simple, Explode = true, - Schema = new OpenApiSchema + Schema = new() { Type = "object" }, Examples = new Dictionary { - ["test"] = new OpenApiExample + ["test"] = new() { Summary = "summary3", Description = "description3" @@ -293,7 +293,7 @@ public async Task SerializeReferencedParameterAsV3JsonWorksAsync(bool produceTer { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedParameter.SerializeAsV3(writer); @@ -310,7 +310,7 @@ public async Task SerializeReferencedParameterAsV3JsonWithoutReferenceWorksAsync { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedParameter.SerializeAsV3WithoutReference(writer); @@ -327,7 +327,7 @@ public async Task SerializeReferencedParameterAsV2JsonWorksAsync(bool produceTer { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedParameter.SerializeAsV2(writer); @@ -344,7 +344,7 @@ public async Task SerializeReferencedParameterAsV2JsonWithoutReferenceWorksAsync { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedParameter.SerializeAsV2WithoutReference(writer); @@ -361,7 +361,7 @@ public async Task SerializeParameterWithSchemaReferenceAsV2JsonWorksAsync(bool p { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedHeaderParameterWithSchemaReference.SerializeAsV2(writer); @@ -378,7 +378,7 @@ public async Task SerializeParameterWithSchemaTypeObjectAsV2JsonWorksAsync(bool { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedHeaderParameterWithSchemaTypeObject.SerializeAsV2(writer); @@ -395,7 +395,7 @@ public async Task SerializeParameterWithFormStyleAndExplodeFalseWorksAsync(bool { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ParameterWithFormStyleAndExplodeFalse.SerializeAsV3WithoutReference(writer); @@ -412,7 +412,7 @@ public async Task SerializeParameterWithFormStyleAndExplodeTrueWorksAsync(bool p { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ParameterWithFormStyleAndExplodeTrue.SerializeAsV3WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs index f08338ea2..08ef42fe7 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiRequestBodyTests.cs @@ -15,15 +15,15 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiRequestBodyTests { - public static OpenApiRequestBody AdvancedRequestBody = new OpenApiRequestBody + public static OpenApiRequestBody AdvancedRequestBody = new() { Description = "description", Required = true, Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -31,9 +31,9 @@ public class OpenApiRequestBodyTests } }; - public static OpenApiRequestBody ReferencedRequestBody = new OpenApiRequestBody + public static OpenApiRequestBody ReferencedRequestBody = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.RequestBody, Id = "example1", @@ -42,9 +42,9 @@ public class OpenApiRequestBodyTests Required = true, Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -59,7 +59,7 @@ public async Task SerializeAdvancedRequestBodyAsV3JsonWorksAsync(bool produceTer { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedRequestBody.SerializeAsV3(writer); @@ -76,7 +76,7 @@ public async Task SerializeReferencedRequestBodyAsV3JsonWorksAsync(bool produceT { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedRequestBody.SerializeAsV3(writer); @@ -93,7 +93,7 @@ public async Task SerializeReferencedRequestBodyAsV3JsonWithoutReferenceWorksAsy { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedRequestBody.SerializeAsV3WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs index f12861a3f..ea3a6ee29 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiResponseTests.cs @@ -20,21 +20,21 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiResponseTests { - public static OpenApiResponse BasicResponse = new OpenApiResponse(); + public static OpenApiResponse BasicResponse = new(); - public static OpenApiResponse AdvancedResponse = new OpenApiResponse + public static OpenApiResponse AdvancedResponse = new() { Description = "A complex object array response", Content = { - ["text/plain"] = new OpenApiMediaType + ["text/plain"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { - Reference = new OpenApiReference {Type = ReferenceType.Schema, Id = "customType"} + Reference = new() {Type = ReferenceType.Schema, Id = "customType"} } }, Example = new OpenApiString("Blabla"), @@ -46,18 +46,18 @@ public class OpenApiResponseTests }, Headers = { - ["X-Rate-Limit-Limit"] = new OpenApiHeader + ["X-Rate-Limit-Limit"] = new() { Description = "The number of allowed requests in the current period", - Schema = new OpenApiSchema + Schema = new() { Type = "integer" } }, - ["X-Rate-Limit-Reset"] = new OpenApiHeader + ["X-Rate-Limit-Reset"] = new() { Description = "The number of seconds left in the current period", - Schema = new OpenApiSchema + Schema = new() { Type = "integer" } @@ -65,9 +65,9 @@ public class OpenApiResponseTests } }; - public static OpenApiResponse ReferencedResponse = new OpenApiResponse + public static OpenApiResponse ReferencedResponse = new() { - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Response, Id = "example1" @@ -75,32 +75,32 @@ public class OpenApiResponseTests Description = "A complex object array response", Content = { - ["text/plain"] = new OpenApiMediaType + ["text/plain"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { - Reference = new OpenApiReference {Type = ReferenceType.Schema, Id = "customType"} + Reference = new() {Type = ReferenceType.Schema, Id = "customType"} } } } }, Headers = { - ["X-Rate-Limit-Limit"] = new OpenApiHeader + ["X-Rate-Limit-Limit"] = new() { Description = "The number of allowed requests in the current period", - Schema = new OpenApiSchema + Schema = new() { Type = "integer" } }, - ["X-Rate-Limit-Reset"] = new OpenApiHeader + ["X-Rate-Limit-Reset"] = new() { Description = "The number of seconds left in the current period", - Schema = new OpenApiSchema + Schema = new() { Type = "integer" } @@ -294,7 +294,7 @@ public async Task SerializeReferencedResponseAsV3JsonWorksAsync(bool produceTers { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedResponse.SerializeAsV3(writer); @@ -311,7 +311,7 @@ public async Task SerializeReferencedResponseAsV3JsonWithoutReferenceWorksAsync( { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedResponse.SerializeAsV3WithoutReference(writer); @@ -328,7 +328,7 @@ public async Task SerializeReferencedResponseAsV2JsonWorksAsync(bool produceTers { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedResponse.SerializeAsV2(writer); @@ -345,7 +345,7 @@ public async Task SerializeReferencedResponseAsV2JsonWithoutReferenceWorksAsync( { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedResponse.SerializeAsV2WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index f1b985a62..b4c331830 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -21,9 +20,9 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiSchemaTests { - public static OpenApiSchema BasicSchema = new OpenApiSchema(); + public static OpenApiSchema BasicSchema = new(); - public static OpenApiSchema AdvancedSchemaNumber = new OpenApiSchema + public static OpenApiSchema AdvancedSchemaNumber = new() { Title = "title1", MultipleOf = 3, @@ -34,47 +33,47 @@ public class OpenApiSchemaTests Type = "integer", Nullable = true, - ExternalDocs = new OpenApiExternalDocs + ExternalDocs = new() { - Url = new Uri("http://example.com/externalDocs") + Url = new("http://example.com/externalDocs") } }; - public static OpenApiSchema AdvancedSchemaObject = new OpenApiSchema + public static OpenApiSchema AdvancedSchemaObject = new() { Title = "title1", Properties = new Dictionary { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Properties = new Dictionary { - ["property2"] = new OpenApiSchema + ["property2"] = new() { Type = "integer" }, - ["property3"] = new OpenApiSchema + ["property3"] = new() { Type = "string", MaxLength = 15 } }, }, - ["property4"] = new OpenApiSchema + ["property4"] = new() { Properties = new Dictionary { - ["property5"] = new OpenApiSchema + ["property5"] = new() { Properties = new Dictionary { - ["property6"] = new OpenApiSchema + ["property6"] = new() { Type = "boolean" } } }, - ["property7"] = new OpenApiSchema + ["property7"] = new() { Type = "string", MinLength = 2 @@ -83,49 +82,49 @@ public class OpenApiSchemaTests }, }, Nullable = true, - ExternalDocs = new OpenApiExternalDocs + ExternalDocs = new() { - Url = new Uri("http://example.com/externalDocs") + Url = new("http://example.com/externalDocs") } }; - public static OpenApiSchema AdvancedSchemaWithAllOf = new OpenApiSchema + public static OpenApiSchema AdvancedSchemaWithAllOf = new() { Title = "title1", AllOf = new List { - new OpenApiSchema + new() { Title = "title2", Properties = new Dictionary { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "integer" }, - ["property2"] = new OpenApiSchema + ["property2"] = new() { Type = "string", MaxLength = 15 } }, }, - new OpenApiSchema + new() { Title = "title3", Properties = new Dictionary { - ["property3"] = new OpenApiSchema + ["property3"] = new() { Properties = new Dictionary { - ["property4"] = new OpenApiSchema + ["property4"] = new() { Type = "boolean" } } }, - ["property5"] = new OpenApiSchema + ["property5"] = new() { Type = "string", MinLength = 2 @@ -135,13 +134,13 @@ public class OpenApiSchemaTests }, }, Nullable = true, - ExternalDocs = new OpenApiExternalDocs + ExternalDocs = new() { - Url = new Uri("http://example.com/externalDocs") + Url = new("http://example.com/externalDocs") } }; - public static OpenApiSchema ReferencedSchema = new OpenApiSchema + public static OpenApiSchema ReferencedSchema = new() { Title = "title1", MultipleOf = 3, @@ -152,34 +151,34 @@ public class OpenApiSchemaTests Type = "integer", Nullable = true, - ExternalDocs = new OpenApiExternalDocs + ExternalDocs = new() { - Url = new Uri("http://example.com/externalDocs") + Url = new("http://example.com/externalDocs") }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "schemaObject1" } }; - public static OpenApiSchema AdvancedSchemaWithRequiredPropertiesObject = new OpenApiSchema + public static OpenApiSchema AdvancedSchemaWithRequiredPropertiesObject = new() { Title = "title1", Required = new HashSet { "property1" }, Properties = new Dictionary { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Required = new HashSet { "property3" }, Properties = new Dictionary { - ["property2"] = new OpenApiSchema + ["property2"] = new() { Type = "integer" }, - ["property3"] = new OpenApiSchema + ["property3"] = new() { Type = "string", MaxLength = 15, @@ -188,21 +187,21 @@ public class OpenApiSchemaTests }, ReadOnly = true, }, - ["property4"] = new OpenApiSchema + ["property4"] = new() { Properties = new Dictionary { - ["property5"] = new OpenApiSchema + ["property5"] = new() { Properties = new Dictionary { - ["property6"] = new OpenApiSchema + ["property6"] = new() { Type = "boolean" } } }, - ["property7"] = new OpenApiSchema + ["property7"] = new() { Type = "string", MinLength = 2 @@ -212,9 +211,9 @@ public class OpenApiSchemaTests }, }, Nullable = true, - ExternalDocs = new OpenApiExternalDocs + ExternalDocs = new() { - Url = new Uri("http://example.com/externalDocs") + Url = new("http://example.com/externalDocs") } }; @@ -377,7 +376,7 @@ public async Task SerializeReferencedSchemaAsV3WithoutReferenceJsonWorksAsync(bo { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedSchema.SerializeAsV3WithoutReference(writer); @@ -394,7 +393,7 @@ public async Task SerializeReferencedSchemaAsV3JsonWorksAsync(bool produceTerseO { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedSchema.SerializeAsV3(writer); @@ -411,7 +410,7 @@ public async Task SerializeSchemaWRequiredPropertiesAsV2JsonWorksAsync(bool prod { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedSchemaWithRequiredPropertiesObject.SerializeAsV2(writer); @@ -429,17 +428,17 @@ public void SerializeAsV2ShouldSetFormatPropertyInParentSchemaIfPresentInChildre { OneOf = new List { - new OpenApiSchema + new() { Type = "number", Format = "decimal" }, - new OpenApiSchema { Type = "string" }, + new() { Type = "string" }, } }; var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var openApiJsonWriter = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = false }); + var openApiJsonWriter = new OpenApiJsonWriter(outputStringWriter, new() { Terse = false }); // Act // Serialize as V2 diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs index bc7e4b8a1..36ead6e72 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecurityRequirementTests.cs @@ -13,15 +13,15 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiSecurityRequirementTests { - public static OpenApiSecurityRequirement BasicSecurityRequirement = new OpenApiSecurityRequirement(); + public static OpenApiSecurityRequirement BasicSecurityRequirement = new(); public static OpenApiSecurityRequirement SecurityRequirementWithReferencedSecurityScheme = - new OpenApiSecurityRequirement + new() { [ - new OpenApiSecurityScheme + new() { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "scheme1" } + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "scheme1" } } ] = new List { @@ -30,9 +30,9 @@ public class OpenApiSecurityRequirementTests "scope3", }, [ - new OpenApiSecurityScheme + new() { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "scheme2" } + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "scheme2" } } ] = new List { @@ -40,20 +40,20 @@ public class OpenApiSecurityRequirementTests "scope5", }, [ - new OpenApiSecurityScheme + new() { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "scheme3" } + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "scheme3" } } ] = new List() }; public static OpenApiSecurityRequirement SecurityRequirementWithUnreferencedSecurityScheme = - new OpenApiSecurityRequirement + new() { [ - new OpenApiSecurityScheme + new() { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "scheme1" } + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "scheme1" } } ] = new List { @@ -62,7 +62,7 @@ public class OpenApiSecurityRequirementTests "scope3", }, [ - new OpenApiSecurityScheme + new() { // This security scheme is unreferenced, so this key value pair cannot be serialized. Name = "brokenUnreferencedScheme" @@ -73,9 +73,9 @@ public class OpenApiSecurityRequirementTests "scope5", }, [ - new OpenApiSecurityScheme + new() { - Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "scheme3" } + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "scheme3" } } ] = new List() }; @@ -219,7 +219,7 @@ public void SchemesShouldConsiderOnlyReferenceIdForEquality() Type = SecuritySchemeType.ApiKey, Name = "apiKeyName1", In = ParameterLocation.Header, - Reference = new OpenApiReference + Reference = new() { Id = "securityScheme1", Type = ReferenceType.SecurityScheme @@ -229,8 +229,8 @@ public void SchemesShouldConsiderOnlyReferenceIdForEquality() var securityScheme2 = new OpenApiSecurityScheme { Type = SecuritySchemeType.OpenIdConnect, - OpenIdConnectUrl = new Uri("http://example.com"), - Reference = new OpenApiReference + OpenIdConnectUrl = new("http://example.com"), + Reference = new() { Id = "securityScheme2", Type = ReferenceType.SecurityScheme @@ -242,7 +242,7 @@ public void SchemesShouldConsiderOnlyReferenceIdForEquality() Type = SecuritySchemeType.ApiKey, Name = "apiKeyName1", In = ParameterLocation.Header, - Reference = new OpenApiReference + Reference = new() { Id = "securityScheme1", Type = ReferenceType.SecurityScheme @@ -254,7 +254,7 @@ public void SchemesShouldConsiderOnlyReferenceIdForEquality() Type = SecuritySchemeType.ApiKey, Name = "apiKeyName2", In = ParameterLocation.Query, - Reference = new OpenApiReference + Reference = new() { Id = "securityScheme1", Type = ReferenceType.SecurityScheme diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs index 6b93fab24..5cc4a19cb 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSecuritySchemeTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using System.Globalization; using System.IO; @@ -19,7 +18,7 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiSecuritySchemeTests { - public static OpenApiSecurityScheme ApiKeySecurityScheme = new OpenApiSecurityScheme + public static OpenApiSecurityScheme ApiKeySecurityScheme = new() { Description = "description1", Name = "parameterName", @@ -27,14 +26,14 @@ public class OpenApiSecuritySchemeTests In = ParameterLocation.Query, }; - public static OpenApiSecurityScheme HttpBasicSecurityScheme = new OpenApiSecurityScheme + public static OpenApiSecurityScheme HttpBasicSecurityScheme = new() { Description = "description1", Type = SecuritySchemeType.Http, Scheme = OpenApiConstants.Basic }; - public static OpenApiSecurityScheme HttpBearerSecurityScheme = new OpenApiSecurityScheme + public static OpenApiSecurityScheme HttpBearerSecurityScheme = new() { Description = "description1", Type = SecuritySchemeType.Http, @@ -42,77 +41,77 @@ public class OpenApiSecuritySchemeTests BearerFormat = OpenApiConstants.Jwt }; - public static OpenApiSecurityScheme OAuth2SingleFlowSecurityScheme = new OpenApiSecurityScheme + public static OpenApiSecurityScheme OAuth2SingleFlowSecurityScheme = new() { Description = "description1", Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { Scopes = new Dictionary { ["operation1:object1"] = "operation 1 on object 1", ["operation2:object2"] = "operation 2 on object 2" }, - AuthorizationUrl = new Uri("https://example.com/api/oauth") + AuthorizationUrl = new("https://example.com/api/oauth") } } }; - public static OpenApiSecurityScheme OAuth2MultipleFlowSecurityScheme = new OpenApiSecurityScheme + public static OpenApiSecurityScheme OAuth2MultipleFlowSecurityScheme = new() { Description = "description1", Type = SecuritySchemeType.OAuth2, - Flows = new OpenApiOAuthFlows + Flows = new() { - Implicit = new OpenApiOAuthFlow + Implicit = new() { Scopes = new Dictionary { ["operation1:object1"] = "operation 1 on object 1", ["operation2:object2"] = "operation 2 on object 2" }, - AuthorizationUrl = new Uri("https://example.com/api/oauth") + AuthorizationUrl = new("https://example.com/api/oauth") }, - ClientCredentials = new OpenApiOAuthFlow + ClientCredentials = new() { Scopes = new Dictionary { ["operation1:object1"] = "operation 1 on object 1", ["operation2:object2"] = "operation 2 on object 2" }, - TokenUrl = new Uri("https://example.com/api/token"), - RefreshUrl = new Uri("https://example.com/api/refresh"), + TokenUrl = new("https://example.com/api/token"), + RefreshUrl = new("https://example.com/api/refresh"), }, - AuthorizationCode = new OpenApiOAuthFlow + AuthorizationCode = new() { Scopes = new Dictionary { ["operation1:object1"] = "operation 1 on object 1", ["operation2:object2"] = "operation 2 on object 2" }, - TokenUrl = new Uri("https://example.com/api/token"), - AuthorizationUrl = new Uri("https://example.com/api/oauth"), + TokenUrl = new("https://example.com/api/token"), + AuthorizationUrl = new("https://example.com/api/oauth"), } } }; - public static OpenApiSecurityScheme OpenIdConnectSecurityScheme = new OpenApiSecurityScheme + public static OpenApiSecurityScheme OpenIdConnectSecurityScheme = new() { Description = "description1", Type = SecuritySchemeType.OpenIdConnect, Scheme = OpenApiConstants.Bearer, - OpenIdConnectUrl = new Uri("https://example.com/openIdConnect") + OpenIdConnectUrl = new("https://example.com/openIdConnect") }; - public static OpenApiSecurityScheme ReferencedSecurityScheme = new OpenApiSecurityScheme + public static OpenApiSecurityScheme ReferencedSecurityScheme = new() { Description = "description1", Type = SecuritySchemeType.OpenIdConnect, Scheme = OpenApiConstants.Bearer, - OpenIdConnectUrl = new Uri("https://example.com/openIdConnect"), - Reference = new OpenApiReference + OpenIdConnectUrl = new("https://example.com/openIdConnect"), + Reference = new() { Type = ReferenceType.SecurityScheme, Id = "sampleSecurityScheme" @@ -313,7 +312,7 @@ public async Task SerializeReferencedSecuritySchemeAsV3JsonWorksAsync(bool produ { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act // Add dummy start object, value, and end object to allow SerializeAsV3 to output security scheme @@ -335,7 +334,7 @@ public async Task SerializeReferencedSecuritySchemeAsV3JsonWithoutReferenceWorks { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedSecurityScheme.SerializeAsV3WithoutReference(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs index 8e425f897..19fc00aeb 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerTests.cs @@ -12,34 +12,34 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiServerTests { - public static OpenApiServer BasicServer = new OpenApiServer + public static OpenApiServer BasicServer = new() { Description = "description1", Url = "https://example.com/server1" }; - public static OpenApiServer AdvancedServer = new OpenApiServer + public static OpenApiServer AdvancedServer = new() { Description = "description1", Url = "https://{username}.example.com:{port}/{basePath}", Variables = new Dictionary { - ["username"] = new OpenApiServerVariable + ["username"] = new() { Default = "unknown", Description = "variableDescription1", }, - ["port"] = new OpenApiServerVariable + ["port"] = new() { Default = "8443", Description = "variableDescription2", - Enum = new List + Enum = new() { "443", "8443" } }, - ["basePath"] = new OpenApiServerVariable + ["basePath"] = new() { Default = "v1" }, diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs index 1398e2249..ca23e3b97 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiServerVariableTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; @@ -12,12 +11,12 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiServerVariableTests { - public static OpenApiServerVariable BasicServerVariable = new OpenApiServerVariable(); + public static OpenApiServerVariable BasicServerVariable = new(); - public static OpenApiServerVariable AdvancedServerVariable = new OpenApiServerVariable + public static OpenApiServerVariable AdvancedServerVariable = new() { Default = "8443", - Enum = new List + Enum = new() { "8443", "443" diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs index 9d0efd995..fa6690c94 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiTagTests.cs @@ -19,9 +19,9 @@ namespace Microsoft.OpenApi.Tests.Models [UsesVerify] public class OpenApiTagTests { - public static OpenApiTag BasicTag = new OpenApiTag(); + public static OpenApiTag BasicTag = new(); - public static OpenApiTag AdvancedTag = new OpenApiTag + public static OpenApiTag AdvancedTag = new() { Name = "pet", Description = "Pets operations", @@ -32,7 +32,7 @@ public class OpenApiTagTests } }; - public static OpenApiTag ReferencedTag = new OpenApiTag + public static OpenApiTag ReferencedTag = new() { Name = "pet", Description = "Pets operations", @@ -41,7 +41,7 @@ public class OpenApiTagTests { {"x-tag-extension", new OpenApiNull()} }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Tag, Id = "pet" @@ -55,7 +55,7 @@ public async Task SerializeBasicTagAsV3JsonWithoutReferenceWorksAsync(bool produ { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act BasicTag.SerializeAsV3WithoutReference(writer); @@ -72,7 +72,7 @@ public async Task SerializeBasicTagAsV2JsonWithoutReferenceWorksAsync(bool produ { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act BasicTag.SerializeAsV2WithoutReference(writer); @@ -126,7 +126,7 @@ public async Task SerializeAdvancedTagAsV3JsonWithoutReferenceWorksAsync(bool pr { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedTag.SerializeAsV3WithoutReference(writer); @@ -143,7 +143,7 @@ public async Task SerializeAdvancedTagAsV2JsonWithoutReferenceWorksAsync(bool pr { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedTag.SerializeAsV2WithoutReference(writer); @@ -214,7 +214,7 @@ public async Task SerializeAdvancedTagAsV3JsonWorksAsync(bool produceTerseOutput { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedTag.SerializeAsV3(writer); @@ -231,7 +231,7 @@ public async Task SerializeAdvancedTagAsV2JsonWorksAsync(bool produceTerseOutput { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act AdvancedTag.SerializeAsV2(writer); @@ -288,7 +288,7 @@ public async Task SerializeReferencedTagAsV3JsonWorksAsync(bool produceTerseOutp { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedTag.SerializeAsV3(writer); @@ -305,7 +305,7 @@ public async Task SerializeReferencedTagAsV2JsonWorksAsync(bool produceTerseOutp { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act ReferencedTag.SerializeAsV2(writer); diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs index 975a0390b..92562ac18 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiXmlTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. -using System; using System.Collections.Generic; using FluentAssertions; using Microsoft.OpenApi.Any; @@ -15,10 +14,10 @@ namespace Microsoft.OpenApi.Tests.Models [Collection("DefaultSettings")] public class OpenApiXmlTests { - public static OpenApiXml AdvancedXml = new OpenApiXml + public static OpenApiXml AdvancedXml = new() { Name = "animal", - Namespace = new Uri("http://swagger.io/schema/sample"), + Namespace = new("http://swagger.io/schema/sample"), Prefix = "sample", Wrapped = true, Attribute = true, @@ -28,7 +27,7 @@ public class OpenApiXmlTests } }; - public static OpenApiXml BasicXml = new OpenApiXml(); + public static OpenApiXml BasicXml = new(); [Theory] [InlineData(OpenApiSpecVersion.OpenApi3_0, OpenApiFormat.Json)] diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs index 8bb4901a0..deb8e30be 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApiTests.cs @@ -26,7 +26,7 @@ public void ReviewPublicApiChanges() // It takes a human to read the change, determine if it is breaking and update the PublicApi.approved.txt with the new approved API surface // Arrange - var publicApi = typeof(OpenApiSpecVersion).Assembly.GeneratePublicApi(new ApiGeneratorOptions { AllowNamespacePrefixes = new[] { "Microsoft.OpenApi" } } ); + var publicApi = typeof(OpenApiSpecVersion).Assembly.GeneratePublicApi(new() { AllowNamespacePrefixes = new[] { "Microsoft.OpenApi" } } ); // Act var approvedFilePath = Path.Combine("PublicApi", "PublicApi.approved.txt"); diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index 0110cadf0..94a5556f3 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -15,42 +15,42 @@ namespace Microsoft.OpenApi.Tests.Services [UsesVerify] public class OpenApiUrlTreeNodeTests { - private OpenApiDocument OpenApiDocumentSample_1 => new OpenApiDocument + private OpenApiDocument OpenApiDocumentSample_1 => new() { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation(), + [OperationType.Get] = new(), } }, - ["/houses"] = new OpenApiPathItem + ["/houses"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation(), - [OperationType.Post] = new OpenApiOperation() + [OperationType.Get] = new(), + [OperationType.Post] = new() } }, - ["/cars"] = new OpenApiPathItem + ["/cars"] = new() { Operations = new Dictionary { - [OperationType.Post] = new OpenApiOperation() + [OperationType.Post] = new() } } } }; - private OpenApiDocument OpenApiDocumentSample_2 => new OpenApiDocument + private OpenApiDocument OpenApiDocumentSample_2 => new() { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem(), - ["/hotels"] = new OpenApiPathItem(), - ["/offices"] = new OpenApiPathItem() + ["/"] = new(), + ["/hotels"] = new(), + ["/offices"] = new() } }; @@ -67,9 +67,9 @@ public void CreateSingleRootWorks() { var doc = new OpenApiDocument { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem() + ["/"] = new() } }; @@ -87,9 +87,9 @@ public void CreatePathWithoutRootWorks() { var doc = new OpenApiDocument { - Paths = new OpenApiPaths + Paths = new() { - ["/houses"] = new OpenApiPathItem() + ["/houses"] = new() } }; @@ -155,10 +155,10 @@ public void AttachPathWorks() OperationType.Get, new OpenApiOperation { OperationId = "motorcycles.ListMotorcycle", - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved entities" } @@ -180,10 +180,10 @@ public void AttachPathWorks() OperationType.Get, new OpenApiOperation { OperationId = "computers.ListComputer", - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved entities" } @@ -210,11 +210,11 @@ public void CreatePathsWithMultipleSegmentsWorks() { var doc = new OpenApiDocument { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem(), - ["/houses/apartments/{apartment-id}"] = new OpenApiPathItem(), - ["/cars/coupes"] = new OpenApiPathItem() + ["/"] = new(), + ["/houses/apartments/{apartment-id}"] = new(), + ["/cars/coupes"] = new() } }; @@ -235,11 +235,11 @@ public void HasOperationsWorks() { var doc1 = new OpenApiDocument { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem(), - ["/houses"] = new OpenApiPathItem(), - ["/cars/{car-id}"] = new OpenApiPathItem + ["/"] = new(), + ["/houses"] = new(), + ["/cars/{car-id}"] = new() { Operations = new Dictionary { @@ -247,10 +247,10 @@ public void HasOperationsWorks() OperationType.Get, new OpenApiOperation { OperationId = "cars.GetCar", - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved entity" } @@ -265,9 +265,9 @@ public void HasOperationsWorks() var doc2 = new OpenApiDocument { - Paths = new OpenApiPaths + Paths = new() { - ["/cars/{car-id}"] = new OpenApiPathItem + ["/cars/{car-id}"] = new() { Operations = new Dictionary { @@ -275,10 +275,10 @@ public void HasOperationsWorks() OperationType.Get, new OpenApiOperation { OperationId = "cars.GetCar", - Responses = new OpenApiResponses + Responses = new() { { - "200", new OpenApiResponse + "200", new() { Description = "Retrieved entity" } @@ -290,10 +290,10 @@ public void HasOperationsWorks() OperationType.Put, new OpenApiOperation { OperationId = "cars.UpdateCar", - Responses = new OpenApiResponses + Responses = new() { { - "204", new OpenApiResponse + "204", new() { Description = "Success." } @@ -329,10 +329,10 @@ public void SegmentIsParameterWorks() { var doc = new OpenApiDocument { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem(), - ["/houses/apartments/{apartment-id}"] = new OpenApiPathItem() + ["/"] = new(), + ["/houses/apartments/{apartment-id}"] = new() } }; diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs index 5aa96ba16..02eba9347 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiValidatorTests.cs @@ -22,23 +22,23 @@ public class OpenApiValidatorTests public void ResponseMustHaveADescription() { var openApiDocument = new OpenApiDocument(); - openApiDocument.Info = new OpenApiInfo + openApiDocument.Info = new() { Title = "foo", Version = "1.2.2" }; - openApiDocument.Paths = new OpenApiPaths(); + openApiDocument.Paths = new(); openApiDocument.Paths.Add( "/test", - new OpenApiPathItem + new() { Operations = { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Responses = { - ["200"] = new OpenApiResponse() + ["200"] = new() } } } @@ -61,21 +61,21 @@ public void ServersShouldBeReferencedByIndex() { var openApiDocument = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "foo", Version = "1.2.2" }, Servers = new List { - new OpenApiServer + new() { Url = "http://example.org" }, - new OpenApiServer + new() { }, }, - Paths = new OpenApiPaths() + Paths = new() }; var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet()); @@ -101,18 +101,18 @@ public void ValidateCustomExtension() { if (item.Bar == "hey") { - context.AddError(new OpenApiValidatorError("FooExtensionRule", context.PathString, "Don't say hey")); + context.AddError(new("FooExtensionRule", context.PathString, "Don't say hey")); } })); var openApiDocument = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "foo", Version = "1.2.2" }, - Paths = new OpenApiPaths() + Paths = new() }; var fooExtension = new FooExtension diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs index cca17e011..b051c1a22 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiHeaderValidationTests.cs @@ -23,7 +23,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() { Required = true, Example = new OpenApiInteger(55), - Schema = new OpenApiSchema + Schema = new() { Type = "string", } @@ -59,21 +59,21 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() var header = new OpenApiHeader { Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "integer", } }, Examples = { - ["example0"] = new OpenApiExample + ["example0"] = new() { Value = new OpenApiString("1"), }, - ["example1"] = new OpenApiExample + ["example1"] = new() { Value = new OpenApiObject { @@ -82,7 +82,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() ["z"] = new OpenApiString("200") } }, - ["example2"] = new OpenApiExample + ["example2"] = new() { Value = new OpenApiArray @@ -90,7 +90,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() new OpenApiInteger(3) } }, - ["example3"] = new OpenApiExample + ["example3"] = new() { Value = new OpenApiObject { diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs index 48ddcce4d..d33cb02da 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiMediaTypeValidationTests.cs @@ -22,7 +22,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() var mediaType = new OpenApiMediaType { Example = new OpenApiInteger(55), - Schema = new OpenApiSchema + Schema = new() { Type = "string", } @@ -57,21 +57,21 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() var mediaType = new OpenApiMediaType { - Schema = new OpenApiSchema + Schema = new() { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "integer", } }, Examples = { - ["example0"] = new OpenApiExample + ["example0"] = new() { Value = new OpenApiString("1"), }, - ["example1"] = new OpenApiExample + ["example1"] = new() { Value = new OpenApiObject { @@ -80,7 +80,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() ["z"] = new OpenApiString("200") } }, - ["example2"] = new OpenApiExample + ["example2"] = new() { Value = new OpenApiArray @@ -88,7 +88,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() new OpenApiInteger(3) } }, - ["example3"] = new OpenApiExample + ["example3"] = new() { Value = new OpenApiObject { diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs index 1a3b5442b..27ea80c48 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiParameterValidationTests.cs @@ -72,7 +72,7 @@ public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema() In = ParameterLocation.Path, Required = true, Example = new OpenApiInteger(55), - Schema = new OpenApiSchema + Schema = new() { Type = "string", } @@ -110,21 +110,21 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() Name = "parameter1", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "integer", } }, Examples = { - ["example0"] = new OpenApiExample + ["example0"] = new() { Value = new OpenApiString("1"), }, - ["example1"] = new OpenApiExample + ["example1"] = new() { Value = new OpenApiObject { @@ -133,7 +133,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() ["z"] = new OpenApiString("200") } }, - ["example2"] = new OpenApiExample + ["example2"] = new() { Value = new OpenApiArray @@ -141,7 +141,7 @@ public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema() new OpenApiInteger(3) } }, - ["example3"] = new OpenApiExample + ["example3"] = new() { Value = new OpenApiObject { @@ -190,7 +190,7 @@ public void PathParameterNotInThePathShouldReturnAnError() Name = "parameter1", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string", } @@ -228,7 +228,7 @@ public void PathParameterInThePathShouldBeOk() Name = "parameter1", In = ParameterLocation.Path, Required = true, - Schema = new OpenApiSchema + Schema = new() { Type = "string", } diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs index 61b128e5f..b145f9ab9 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs @@ -21,7 +21,7 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() var sharedSchema = new OpenApiSchema { Type = "string", - Reference = new OpenApiReference + Reference = new() { Id = "test" }, @@ -29,7 +29,7 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() }; OpenApiDocument document = new OpenApiDocument(); - document.Components = new OpenApiComponents + document.Components = new() { Schemas = new Dictionary { @@ -37,21 +37,21 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() } }; - document.Paths = new OpenApiPaths + document.Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = sharedSchema } @@ -64,7 +64,7 @@ public void ReferencedSchemaShouldOnlyBeValidatedOnce() }; // Act - var errors = document.Validate(new ValidationRuleSet { new AlwaysFailRule() }); + var errors = document.Validate(new() { new AlwaysFailRule() }); // Assert Assert.True(errors.Count() == 1); @@ -77,7 +77,7 @@ public void UnresolvedReferenceSchemaShouldNotBeValidated() var sharedSchema = new OpenApiSchema { Type = "string", - Reference = new OpenApiReference + Reference = new() { Id = "test" }, @@ -85,7 +85,7 @@ public void UnresolvedReferenceSchemaShouldNotBeValidated() }; OpenApiDocument document = new OpenApiDocument(); - document.Components = new OpenApiComponents + document.Components = new() { Schemas = new Dictionary { @@ -94,7 +94,7 @@ public void UnresolvedReferenceSchemaShouldNotBeValidated() }; // Act - var errors = document.Validate(new ValidationRuleSet { new AlwaysFailRule() }); + var errors = document.Validate(new() { new AlwaysFailRule() }); // Assert Assert.True(errors.Count() == 0); @@ -107,7 +107,7 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() var sharedSchema = new OpenApiSchema { - Reference = new OpenApiReference + Reference = new() { Id = "test" }, @@ -116,21 +116,21 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() OpenApiDocument document = new OpenApiDocument(); - document.Paths = new OpenApiPaths + document.Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = sharedSchema } @@ -143,7 +143,7 @@ public void UnresolvedSchemaReferencedShouldNotBeValidated() }; // Act - var errors = document.Validate(new ValidationRuleSet { new AlwaysFailRule() }); + var errors = document.Validate(new() { new AlwaysFailRule() }); // Assert Assert.True(errors.Count() == 0); diff --git a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs index 1760b000f..bfe3706f1 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiSchemaValidationTests.cs @@ -109,7 +109,7 @@ public void ValidateEnumShouldNotHaveDataTypeMismatchForSimpleSchema() }, }, Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "integer", } @@ -151,33 +151,33 @@ public void ValidateDefaultShouldNotHaveDataTypeMismatchForComplexSchema() Type = "object", Properties = { - ["property1"] = new OpenApiSchema + ["property1"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "integer", Format = "int64" } }, - ["property2"] = new OpenApiSchema + ["property2"] = new() { Type = "array", - Items = new OpenApiSchema + Items = new() { Type = "object", - AdditionalProperties = new OpenApiSchema + AdditionalProperties = new() { Type = "boolean" } } }, - ["property3"] = new OpenApiSchema + ["property3"] = new() { Type = "string", Format = "password" }, - ["property4"] = new OpenApiSchema + ["property4"] = new() { Type = "string" } @@ -245,8 +245,8 @@ public void ValidateSchemaRequiredFieldListMustContainThePropertySpecifiedInTheD new OpenApiSchema { Type = "object", - Discriminator = new OpenApiDiscriminator { PropertyName = "property1" }, - Reference = new OpenApiReference { Id = "schema1" } + Discriminator = new() { PropertyName = "property1" }, + Reference = new() { Id = "schema1" } } } } @@ -263,7 +263,7 @@ public void ValidateSchemaRequiredFieldListMustContainThePropertySpecifiedInTheD result.Should().BeFalse(); errors.Should().BeEquivalentTo(new List { - new OpenApiValidatorError(nameof(OpenApiSchemaRules.ValidateSchemaDiscriminator),"#/schemas/schema1/discriminator", + new(nameof(OpenApiSchemaRules.ValidateSchemaDiscriminator),"#/schemas/schema1/discriminator", string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator, "schema1", "property1")) }); @@ -282,13 +282,13 @@ public void ValidateOneOfSchemaPropertyNameContainsPropertySpecifiedInTheDiscrim new OpenApiSchema { Type = "array", - Discriminator = new OpenApiDiscriminator + Discriminator = new() { PropertyName = "type" }, OneOf = new List { - new OpenApiSchema + new() { Properties = { @@ -300,14 +300,14 @@ public void ValidateOneOfSchemaPropertyNameContainsPropertySpecifiedInTheDiscrim } } }, - Reference = new OpenApiReference + Reference = new() { Type = ReferenceType.Schema, Id = "Person" } } }, - Reference = new OpenApiReference { Id = "Person" } + Reference = new() { Id = "Person" } } } } diff --git a/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs b/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs index 6a8286c1d..a4c73e4b1 100644 --- a/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Visitors/InheritanceTests.cs @@ -66,7 +66,7 @@ public void ExpectedVirtualsInvolved() internal protected class TestVisitor : OpenApiVisitorBase { - public Stack CallStack { get; } = new Stack(); + public Stack CallStack { get; } = new(); private string EncodeCall([CallerMemberName] string name = "", [CallerLineNumber] int lineNumber = 0) { diff --git a/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs b/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs index 71b84bf16..09c808a1e 100644 --- a/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Walkers/WalkerLocationTests.cs @@ -35,13 +35,13 @@ public void LocateTopLevelArrayItems() { Servers = new List { - new OpenApiServer(), - new OpenApiServer() + new(), + new() }, - Paths = new OpenApiPaths(), + Paths = new(), Tags = new List { - new OpenApiTag() + new() } }; @@ -64,23 +64,23 @@ public void LocatePathOperationContentSchema() { var doc = new OpenApiDocument { - Paths = new OpenApiPaths() + Paths = new() }; - doc.Paths.Add("/test", new OpenApiPathItem + doc.Paths.Add("/test", new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { Type = "string" } @@ -122,7 +122,7 @@ public void WalkDOMWithCycles() Type = "object", Properties = new Dictionary { - ["name"] = new OpenApiSchema { Type = "string" } + ["name"] = new() { Type = "string" } } }; @@ -130,8 +130,8 @@ public void WalkDOMWithCycles() var doc = new OpenApiDocument { - Paths = new OpenApiPaths(), - Components = new OpenApiComponents + Paths = new(), + Components = new() { Schemas = new Dictionary { @@ -162,7 +162,7 @@ public void LocateReferences() { var baseSchema = new OpenApiSchema { - Reference = new OpenApiReference + Reference = new() { Id = "base", Type = ReferenceType.Schema @@ -173,7 +173,7 @@ public void LocateReferences() var derivedSchema = new OpenApiSchema { AnyOf = new List { baseSchema }, - Reference = new OpenApiReference + Reference = new() { Id = "derived", Type = ReferenceType.Schema @@ -184,7 +184,7 @@ public void LocateReferences() var testHeader = new OpenApiHeader { Schema = derivedSchema, - Reference = new OpenApiReference + Reference = new() { Id = "test-header", Type = ReferenceType.Header @@ -194,21 +194,21 @@ public void LocateReferences() var doc = new OpenApiDocument { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = derivedSchema } @@ -223,7 +223,7 @@ public void LocateReferences() } } }, - Components = new OpenApiComponents + Components = new() { Schemas = new Dictionary { @@ -252,8 +252,8 @@ public void LocateReferences() internal class LocatorVisitor : OpenApiVisitorBase { - public List Locations = new List(); - public List Keys = new List(); + public List Locations = new(); + public List Keys = new(); public override void Visit(OpenApiInfo info) { diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs index c3b49e5f7..6e615bd26 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiReferencableTests.cs @@ -14,27 +14,27 @@ namespace Microsoft.OpenApi.Tests.Workspaces { public class OpenApiReferencableTests { - private static readonly OpenApiCallback _callbackFragment = new OpenApiCallback(); - private static readonly OpenApiExample _exampleFragment = new OpenApiExample(); - private static readonly OpenApiLink _linkFragment = new OpenApiLink(); - private static readonly OpenApiHeader _headerFragment = new OpenApiHeader + private static readonly OpenApiCallback _callbackFragment = new(); + private static readonly OpenApiExample _exampleFragment = new(); + private static readonly OpenApiLink _linkFragment = new(); + private static readonly OpenApiHeader _headerFragment = new() { - Schema = new OpenApiSchema(), + Schema = new(), Examples = new Dictionary { { "example1", new OpenApiExample() } } }; - private static readonly OpenApiParameter _parameterFragment = new OpenApiParameter + private static readonly OpenApiParameter _parameterFragment = new() { - Schema = new OpenApiSchema(), + Schema = new(), Examples = new Dictionary { { "example1", new OpenApiExample() } } }; - private static readonly OpenApiRequestBody _requestBodyFragment = new OpenApiRequestBody(); - private static readonly OpenApiResponse _responseFragment = new OpenApiResponse + private static readonly OpenApiRequestBody _requestBodyFragment = new(); + private static readonly OpenApiResponse _responseFragment = new() { Headers = new Dictionary { @@ -45,9 +45,9 @@ public class OpenApiReferencableTests { "link1", new OpenApiLink() } } }; - private static readonly OpenApiSchema _schemaFragment = new OpenApiSchema(); - private static readonly OpenApiSecurityScheme _securitySchemeFragment = new OpenApiSecurityScheme(); - private static readonly OpenApiTag _tagFragment = new OpenApiTag(); + private static readonly OpenApiSchema _schemaFragment = new(); + private static readonly OpenApiSecurityScheme _securitySchemeFragment = new(); + private static readonly OpenApiTag _tagFragment = new(); public static IEnumerable ResolveReferenceCanResolveValidJsonPointersTestData => new List @@ -78,7 +78,7 @@ public void ResolveReferenceCanResolveValidJsonPointers( IOpenApiElement expectedResolvedElement) { // Act - var actualResolvedElement = element.ResolveReference(new JsonPointer(jsonPointer)); + var actualResolvedElement = element.ResolveReference(new(jsonPointer)); // Assert Assert.Same(expectedResolvedElement, actualResolvedElement); @@ -110,7 +110,7 @@ public void ResolveReferenceCanResolveValidJsonPointers( public void ResolveReferenceShouldThrowOnInvalidReferenceId(IOpenApiReferenceable element, string jsonPointer) { // Act - Action resolveReference = () => element.ResolveReference(new JsonPointer(jsonPointer)); + Action resolveReference = () => element.ResolveReference(new(jsonPointer)); // Assert var exception = Assert.Throws(resolveReference); diff --git a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs index deb372016..f86295f35 100644 --- a/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs +++ b/test/Microsoft.OpenApi.Tests/Workspaces/OpenApiWorkspaceTests.cs @@ -17,8 +17,8 @@ public void OpenApiWorkspaceCanHoldMultipleDocuments() { var workspace = new OpenApiWorkspace(); - workspace.AddDocument("root", new OpenApiDocument()); - workspace.AddDocument("common", new OpenApiDocument()); + workspace.AddDocument("root", new()); + workspace.AddDocument("common", new()); Assert.Equal(2, workspace.Documents.Count()); } @@ -28,27 +28,27 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther() { var workspace = new OpenApiWorkspace(); - workspace.AddDocument("root", new OpenApiDocument + workspace.AddDocument("root", new() { - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = new Dictionary { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { - Responses = new OpenApiResponses + Responses = new() { - ["200"] = new OpenApiResponse + ["200"] = new() { Content = new Dictionary { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { - Schema = new OpenApiSchema + Schema = new() { - Reference = new OpenApiReference + Reference = new() { Id = "test", Type = ReferenceType.Schema @@ -63,12 +63,12 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther() } } }); - workspace.AddDocument("common", new OpenApiDocument + workspace.AddDocument("common", new() { - Components = new OpenApiComponents + Components = new() { Schemas = { - ["test"] = new OpenApiSchema + ["test"] = new() { Type = "string", Description = "The referenced one" @@ -84,7 +84,7 @@ public void OpenApiWorkspacesCanResolveExternalReferences() { var workspace = new OpenApiWorkspace(); workspace.AddDocument("common", CreateCommonDocument()); - var schema = workspace.ResolveReference(new OpenApiReference {Id = "test", Type = ReferenceType.Schema, ExternalResource = "common"}) as OpenApiSchema; + var schema = workspace.ResolveReference(new() {Id = "test", Type = ReferenceType.Schema, ExternalResource = "common"}) as OpenApiSchema; Assert.NotNull(schema); Assert.Equal("The referenced one", schema.Description); @@ -104,9 +104,9 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther_short() { re.Description = "Success"; re.CreateContent("application/json", co => - co.Schema = new OpenApiSchema + co.Schema = new() { - Reference = new OpenApiReference() // Reference + Reference = new() // Reference { Id = "test", Type = ReferenceType.Schema, ExternalResource = "common" }, @@ -131,8 +131,8 @@ public void OpenApiWorkspacesAllowDocumentsToReferenceEachOther_short() public void OpenApiWorkspacesShouldNormalizeDocumentLocations() { var workspace = new OpenApiWorkspace(); - workspace.AddDocument("hello", new OpenApiDocument()); - workspace.AddDocument("hi", new OpenApiDocument()); + workspace.AddDocument("hello", new()); + workspace.AddDocument("hi", new()); Assert.True(workspace.Contains("./hello")); Assert.True(workspace.Contains("./foo/../hello")); @@ -158,7 +158,7 @@ public void OpenApiWorkspacesCanResolveReferencesToDocumentFragments() workspace.AddFragment("fragment", schemaFragment); // Act - var schema = workspace.ResolveReference(new OpenApiReference {ExternalResource = "fragment"}) as OpenApiSchema; + var schema = workspace.ResolveReference(new() {ExternalResource = "fragment"}) as OpenApiSchema; // Assert Assert.NotNull(schema); @@ -180,7 +180,7 @@ public void OpenApiWorkspacesCanResolveReferencesToDocumentFragmentsWithJsonPoin workspace.AddFragment("fragment", responseFragment); // Act - var resolvedElement = workspace.ResolveReference(new OpenApiReference + var resolvedElement = workspace.ResolveReference(new() { Id = "headers/header1", ExternalResource = "fragment" @@ -193,12 +193,12 @@ public void OpenApiWorkspacesCanResolveReferencesToDocumentFragmentsWithJsonPoin // Test artifacts private static OpenApiDocument CreateCommonDocument() { - return new OpenApiDocument + return new() { - Components = new OpenApiComponents + Components = new() { Schemas = { - ["test"] = new OpenApiSchema + ["test"] = new() { Type = "string", Description = "The referenced one" @@ -215,7 +215,7 @@ public static OpenApiDocument CreatePathItem(this OpenApiDocument document, stri { var pathItem = new OpenApiPathItem(); config(pathItem); - document.Paths = new OpenApiPaths(); + document.Paths = new(); document.Paths.Add(path, pathItem); return document; } diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs index 72c84505c..f53beb8e3 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiJsonWriterTests.cs @@ -46,7 +46,7 @@ public void WriteStringListAsJsonShouldMatchExpected(string[] stringValues, bool { // Arrange var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputString, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputString, new() { Terse = produceTerseOutput }); // Act writer.WriteStartArray(); @@ -128,7 +128,7 @@ public static IEnumerable WriteMapAsJsonShouldMatchExpectedTestCasesCo new Dictionary { ["property1"] = new DateTime(1970, 01, 01), - ["property2"] = new DateTimeOffset(new DateTime(1970, 01, 01)), + ["property2"] = new DateTimeOffset(new(1970, 01, 01)), ["property3"] = new DateTime(2018, 04, 03), }, @@ -219,7 +219,7 @@ public void WriteMapAsJsonShouldMatchExpected(IDictionary inputM { // Arrange var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputString, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputString, new() { Terse = produceTerseOutput }); // Act WriteValueRecursive(writer, inputMap); @@ -235,8 +235,8 @@ public static IEnumerable WriteDateTimeAsJsonTestCases() { return from input in new DateTimeOffset[] { - new DateTimeOffset(2018, 1, 1, 10, 20, 30, TimeSpan.Zero), - new DateTimeOffset(2018, 1, 1, 10, 20, 30, 100, TimeSpan.FromHours(14)), + 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), DateTime.UtcNow + TimeSpan.FromDays(4), } @@ -250,7 +250,7 @@ public void WriteDateTimeAsJsonShouldMatchExpected(DateTimeOffset dateTimeOffset { // Arrange var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputString, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputString, new() { Terse = produceTerseOutput }); // Act writer.WriteValue(dateTimeOffset); diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs index 6e6ab8ba3..7c378c16f 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs @@ -265,7 +265,7 @@ private static string WriteAsJson(IOpenApiAny any, bool produceTerseOutput = fal var stream = new MemoryStream(); IOpenApiWriter writer = new OpenApiJsonWriter( new StreamWriter(stream), - new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + new() { Terse = produceTerseOutput }); writer.WriteAny(any); writer.Flush(); diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs index 64ccdac64..5e738ecc6 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs @@ -43,7 +43,7 @@ public void WriteStringWithSpecialCharactersAsJsonWorks(string input, string exp { // Arrange var outputStringWriter = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiJsonWriter(outputStringWriter, new OpenApiJsonWriterSettings { Terse = produceTerseOutput }); + var writer = new OpenApiJsonWriter(outputStringWriter, new() { Terse = produceTerseOutput }); // Act writer.WriteValue(input); diff --git a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs index 2bd5bab5e..74e6a7d27 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiYamlWriterTests.cs @@ -385,7 +385,7 @@ public void WriteInlineSchema() """; var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true } ); + var writer = new OpenApiYamlWriter(outputString, new() { InlineLocalReferences = true } ); // Act doc.SerializeAsV3(writer); @@ -421,7 +421,7 @@ public void WriteInlineSchemaV2() """; var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true }); + var writer = new OpenApiYamlWriter(outputString, new() { InlineLocalReferences = true }); // Act doc.SerializeAsV2(writer); @@ -440,7 +440,7 @@ private static OpenApiDocument CreateDocWithSimpleSchemaToInline() { Type = "object", UnresolvedReference = false, - Reference = new OpenApiReference + Reference = new() { Id = "thing", Type = ReferenceType.Schema @@ -449,23 +449,24 @@ private static OpenApiDocument CreateDocWithSimpleSchemaToInline() var doc = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Demo", Version = "1.0.0" }, - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Responses = { - ["200"] = new OpenApiResponse { + ["200"] = new() + { Description = "OK", Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = thingSchema } @@ -476,7 +477,7 @@ private static OpenApiDocument CreateDocWithSimpleSchemaToInline() } } }, - Components = new OpenApiComponents + Components = new() { Schemas = { ["thing"] = thingSchema} @@ -533,7 +534,7 @@ public void WriteInlineRecursiveSchema() // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true }); + var writer = new OpenApiYamlWriter(outputString, new() { InlineLocalReferences = true }); // Act doc.SerializeAsV3(writer); @@ -551,7 +552,7 @@ private static OpenApiDocument CreateDocWithRecursiveSchemaReference() { Type = "object", UnresolvedReference = false, - Reference = new OpenApiReference + Reference = new() { Id = "thing", Type = ReferenceType.Schema @@ -568,23 +569,24 @@ private static OpenApiDocument CreateDocWithRecursiveSchemaReference() var doc = new OpenApiDocument { - Info = new OpenApiInfo + Info = new() { Title = "Demo", Version = "1.0.0" }, - Paths = new OpenApiPaths + Paths = new() { - ["/"] = new OpenApiPathItem + ["/"] = new() { Operations = { - [OperationType.Get] = new OpenApiOperation + [OperationType.Get] = new() { Responses = { - ["200"] = new OpenApiResponse { + ["200"] = new() + { Description = "OK", Content = { - ["application/json"] = new OpenApiMediaType + ["application/json"] = new() { Schema = thingSchema } @@ -595,7 +597,7 @@ private static OpenApiDocument CreateDocWithRecursiveSchemaReference() } } }, - Components = new OpenApiComponents + Components = new() { Schemas = { ["thing"] = thingSchema} @@ -649,7 +651,7 @@ public void WriteInlineRecursiveSchemav2() // Component schemas that are there due to cycles are still inlined because the items they reference may not exist in the components because they don't have cycles. var outputString = new StringWriter(CultureInfo.InvariantCulture); - var writer = new OpenApiYamlWriter(outputString, new OpenApiWriterSettings { InlineLocalReferences = true }); + var writer = new OpenApiYamlWriter(outputString, new() { InlineLocalReferences = true }); // Act doc.SerializeAsV2(writer); From cca0dd9554a8c406ea990e447ab482369445ddbd Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 23:42:34 +1100 Subject: [PATCH 12/61] . --- test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs | 2 +- test/Microsoft.OpenApi.SmokeTests/GraphTests.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs index efc79b133..b2cd1143b 100644 --- a/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs +++ b/test/Microsoft.OpenApi.SmokeTests/ApiGurus.cs @@ -27,7 +27,7 @@ public ApisGuruTests(ITestOutputHelper output) static ApisGuruTests() { - System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; _httpClient = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip diff --git a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs index 77b4d2525..9bd1069a2 100644 --- a/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs +++ b/test/Microsoft.OpenApi.SmokeTests/GraphTests.cs @@ -19,7 +19,7 @@ public class GraphTests public GraphTests(ITestOutputHelper output) { _output = output; - System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; _httpClient = new(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip }); From d2c7aa79dcff8325fe90127b6749acb8af2e81a8 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 23:47:35 +1100 Subject: [PATCH 13/61] fix null ref in CreateSimpleList --- src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs index bfb9a554f..b8c8619db 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs @@ -45,8 +45,7 @@ public override List CreateSimpleList(Func map) { if (_nodeList == null) { - throw new OpenApiReaderException( - $"Expected list at line {_nodeList.Start.Line} while parsing {typeof(T).Name}", _nodeList); + throw new OpenApiReaderException($"Expected list while parsing {typeof(T).Name}"); } return _nodeList.Select(n => map(new(Context, n))).ToList(); From a9515118142ca51e8c885a3a51206b9617e76611 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Thu, 5 Oct 2023 23:48:39 +1100 Subject: [PATCH 14/61] fix null ref in CreateList --- src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs index bfb9a554f..3ea1dd651 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/ListNode.cs @@ -25,8 +25,7 @@ public override List CreateList(Func map) { if (_nodeList == null) { - throw new OpenApiReaderException( - $"Expected list at line {_nodeList.Start.Line} while parsing {typeof(T).Name}", _nodeList); + throw new OpenApiReaderException($"Expected list while parsing {typeof(T).Name}"); } return _nodeList.Select(n => map(new(Context, n as YamlMappingNode))) From a2784a2b17eca1a993d0e7af2478203fb11ce171 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 5 Oct 2023 21:06:50 +0000 Subject: [PATCH 15/61] Bump Verify.Xunit from 21.3.0 to 22.1.0 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 21.3.0 to 22.1.0. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/21.3.0...22.1.0) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index b073d6b8d..e69433144 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From c578c4d5f1f3904848dc438fd88dff06f6e8e022 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 20:57:00 +1100 Subject: [PATCH 16/61] csharp_style_inlined_variable_declaration as error --- .editorconfig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.editorconfig b/.editorconfig index 49de0d370..5b8c4b64e 100644 --- a/.editorconfig +++ b/.editorconfig @@ -84,7 +84,7 @@ csharp_prefer_braces = true:silent csharp_style_deconstructed_variable_declaration = true:suggestion csharp_prefer_simple_default_expression = true:suggestion csharp_style_pattern_local_over_anonymous_function = true:suggestion -csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_inlined_variable_declaration = true:error ############################### # C# Formatting Rules # ############################### From ec241cc2c7617b5e441153cfda83e1404fd68dfc Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:11:51 +1100 Subject: [PATCH 17/61] fix some dodgy indents --- src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs | 2 +- .../V2/OpenApiDocumentDeserializer.cs | 5 +++-- .../V3/OpenApiDocumentDeserializer.cs | 4 ++-- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs index c924311d7..61f609817 100644 --- a/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs +++ b/src/Microsoft.OpenApi.Readers/ParseNodes/MapNode.cs @@ -125,7 +125,7 @@ public override Dictionary CreateMapWithReference( Id = entry.key }; } - } + } finally { Context.EndObject(); diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index beba2e815..7783fdca3 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -36,13 +36,14 @@ internal static partial class OpenApiV2Deserializer }, { "consumes", - (o, n) => { + (o, n) => + { var consumes = n.CreateSimpleList(s => s.GetScalarValue()); if (consumes.Count > 0) { n.Context.SetTempStorage(TempStorageKeys.GlobalConsumes, consumes); } - } + } }, { "produces", (o, n) => { diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs index 88cd93000..a4d16a429 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiDocumentDeserializer.cs @@ -26,13 +26,13 @@ internal static partial class OpenApiV3Deserializer {"components", (o, n) => o.Components = LoadComponents(n)}, {"tags", (o, n) => {o.Tags = n.CreateList(LoadTag); foreach (var tag in o.Tags) - { + { tag.Reference = new() { Id = tag.Name, Type = ReferenceType.Tag }; - } + } } }, {"externalDocs", (o, n) => o.ExternalDocs = LoadExternalDocs(n)}, {"security", (o, n) => o.SecurityRequirements = n.CreateList(LoadSecurityRequirement)} From 122d8411a41fe15ce9cdc2289f840b0ddbdf6087 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:13:02 +1100 Subject: [PATCH 18/61] fix Fileds typo --- .../V3/OpenApiOAuthFlowDeserializer.cs | 4 ++-- .../V3/OpenApiOAuthFlowsDeserializer.cs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs index 0b5f6a3eb..16fc934a9 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowDeserializer.cs @@ -14,7 +14,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _oAuthFlowFixedFileds = + private static readonly FixedFieldMap _oAuthFlowFixedFields = new() { { @@ -51,7 +51,7 @@ public static OpenApiOAuthFlow LoadOAuthFlow(ParseNode node) var oauthFlow = new OpenApiOAuthFlow(); foreach (var property in mapNode) { - property.ParseField(oauthFlow, _oAuthFlowFixedFileds, _oAuthFlowPatternFields); + property.ParseField(oauthFlow, _oAuthFlowFixedFields, _oAuthFlowPatternFields); } return oauthFlow; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs index 9a80bed88..5423323f8 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiOAuthFlowsDeserializer.cs @@ -13,7 +13,7 @@ namespace Microsoft.OpenApi.Readers.V3 /// internal static partial class OpenApiV3Deserializer { - private static readonly FixedFieldMap _oAuthFlowsFixedFileds = + private static readonly FixedFieldMap _oAuthFlowsFixedFields = new() { {"implicit", (o, n) => o.Implicit = LoadOAuthFlow(n)}, @@ -35,7 +35,7 @@ public static OpenApiOAuthFlows LoadOAuthFlows(ParseNode node) var oAuthFlows = new OpenApiOAuthFlows(); foreach (var property in mapNode) { - property.ParseField(oAuthFlows, _oAuthFlowsFixedFileds, _oAuthFlowsPatternFields); + property.ParseField(oAuthFlows, _oAuthFlowsFixedFields, _oAuthFlowsPatternFields); } return oAuthFlows; From c59fd1ba86676bc3182767bc9db285aec586f42f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:19:01 +1100 Subject: [PATCH 19/61] fix comment typos --- src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs | 2 +- src/Microsoft.OpenApi.Readers/ParsingContext.cs | 4 ++-- src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs | 2 +- src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs | 4 ++-- src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs | 2 +- src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 2 +- src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs | 2 +- src/Microsoft.OpenApi/Services/OpenApiWalker.cs | 2 +- src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs | 2 +- src/Microsoft.OpenApi/Validations/IValidationContext.cs | 2 +- src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs | 2 +- src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs | 4 ++-- .../Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs | 2 +- test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs | 2 +- 15 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs b/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs index b3c0c4613..f69ae474a 100644 --- a/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs +++ b/src/Microsoft.OpenApi.Readers/Interface/IStreamLoader.cs @@ -17,7 +17,7 @@ public interface IStreamLoader /// Use Uri to locate data and convert into an input object. /// /// Identifier of some source of an OpenAPI Description - /// A data objext that can be processed by a reader to generate an + /// A data object that can be processed by a reader to generate an Task LoadAsync(Uri uri); /// diff --git a/src/Microsoft.OpenApi.Readers/ParsingContext.cs b/src/Microsoft.OpenApi.Readers/ParsingContext.cs index 93a7d6564..eb7459d10 100644 --- a/src/Microsoft.OpenApi.Readers/ParsingContext.cs +++ b/src/Microsoft.OpenApi.Readers/ParsingContext.cs @@ -39,7 +39,7 @@ public class ParsingContext /// /// Create Parsing Context /// - /// Provide instance for diagnotic object for collecting and accessing information about the parsing. + /// Provide instance for diagnostic object for collecting and accessing information about the parsing. public ParsingContext(OpenApiDiagnostic diagnostic) { Diagnostic = diagnostic; @@ -165,7 +165,7 @@ public T GetFromTempStorage(string key, object scope = null) } /// - /// Sets the temporary storge for this key and value. + /// Sets the temporary storage for this key and value. /// public void SetTempStorage(string key, object value, object scope = null) { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index 20490aca7..0a0495ea4 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -24,7 +24,7 @@ internal class OpenApiV2VersionService : IOpenApiVersionService /// /// Create Parsing Context /// - /// Provide instance for diagnotic object for collecting and accessing information about the parsing. + /// Provide instance for diagnostic object for collecting and accessing information about the parsing. public OpenApiV2VersionService(OpenApiDiagnostic diagnostic) { Diagnostic = diagnostic; diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 011680d3d..23bf82c7e 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -26,7 +26,7 @@ internal class OpenApiV3VersionService : IOpenApiVersionService /// /// Create Parsing Context /// - /// Provide instance for diagnotic object for collecting and accessing information about the parsing. + /// Provide instance for diagnostic object for collecting and accessing information about the parsing. public OpenApiV3VersionService(OpenApiDiagnostic diagnostic) { Diagnostic = diagnostic; @@ -68,7 +68,7 @@ public OpenApiV3VersionService(OpenApiDiagnostic diagnostic) /// Parse the string to a object. /// /// The URL of the reference - /// The type of object refefenced based on the context of the reference + /// The type of object referenced based on the context of the reference public OpenApiReference ConvertToOpenApiReference( string reference, ReferenceType? type) diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs index ad6f2c0e5..18f598e44 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiExtension.cs @@ -6,7 +6,7 @@ namespace Microsoft.OpenApi.Interfaces { /// - /// Interface requuired for implementing any custom extension + /// Interface required for implementing any custom extension /// public interface IOpenApiExtension { diff --git a/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs b/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs index 6f5b1bd09..a3b22bd08 100644 --- a/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs +++ b/src/Microsoft.OpenApi/Interfaces/IOpenApiSerializable.cs @@ -6,7 +6,7 @@ namespace Microsoft.OpenApi.Interfaces { /// - /// Represents an Open API element that comes with serialzation functionality. + /// Represents an Open API element that comes with serialization functionality. /// public interface IOpenApiSerializable : IOpenApiElement { diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index b3cea1a8d..c2fa42890 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -308,7 +308,7 @@ private static void WriteHostInfoV2(IOpenApiWriter writer, IList var serverUrl = ParseServerUrl(servers.First()); // Divide the URL in the Url property into host and basePath required in OpenAPI V2 - // The Url property cannotcontain path templating to be valid for V2 serialization. + // The Url property cannot contain path templating to be valid for V2 serialization. var firstServerUrl = new Uri(serverUrl, UriKind.RelativeOrAbsolute); // host diff --git a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs index 87dd07b81..52f2207ed 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiVisitorBase.cs @@ -31,7 +31,7 @@ public virtual void Enter(string segment) } /// - /// Exit from path context elevel. Enter and Exit calls should be matched. + /// Exit from path context level. Enter and Exit calls should be matched. /// public virtual void Exit() { diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index ddda44218..4811f647c 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -896,7 +896,7 @@ internal void Walk(IList schemas) return; } - // Visit Schemass + // Visit Schemas if (schemas != null) { for (int i = 0; i < schemas.Count; i++) diff --git a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs index dc7ae75d3..eda6e1a1d 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWorkspace.cs @@ -101,7 +101,7 @@ public void AddFragment(string location, IOpenApiReferenceable fragment) } /// - /// Add a stream based artificat to the workspace. Useful for images, examples, alternative schemas. + /// Add a stream based artifact to the workspace. Useful for images, examples, alternative schemas. /// /// /// diff --git a/src/Microsoft.OpenApi/Validations/IValidationContext.cs b/src/Microsoft.OpenApi/Validations/IValidationContext.cs index fe93b2a58..73b1fec06 100644 --- a/src/Microsoft.OpenApi/Validations/IValidationContext.cs +++ b/src/Microsoft.OpenApi/Validations/IValidationContext.cs @@ -27,7 +27,7 @@ public interface IValidationContext void Enter(string segment); /// - /// Exit from path context elevel. Enter and Exit calls should be matched. + /// Exit from path context level. Enter and Exit calls should be matched. /// void Exit(); diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs index 16958727d..5254288f3 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterBase.cs @@ -20,7 +20,7 @@ public abstract class OpenApiWriterBase : IOpenApiWriter public OpenApiWriterSettings Settings { get; set; } /// - /// The indentation string to prepand to each line for each indentation level. + /// The indentation string to prepend to each line for each indentation level. /// protected const string IndentationString = " "; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs index 8f4a866ae..a0fa62eae 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -132,7 +132,7 @@ public static void WriteProperty(this IOpenApiWriter writer, string name, T v /// The Open API writer. /// The property name. /// The property value. - /// The proprety value writer action. + /// The property value writer action. public static void WriteOptionalObject( this IOpenApiWriter writer, string name, @@ -158,7 +158,7 @@ public static void WriteOptionalObject( /// The Open API writer. /// The property name. /// The property value. - /// The proprety value writer action. + /// The property value writer action. public static void WriteRequiredObject( this IOpenApiWriter writer, string name, diff --git a/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs b/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs index a694d17b0..ed8072ba6 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/DefaultSettingsFixture.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Readers.Tests public class DefaultSettingsFixture { /// - /// Initializes an intance of . + /// Initializes an instance of . /// public DefaultSettingsFixture() { diff --git a/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs b/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs index 3a0b8aabe..d2afed0c6 100644 --- a/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs +++ b/test/Microsoft.OpenApi.Tests/DefaultSettingsFixture.cs @@ -11,7 +11,7 @@ namespace Microsoft.OpenApi.Tests public class DefaultSettingsFixture { /// - /// Initializes an intance of . + /// Initializes an instance of . /// public DefaultSettingsFixture() { From 539d1493faa906905e7b28b4c0f03dd41910ae39 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:20:45 +1100 Subject: [PATCH 20/61] . --- src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs | 2 +- src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs | 2 +- .../Validations/Rules/OpenApiMediaTypeRules.cs | 2 +- src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs | 6 +++--- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs index 620b79d3b..7be47b5ca 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiSecurityScheme.cs @@ -205,7 +205,7 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) break; case SecuritySchemeType.OAuth2: - // These properties apply to ouauth2 type only. + // These properties apply to oauth2 type only. // flow // authorizationUrl // tokenUrl diff --git a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs index e95d573b2..9ad9158ea 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiUrlTreeNode.cs @@ -242,7 +242,7 @@ public void WriteMermaid(TextWriter writer) } /// - /// Dictionary that maps a set of HTTP methods to HTML color. Keys are sorted, uppercased, concatenated HTTP methods. + /// Dictionary that maps a set of HTTP methods to HTML color. Keys are sorted, upper-cased, concatenated HTTP methods. /// public readonly static IReadOnlyDictionary MermaidNodeStyles = new Dictionary(StringComparer.OrdinalIgnoreCase) { diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs index 0e78b38de..6f7b65a6c 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiMediaTypeRules.cs @@ -12,7 +12,7 @@ namespace Microsoft.OpenApi.Validations.Rules /// Removed this in v1.3 as a default rule as the OpenAPI specification does not require that example /// values validate against the schema. Validating examples against the schema is particularly difficult /// as it requires parsing of the example using the schema as a guide. This is not possible when the schema - /// is ref'd. Even if we fix this issue, this rule should be treated as a warning, not an error + /// is referenced. Even if we fix this issue, this rule should be treated as a warning, not an error /// Future versions of the validator should make that distinction. /// Future versions of the example parsers should not try an infer types. /// Example validation should be done as a separate post reading step so all schemas can be fully available. diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index 6cc4d3a05..df1d48e35 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -38,8 +38,8 @@ public IList FindRules(Type type) /// Gets the default validation rule sets. /// /// - /// This is a method instead of a property to signal that a new default ruleset object is created - /// per call. Making this a property may be misleading callers to think the returned rulesets from multiple calls + /// This is a method instead of a property to signal that a new default rule-set object is created + /// per call. Making this a property may be misleading callers to think the returned rule-sets from multiple calls /// are the same objects. /// public static ValidationRuleSet GetDefaultRuleSet() @@ -56,7 +56,7 @@ public static ValidationRuleSet GetDefaultRuleSet() } /// - /// Return Ruleset with no rules + /// Return with no rules /// public static ValidationRuleSet GetEmptyRuleSet() { From bc0cebb104b0c90708232d87378e3e6e7c33ab86 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:24:13 +1100 Subject: [PATCH 21/61] remove duplicate dictionary lookups in ValidationRuleSet.Add --- src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index 6cc4d3a05..8a641da4e 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -123,12 +123,13 @@ public IList Rules /// The rule. public void Add(ValidationRule rule) { - if (!_rules.ContainsKey(rule.ElementType)) + if (!_rules.TryGetValue(rule.ElementType, out var item)) { - _rules[rule.ElementType] = new List(); + _rules[rule.ElementType] = new List {rule}; + return; } - if (_rules[rule.ElementType].Contains(rule)) + if (item.Contains(rule)) { throw new OpenApiException(SRResource.Validation_RuleAddTwice); } From 88bb6b995cd379cc70c17517338635d510525844 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:25:30 +1100 Subject: [PATCH 22/61] Update ValidationRuleSet.cs --- src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index 8a641da4e..f6bb84806 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -134,7 +134,7 @@ public void Add(ValidationRule rule) throw new OpenApiException(SRResource.Validation_RuleAddTwice); } - _rules[rule.ElementType].Add(rule); + item.Add(rule); } /// From 5d3073aab180e6e0c0d696b25a5b4d8e89c6753a Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:29:09 +1100 Subject: [PATCH 23/61] dont abstract type for private fields --- src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs | 2 +- src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs | 2 +- src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs index 20490aca7..823a66c3d 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiV2VersionService.cs @@ -30,7 +30,7 @@ public OpenApiV2VersionService(OpenApiDiagnostic diagnostic) Diagnostic = diagnostic; } - private IDictionary> _loaders = new Dictionary> + private Dictionary> _loaders = new() { [typeof(IOpenApiAny)] = OpenApiV2Deserializer.LoadAny, [typeof(OpenApiContact)] = OpenApiV2Deserializer.LoadContact, diff --git a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs index 011680d3d..5787a703b 100644 --- a/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs +++ b/src/Microsoft.OpenApi.Readers/V3/OpenApiV3VersionService.cs @@ -32,7 +32,7 @@ public OpenApiV3VersionService(OpenApiDiagnostic diagnostic) Diagnostic = diagnostic; } - private IDictionary> _loaders = new Dictionary> + private Dictionary> _loaders = new() { [typeof(IOpenApiAny)] = OpenApiV3Deserializer.LoadAny, [typeof(OpenApiCallback)] = OpenApiV3Deserializer.LoadCallback, diff --git a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index 6cc4d3a05..f8061ead3 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -17,11 +17,11 @@ namespace Microsoft.OpenApi.Validations /// public sealed class ValidationRuleSet : IEnumerable { - private IDictionary> _rules = new Dictionary>(); + private Dictionary> _rules = new(); private static ValidationRuleSet _defaultRuleSet; - private IList _emptyRules = new List(); + private List _emptyRules = new(); /// /// Retrieve the rules that are related to a specific type From 30bcea6ce4b5cfe3abbf11f6b51e19034c2bc8ef Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:31:42 +1100 Subject: [PATCH 24/61] remove redundant where --- .../V2/OpenApiDocumentDeserializer.cs | 6 ++++-- .../OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs | 9 +++++---- 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index beba2e815..fdb11a51d 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -323,10 +323,12 @@ public RequestBodyReferenceFixer(IDictionary request { _requestBodies = requestBodies; } + public override void Visit(OpenApiOperation operation) { - var body = operation.Parameters.Where(p => p.UnresolvedReference == true - && _requestBodies.ContainsKey(p.Reference.Id)).FirstOrDefault(); + var body = operation.Parameters.FirstOrDefault( + p => p.UnresolvedReference + && _requestBodies.ContainsKey(p.Reference.Id)); if (body != null) { diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index 8f9430a87..bc75c5071 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -75,10 +75,11 @@ public async Task LoadDocumentWithExternalReferenceShouldLoadBothDocumentsIntoWo Assert.False(referencedSchema.UnresolvedReference); var referencedParameter = result.OpenApiDocument - .Paths["/todos"] - .Operations[OperationType.Get] - .Parameters.Select(p => p.GetEffective(result.OpenApiDocument)) - .Where(p => p.Name == "filter").FirstOrDefault(); + .Paths["/todos"] + .Operations[OperationType.Get] + .Parameters + .Select(p => p.GetEffective(result.OpenApiDocument)) + .FirstOrDefault(p => p.Name == "filter"); Assert.Equal("string", referencedParameter.Schema.Type); } From efc739488d1c9c7d0f53c7be5a6ebffb646ae618 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 6 Oct 2023 21:33:24 +1100 Subject: [PATCH 25/61] use some range indexors --- .../OpenApiReaderTests/OpenApiDiagnosticTests.cs | 2 +- .../OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs | 2 +- .../Services/OpenApiUrlTreeNodeTests.cs | 8 ++++---- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs index 4d1b6675d..7f7c34b26 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiReaderTests/OpenApiDiagnosticTests.cs @@ -71,7 +71,7 @@ public Stream Load(Uri uri) public Task LoadAsync(Uri uri) { var path = new Uri(new("http://example.org/OpenApiReaderTests/Samples/OpenApiDiagnosticReportMerged/"), uri).AbsolutePath; - path = path.Substring(1); // remove leading slash + path = path[1..]; // remove leading slash return Task.FromResult(Resources.GetStream(path)); } } diff --git a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs index 8f9430a87..e1859f086 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/OpenApiWorkspaceTests/OpenApiWorkspaceStreamTests.cs @@ -108,7 +108,7 @@ public Stream Load(Uri uri) public Task LoadAsync(Uri uri) { var path = new Uri(new("http://example.org/V3Tests/Samples/OpenApiWorkspace/"), uri).AbsolutePath; - path = path.Substring(1); // remove leading slash + path = path[1..]; // remove leading slash return Task.FromResult(Resources.GetStream(path)); } } diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index 94a5556f3..c7ee7e692 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -199,10 +199,10 @@ public void AttachPathWorks() rootNode.Attach(path2, pathItem2, label2); Assert.Equal(4, rootNode.Children.Count); - Assert.True(rootNode.Children.ContainsKey(path1.Substring(1))); - Assert.True(rootNode.Children.ContainsKey(path2.Substring(1))); - Assert.True(rootNode.Children[path1.Substring(1)].PathItems.ContainsKey(label1)); - Assert.True(rootNode.Children[path2.Substring(1)].PathItems.ContainsKey(label2)); + Assert.True(rootNode.Children.ContainsKey(path1[1..])); + Assert.True(rootNode.Children.ContainsKey(path2[1..])); + Assert.True(rootNode.Children[path1[1..]].PathItems.ContainsKey(label1)); + Assert.True(rootNode.Children[path2[1..]].PathItems.ContainsKey(label2)); } [Fact] From 8aaa6b6bc0d6b83962351aa94a448ed71521b3d8 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 6 Oct 2023 21:38:40 +0000 Subject: [PATCH 26/61] Bump Verify.Xunit from 22.1.0 to 22.1.1 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 22.1.0 to 22.1.1. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index e69433144..331846dae 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From 21325aa3e8584a0ffc631bbffd985086293bb92b Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 21:53:59 +1100 Subject: [PATCH 27/61] Update test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj Co-authored-by: Vincent Biret --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 77c9b8001..94593bafb 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -25,7 +25,7 @@ - + Always From d5257a5e80c9903154ec833b4631dd365072cf60 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 21:56:05 +1100 Subject: [PATCH 28/61] remove some duplicate dictionary lookups --- .../V2/OpenApiResponseDeserializer.cs | 4 ++-- src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs | 5 +++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs index 5c6a4ebb7..09de8ae0b 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiResponseDeserializer.cs @@ -122,9 +122,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/Validations/Rules/RuleHelpers.cs b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs index e777d0b04..accc7f4d8 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 { From bfcb6ae0c2bbf0ea30af8e976710ef7f95eb05d8 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 22:00:16 +1100 Subject: [PATCH 29/61] discard un-used parameters --- .../V2/OpenApiDocumentDeserializer.cs | 12 ++++++------ .../V2/OpenApiOperationDeserializer.cs | 8 ++++---- .../V2/OpenApiSecuritySchemeDeserializer.cs | 8 ++++---- .../V3/OpenApiDocumentDeserializer.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiComponents.cs | 2 +- src/Microsoft.OpenApi/Models/OpenApiDocument.cs | 2 +- .../Services/OpenApiFilterService.cs | 10 +++++----- .../Writers/OpenApiWriterExtensions.cs | 2 +- .../TestCustomExtension.cs | 2 +- .../Validations/OpenApiReferenceValidationTests.cs | 2 +- 10 files changed, 25 insertions(+), 25 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 92643cb92..dad25cae7 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -21,22 +21,22 @@ internal static partial class OpenApiV2Deserializer private static FixedFieldMap _openApiFixedFields = new() { { - "swagger", (o, n) => + "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 +46,7 @@ internal static partial class OpenApiV2Deserializer } }, { - "produces", (o, n) => { + "produces", (_, n) => { var produces = n.CreateSimpleList(s => s.GetScalarValue()); if (produces.Count > 0) { diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index c7a7d723b..151c6b3bb 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -57,7 +57,7 @@ internal static partial class OpenApiV2Deserializer } }, { - "consumes", (o, n) => { + "consumes", (_, n) => { var consumes = n.CreateSimpleList(s => s.GetScalarValue()); if (consumes.Count > 0) { n.Context.SetTempStorage(TempStorageKeys.OperationConsumes,consumes); @@ -65,7 +65,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); @@ -185,7 +185,7 @@ private static OpenApiRequestBody CreateFormBody(ParsingContext context, List k, - v => mediaType) + _ => mediaType) }; return formBody; @@ -205,7 +205,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/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs index 3cb9efe52..40596cac7 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs @@ -47,27 +47,27 @@ internal static partial class OpenApiV2Deserializer {"name", (o, n) => o.Name = n.GetScalarValue()}, {"in", (o, n) => o.In = n.GetScalarValue().GetEnumFromDisplayName()}, { - "flow", (o, n) => + "flow", (_, n) => { _flowValue = n.GetScalarValue(); } }, { "authorizationUrl", - (o, n) => + (_, n) => { _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { "tokenUrl", - (o, n) => + (_, n) => { _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); } }, { - "scopes", (o, n) => + "scopes", (_, n) => { _flow.Scopes = 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/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 31b7282f3..fb70a2965 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -109,7 +109,7 @@ public void SerializeAsV3(IOpenApiWriter writer) writer.WriteOptionalMap( OpenApiConstants.Schemas, Schemas, - (w, key, component) => { + (w, _, component) => { component.SerializeAsV3WithoutReference(w); }); } diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index c2fa42890..27d8e3d25 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -173,7 +173,7 @@ public void SerializeAsV2(IOpenApiWriter writer) writer.WriteOptionalMap( OpenApiConstants.Definitions, openApiSchemas, - (w, key, component) => + (w, _, component) => { component.SerializeAsV2WithoutReference(w); }); 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/Writers/OpenApiWriterExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs index a0fa62eae..2ebb62071 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/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.Tests/Validations/OpenApiReferenceValidationTests.cs b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs index b145f9ab9..d2c4a1b70 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/OpenApiReferenceValidationTests.cs @@ -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")) { } } From 1292e9ec7ccf54741a101bde0f9b8fb910bdb2a4 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 22:14:37 +1100 Subject: [PATCH 30/61] use some pattern matching --- .../OpenApiSpecVersionHelper.cs | 2 +- .../OpenApiRemoteReferenceCollector.cs | 9 +++---- .../V2/OpenApiDocumentDeserializer.cs | 4 +-- .../V2/OpenApiParameterDeserializer.cs | 2 +- .../Models/OpenApiComponents.cs | 27 +++++++------------ .../Models/OpenApiDocument.cs | 12 +++------ .../Models/OpenApiOperation.cs | 2 +- .../Models/OpenApiParameter.cs | 2 +- .../Services/OpenApiReferenceResolver.cs | 2 +- .../Services/OpenApiWalker.cs | 7 ++--- .../Validations/OpenApiValidator.cs | 2 +- .../Validations/Rules/OpenApiContactRules.cs | 2 +- .../Writers/OpenApiJsonWriter.cs | 4 +-- .../Writers/OpenApiYamlWriter.cs | 8 +++--- 14 files changed, 33 insertions(+), 52 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs b/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs index 95ffceeaa..174c9c93e 100644 --- a/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs +++ b/src/Microsoft.OpenApi.Hidi/OpenApiSpecVersionHelper.cs @@ -18,7 +18,7 @@ public static OpenApiSpecVersion TryParseOpenApiSpecVersion(string value) if (int.TryParse(res, out int result)) { - if (result >= 2 && result < 3) + if (result is >= 2 and < 3) { return OpenApiSpecVersion.OpenApi2_0; } diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs index 90cd3632c..12b5f8a99 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs @@ -39,14 +39,11 @@ public override void Visit(IOpenApiReferenceable referenceable) /// private void AddReference(OpenApiReference reference) { - if (reference != null) + if (reference is {IsExternal: true}) { - if (reference.IsExternal) + if (!_references.ContainsKey(reference.ExternalResource)) { - if (!_references.ContainsKey(reference.ExternalResource)) - { - _references.Add(reference.ExternalResource, reference); - } + _references.Add(reference.ExternalResource, reference); } } } diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 92643cb92..779309d53 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -172,7 +172,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 +295,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/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs index b0013d9ae..99ce35cbb 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs @@ -166,7 +166,7 @@ internal static partial class OpenApiV2Deserializer new( p => p.Schema?.Enum, (p, v) => { - if (p.Schema != null || v != null && v.Count > 0) + if (p.Schema != null || v is {Count: > 0}) { GetOrCreateSchema(p).Enum = v; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 31b7282f3..22b766398 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -128,8 +128,7 @@ public void SerializeAsV3(IOpenApiWriter writer) Schemas, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Schema && + if (component.Reference is {Type: ReferenceType.Schema} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -146,8 +145,7 @@ public void SerializeAsV3(IOpenApiWriter writer) Responses, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Response && + if (component.Reference is {Type: ReferenceType.Response} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -164,8 +162,7 @@ public void SerializeAsV3(IOpenApiWriter writer) Parameters, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Parameter && + if (component.Reference is {Type: ReferenceType.Parameter} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -182,8 +179,7 @@ public void SerializeAsV3(IOpenApiWriter writer) Examples, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Example && + if (component.Reference is {Type: ReferenceType.Example} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -200,8 +196,7 @@ public void SerializeAsV3(IOpenApiWriter writer) RequestBodies, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.RequestBody && + if (component.Reference is {Type: ReferenceType.RequestBody} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -218,8 +213,7 @@ public void SerializeAsV3(IOpenApiWriter writer) Headers, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Header && + if (component.Reference is {Type: ReferenceType.Header} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -236,8 +230,7 @@ public void SerializeAsV3(IOpenApiWriter writer) SecuritySchemes, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.SecurityScheme && + if (component.Reference is {Type: ReferenceType.SecurityScheme} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -254,8 +247,7 @@ public void SerializeAsV3(IOpenApiWriter writer) Links, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Link && + if (component.Reference is {Type: ReferenceType.Link} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); @@ -272,8 +264,7 @@ public void SerializeAsV3(IOpenApiWriter writer) Callbacks, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Callback && + if (component.Reference is {Type: ReferenceType.Callback} && component.Reference.Id == key) { component.SerializeAsV3WithoutReference(w); diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index c2fa42890..13d74f6f4 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -189,8 +189,7 @@ public void SerializeAsV2(IOpenApiWriter writer) Components?.Schemas, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Schema && + if (component.Reference is {Type: ReferenceType.Schema} && component.Reference.Id == key) { component.SerializeAsV2WithoutReference(w); @@ -218,8 +217,7 @@ public void SerializeAsV2(IOpenApiWriter writer) parameters, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Parameter && + if (component.Reference is {Type: ReferenceType.Parameter} && component.Reference.Id == key) { component.SerializeAsV2WithoutReference(w); @@ -236,8 +234,7 @@ public void SerializeAsV2(IOpenApiWriter writer) Components?.Responses, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.Response && + if (component.Reference is {Type: ReferenceType.Response} && component.Reference.Id == key) { component.SerializeAsV2WithoutReference(w); @@ -254,8 +251,7 @@ public void SerializeAsV2(IOpenApiWriter writer) Components?.SecuritySchemes, (w, key, component) => { - if (component.Reference != null && - component.Reference.Type == ReferenceType.SecurityScheme && + if (component.Reference is {Type: ReferenceType.SecurityScheme} && component.Reference.Id == key) { component.SerializeAsV2WithoutReference(w); diff --git a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs index cdf18cddb..1d477b69d 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiOperation.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiOperation.cs @@ -280,7 +280,7 @@ public void SerializeAsV2(IOpenApiWriter writer) .SelectMany(static r => r.Value.Content?.Keys) .Concat( Responses - .Where(static r => r.Value.Reference != null && r.Value.Reference.HostDocument != null) + .Where(static r => r.Value.Reference is {HostDocument: not null}) .SelectMany(static r => r.Value.GetEffective(r.Value.Reference.HostDocument)?.Content?.Keys)) .Distinct() .ToList(); diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 553fd3da5..263548a15 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -246,7 +246,7 @@ public void SerializeAsV3WithoutReference(IOpenApiWriter writer) } // explode - writer.WriteProperty(OpenApiConstants.Explode, _explode, _style.HasValue && _style.Value == ParameterStyle.Form); + writer.WriteProperty(OpenApiConstants.Explode, _explode, _style is ParameterStyle.Form); // allowReserved writer.WriteProperty(OpenApiConstants.AllowReserved, AllowReserved, false); diff --git a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs index 19e463e36..88e1b45f9 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiReferenceResolver.cs @@ -300,7 +300,7 @@ private void ResolveTags(IList tags) private bool IsUnresolvedReference(IOpenApiReferenceable possibleReference) { - return (possibleReference != null && possibleReference.UnresolvedReference); + return possibleReference is {UnresolvedReference: true}; } } } diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index 4811f647c..04d23ed37 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -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); } diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index ae2c52721..641162af3 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -304,7 +304,7 @@ private void Validate(object item, Type type) } // Validate unresolved references as references - if (item is IOpenApiReferenceable potentialReference && potentialReference.UnresolvedReference) + if (item is IOpenApiReferenceable {UnresolvedReference: true}) { type = typeof(IOpenApiReferenceable); } diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs index b64704375..cfa8d9927 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiContactRules.cs @@ -21,7 +21,7 @@ public static class OpenApiContactRules (context, item) => { context.Enter("email"); - if (item != null && item.Email != null) + if (item is {Email: not null}) { if (!item.Email.IsEmailAddress()) { diff --git a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs index 1ff94b319..ef8ef47b5 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiJsonWriter.cs @@ -59,7 +59,7 @@ public override void WriteStartObject() var currentScope = StartScope(ScopeType.Object); - if (previousScope != null && previousScope.Type == ScopeType.Array) + if (previousScope is {Type: ScopeType.Array}) { currentScope.IsInArray = true; @@ -110,7 +110,7 @@ public override void WriteStartArray() var currentScope = StartScope(ScopeType.Array); - if (previousScope != null && previousScope.Type == ScopeType.Array) + if (previousScope is {Type: ScopeType.Array}) { currentScope.IsInArray = true; diff --git a/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs b/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs index be8794941..b68c6cd7d 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiYamlWriter.cs @@ -48,7 +48,7 @@ public override void WriteStartObject() var currentScope = StartScope(ScopeType.Object); - if (previousScope != null && previousScope.Type == ScopeType.Array) + if (previousScope is {Type: ScopeType.Array}) { currentScope.IsInArray = true; @@ -76,7 +76,7 @@ public override void WriteEndObject() if (previousScope.ObjectCount == 0) { // If we are in an object, write a white space preceding the braces. - if (currentScope != null && currentScope.Type == ScopeType.Object) + if (currentScope is {Type: ScopeType.Object}) { Writer.Write(" "); } @@ -94,7 +94,7 @@ public override void WriteStartArray() var currentScope = StartScope(ScopeType.Array); - if (previousScope != null && previousScope.Type == ScopeType.Array) + if (previousScope is {Type: ScopeType.Array}) { currentScope.IsInArray = true; @@ -122,7 +122,7 @@ public override void WriteEndArray() if (previousScope.ObjectCount == 0) { // If we are in an object, write a white space preceding the braces. - if (currentScope != null && currentScope.Type == ScopeType.Object) + if (currentScope is {Type: ScopeType.Object}) { Writer.Write(" "); } From e397649e109b81cf86e417e05aa4a7829e22f866 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 22:17:09 +1100 Subject: [PATCH 31/61] use some var --- .../Formatters/PowerShellFormatter.cs | 2 +- .../Handlers/PluginCommandHandler.cs | 4 ++-- .../Handlers/ShowCommandHandler.cs | 4 ++-- .../Handlers/TransformCommandHandler.cs | 4 ++-- .../Handlers/ValidateCommandHandler.cs | 4 ++-- src/Microsoft.OpenApi.Hidi/OpenApiService.cs | 18 ++++++++--------- .../OpenApiSpecVersionHelper.cs | 2 +- .../OpenApiYamlDocumentReader.cs | 2 +- .../ParsingContext.cs | 2 +- .../V2/OpenApiDocumentDeserializer.cs | 6 +++--- .../V2/OpenApiParameterDeserializer.cs | 2 +- .../V2/OpenApiV2VersionService.cs | 2 +- .../V3/OpenApiV3VersionService.cs | 2 +- .../EnumBindingSourceExtension.cs | 8 ++++---- .../Any/OpenApiAnyCloneHelper.cs | 4 ++-- .../Models/OpenApiComponents.cs | 2 +- .../Models/OpenApiDocument.cs | 6 +++--- .../Services/OpenApiReferenceResolver.cs | 4 ++-- .../Services/OpenApiWalker.cs | 19 ++++++++---------- .../Services/OpenApiWorkspace.cs | 2 +- .../Validations/Rules/OpenApiSchemaRules.cs | 2 +- .../Validations/Rules/RuleHelpers.cs | 2 +- .../Validations/ValidationExtensions.cs | 4 ++-- .../Validations/ValidationRule.cs | 2 +- .../Validations/ValidationRuleSet.cs | 10 +++++----- .../Writers/OpenApiYamlWriter.cs | 2 +- .../Services/OpenApiServiceTests.cs | 12 +++++------ .../Resources.cs | 6 +++--- .../V2Tests/OpenApiDocumentTests.cs | 10 +++++----- .../V3Tests/OpenApiDocumentTests.cs | 4 ++-- .../Expressions/BodyExpressionTests.cs | 4 ++-- .../Expressions/HeaderExpressionTests.cs | 2 +- .../Expressions/PathExpressionTests.cs | 2 +- .../Expressions/QueryExpressionTests.cs | 2 +- .../Expressions/RequestExpressionTests.cs | 4 ++-- .../Expressions/ResponseExpressionTests.cs | 4 ++-- .../Expressions/RuntimeExpressionTests.cs | 20 +++++++++---------- .../Expressions/SourceExpressionTests.cs | 10 +++++----- .../OpenApiDeprecationExtensionTests.cs | 8 ++++---- .../OpenApiEnumFlagsExtensionTests.cs | 10 +++++----- ...nApiEnumValuesDescriptionExtensionTests.cs | 8 ++++---- .../OpenApiPagingExtensionsTests.cs | 2 +- ...penApiPrimaryErrorMessageExtensionTests.cs | 6 +++--- .../Models/OpenApiDocumentTests.cs | 2 +- .../Models/OpenApiSecurityRequirementTests.cs | 4 ++-- .../Services/OpenApiUrlTreeNodeTests.cs | 2 +- .../OpenApiComponentsValidationTests.cs | 6 +++--- .../OpenApiContactValidationTests.cs | 6 +++--- .../OpenApiExternalDocsValidationTests.cs | 6 +++--- .../OpenApiHeaderValidationTests.cs | 4 ++-- .../Validations/OpenApiInfoValidationTests.cs | 6 +++--- .../OpenApiLicenseValidationTests.cs | 6 +++--- .../OpenApiMediaTypeValidationTests.cs | 4 ++-- .../OpenApiOAuthFlowValidationTests.cs | 8 ++++---- .../OpenApiParameterValidationTests.cs | 12 +++++------ .../OpenApiReferenceValidationTests.cs | 6 +++--- .../OpenApiResponseValidationTests.cs | 6 +++--- .../OpenApiSchemaValidationTests.cs | 10 +++++----- .../OpenApiServerValidationTests.cs | 6 +++--- .../Validations/OpenApiTagValidationTests.cs | 12 +++++------ 60 files changed, 169 insertions(+), 172 deletions(-) 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/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/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 92643cb92..097c38fbc 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -138,7 +138,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 +172,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 +295,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/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs index b0013d9ae..76926ecc2 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs @@ -288,7 +288,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/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/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.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/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index 31b7282f3..0f4262455 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); diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index c2fa42890..b761f112e 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); @@ -425,8 +425,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/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/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index 4811f647c..4022793d5 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); } @@ -879,7 +876,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 +896,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/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..ddf9dc0b4 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/RuleHelpers.cs @@ -121,7 +121,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..733d5f725 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRule.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRule.cs @@ -62,7 +62,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..69ec17e11 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); } @@ -163,10 +163,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/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/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index b2b6b6c9b..f588e4838 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -208,7 +208,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 +228,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 +246,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 +264,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 +284,7 @@ public async Task TransformCommandConvertsOpenApiWithDefaultOutputNameAndSwitchF [Fact] public Task ThrowTransformCommandIfOpenApiAndCsdlAreEmpty() { - HidiOptions options = new HidiOptions + var options = new HidiOptions { CleanOutput = true, TerseOutput = false, @@ -299,7 +299,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, 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/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.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/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/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..94518ba0c 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); 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..baa3032bc 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() { 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); } } From 6ae128c19797c9b85a515a76df65dfbc825e49b4 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 23:11:53 +1100 Subject: [PATCH 32/61] use some expression lambdas --- src/Microsoft.OpenApi.Hidi/Logger.cs | 5 +- .../V2/OpenApiContactDeserializer.cs | 18 +- .../V2/OpenApiDocumentDeserializer.cs | 6 +- .../V2/OpenApiExternalDocsDeserializer.cs | 12 +- .../V2/OpenApiHeaderDeserializer.cs | 108 +++------ .../V2/OpenApiInfoDeserializer.cs | 36 +-- .../V2/OpenApiLicenseDeserializer.cs | 12 +- .../V2/OpenApiOperationDeserializer.cs | 48 ++-- .../V2/OpenApiParameterDeserializer.cs | 114 ++++------ .../V2/OpenApiPathItemDeserializer.cs | 6 +- .../V2/OpenApiResponseDeserializer.cs | 24 +- .../V2/OpenApiSchemaDeserializer.cs | 162 +++++--------- .../V2/OpenApiSecuritySchemeDeserializer.cs | 22 +- .../V2/OpenApiTagDeserializer.cs | 18 +- .../V2/OpenApiXmlDeserializer.cs | 24 +- .../V3/OpenApiContactDeserializer.cs | 18 +- .../V3/OpenApiDiscriminatorDeserializer.cs | 12 +- .../V3/OpenApiEncodingDeserializer.cs | 30 +-- .../V3/OpenApiExampleDeserializer.cs | 24 +- .../V3/OpenApiExternalDocsDeserializer.cs | 12 +- .../V3/OpenApiHeaderDeserializer.cs | 60 ++--- .../V3/OpenApiInfoDeserializer.cs | 36 +-- .../V3/OpenApiLicenseDeserializer.cs | 12 +- .../V3/OpenApiLinkDeserializer.cs | 30 +-- .../V3/OpenApiMediaTypeDeserializer.cs | 24 +- .../V3/OpenApiOAuthFlowDeserializer.cs | 18 +- .../V3/OpenApiOperationDeserializer.cs | 66 ++---- .../V3/OpenApiParameterDeserializer.cs | 72 ++---- .../V3/OpenApiPathItemDeserializer.cs | 12 +- .../V3/OpenApiRequestBodyDeserializer.cs | 18 +- .../V3/OpenApiResponseDeserializer.cs | 24 +- .../V3/OpenApiSchemaDeserializer.cs | 205 ++++++------------ .../V3/OpenApiSecuritySchemeDeserializer.cs | 48 ++-- .../V3/OpenApiServerDeserializer.cs | 18 +- .../V3/OpenApiServerVariableDeserializer.cs | 18 +- .../V3/OpenApiTagDeserializer.cs | 18 +- .../V3/OpenApiXmlDeserializer.cs | 30 +-- .../Models/OpenApiDocument.cs | 5 +- .../Models/OpenApiOperation.cs | 10 +- .../Services/OpenApiServiceTests.cs | 1 - .../Services/OpenApiUrlTreeNodeTests.cs | 25 +-- .../Workspaces/OpenApiWorkspaceTests.cs | 3 +- 42 files changed, 482 insertions(+), 982 deletions(-) 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.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..09ffb68f5 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -21,9 +21,9 @@ internal static partial class OpenApiV2Deserializer private static FixedFieldMap _openApiFixedFields = new() { { - "swagger", (o, n) => - { - } /* Version is valid field but we already parsed it */ + "swagger", + (o, n) => {} + /* 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())}, 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..873b34204 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -27,34 +27,24 @@ 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) => { @@ -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) }, }; diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiParameterDeserializer.cs index b0013d9ae..4cf80abb2 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) }, }; 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..dc7bc1fc8 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) }, }; 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..5f4aacfaa 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs @@ -47,30 +47,20 @@ 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", + (o, n) => _flowValue = n.GetScalarValue() }, { "authorizationUrl", - (o, n) => - { - _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + (o, n) => _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { "tokenUrl", - (o, n) => - { - _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + (o, n) => _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "scopes", (o, n) => - { - _flow.Scopes = n.CreateSimpleMap(LoadString); - } + "scopes", + (o, 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/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/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/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/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index c2fa42890..c215ad3c2 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -173,10 +173,7 @@ public void SerializeAsV2(IOpenApiWriter writer) writer.WriteOptionalMap( OpenApiConstants.Definitions, openApiSchemas, - (w, key, component) => - { - component.SerializeAsV2WithoutReference(w); - }); + (w, key, component) => component.SerializeAsV2WithoutReference(w)); } } else 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/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index b2b6b6c9b..5face8879 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() { diff --git a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs index c7ee7e692..9544788b5 100644 --- a/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs +++ b/test/Microsoft.OpenApi.Tests/Services/OpenApiUrlTreeNodeTests.cs @@ -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/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 From 93505622683eff1b7293b73ab43a6a6e1c1a3ad5 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 23:13:32 +1100 Subject: [PATCH 33/61] remove redundant type specs --- src/Microsoft.OpenApi.Hidi/Extensions/StringExtensions.cs | 2 +- src/Microsoft.OpenApi/Any/OpenApiByte.cs | 2 +- .../Services/OpenApiServiceTests.cs | 6 +++--- .../Writers/OpenApiJsonWriterTests.cs | 5 +++-- .../Writers/OpenApiWriterAnyExtensionsTests.cs | 8 ++++---- 5 files changed, 12 insertions(+), 11 deletions(-) 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/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/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs index b2b6b6c9b..fb451c1d8 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs +++ b/test/Microsoft.OpenApi.Hidi.Tests/Services/OpenApiServiceTests.cs @@ -322,7 +322,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 +339,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 +355,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.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..05b57f4f3 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, From 1228e7526fb0a5f09553c610eb774b73258b3109 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 23:28:31 +1100 Subject: [PATCH 34/61] use some expression gets --- .../Expressions/BodyExpression.cs | 8 +---- .../Expressions/HeaderExpression.cs | 16 ++-------- .../Expressions/PathExpression.cs | 16 ++-------- .../Expressions/QueryExpression.cs | 16 ++-------- .../Services/OpenApiVisitorBase.cs | 8 +---- .../Validations/OpenApiValidator.cs | 16 ++-------- .../Validations/ValidationRuleSet.cs | 5 +-- src/Microsoft.OpenApi/Writers/Scope.cs | 8 +---- .../OpenApiWriterAnyExtensionsTests.cs | 11 +++---- .../OpenApiWriterSpecialCharacterTests.cs | 31 +++++++++---------- 10 files changed, 30 insertions(+), 105 deletions(-) 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/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/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/ValidationRuleSet.cs b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs index 7c93919e4..3829f8d05 100644 --- a/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs +++ b/src/Microsoft.OpenApi/Validations/ValidationRuleSet.cs @@ -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(); } /// 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/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs index 7c378c16f..6a1d4ee8b 100644 --- a/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs +++ b/test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterAnyExtensionsTests.cs @@ -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] From 06bccb9749ea3e11342de8ff325752e23ec06e3f Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 23:35:58 +1100 Subject: [PATCH 35/61] only null check on public apis --- .../Extensions/OpenApiSerializableExtensions.cs | 1 - src/Microsoft.OpenApi/Models/OpenApiContact.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiExternalDocs.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiLicense.cs | 2 -- src/Microsoft.OpenApi/Models/OpenApiSchema.cs | 6 ------ src/Microsoft.OpenApi/Models/OpenApiXml.cs | 2 -- src/Microsoft.OpenApi/Validations/ValidationRule.cs | 2 -- .../Writers/OpenApiWriterAnyExtensions.cs | 9 --------- src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs | 6 ------ 9 files changed, 32 deletions(-) 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/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/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/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/Validations/ValidationRule.cs b/src/Microsoft.OpenApi/Validations/ValidationRule.cs index 5c930de1b..89cbe41f0 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; 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 a0fa62eae..ac9f66b9a 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -402,22 +402,16 @@ private static void WriteMapInternal( private static void CheckArguments(IOpenApiWriter writer, string name, Action action) { - CheckArguments(writer, name); - Utils.CheckArgumentNull(action); } private static void CheckArguments(IOpenApiWriter writer, string name, Action action) { - CheckArguments(writer, name); - Utils.CheckArgumentNull(action); } private static void CheckArguments(IOpenApiWriter writer, string name) { - Utils.CheckArgumentNull(writer); - Utils.CheckArgumentNullOrEmpty(name); } } From 9937565da57d05bb09016c01636538c508abb153 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Sun, 8 Oct 2023 23:41:49 +1100 Subject: [PATCH 36/61] remove redundant CheckArguments --- .../Writers/OpenApiWriterExtensions.cs | 37 ++++--------------- 1 file changed, 8 insertions(+), 29 deletions(-) diff --git a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs index a0fa62eae..7c532da5b 100644 --- a/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/OpenApiWriterExtensions.cs @@ -27,7 +27,7 @@ public static void WriteProperty(this IOpenApiWriter writer, string name, string return; } - CheckArguments(writer, name); + Utils.CheckArgumentNullOrEmpty(name); writer.WritePropertyName(name); writer.WriteValue(value); } @@ -40,7 +40,7 @@ public static void WriteProperty(this IOpenApiWriter writer, string name, string /// The property value. public static void WriteRequiredProperty(this IOpenApiWriter writer, string name, string value) { - CheckArguments(writer, name); + Utils.CheckArgumentNullOrEmpty(name); writer.WritePropertyName(name); if (value == null) { @@ -66,7 +66,7 @@ public static void WriteProperty(this IOpenApiWriter writer, string name, bool v return; } - CheckArguments(writer, name); + Utils.CheckArgumentNullOrEmpty(name); writer.WritePropertyName(name); writer.WriteValue(value); } @@ -89,7 +89,7 @@ public static void WriteProperty( return; } - CheckArguments(writer, name); + Utils.CheckArgumentNullOrEmpty(name); writer.WritePropertyName(name); writer.WriteValue(value.Value); } @@ -120,7 +120,7 @@ public static void WriteProperty(this IOpenApiWriter writer, string name, T? public static void WriteProperty(this IOpenApiWriter writer, string name, T value) where T : struct { - CheckArguments(writer, name); + Utils.CheckArgumentNullOrEmpty(name); writer.WritePropertyName(name); writer.WriteValue(value); } @@ -166,7 +166,7 @@ public static void WriteRequiredObject( Action action) where T : IOpenApiElement { - CheckArguments(writer, name, action); + Utils.CheckArgumentNull(action); writer.WritePropertyName(name); if (value != null) @@ -339,7 +339,7 @@ private static void WriteCollectionInternal( IEnumerable elements, Action action) { - CheckArguments(writer, name, action); + Utils.CheckArgumentNull(action); writer.WritePropertyName(name); writer.WriteStartArray(); @@ -376,7 +376,7 @@ private static void WriteMapInternal( IDictionary elements, Action action) { - CheckArguments(writer, name, action); + Utils.CheckArgumentNull(action); writer.WritePropertyName(name); writer.WriteStartObject(); @@ -399,26 +399,5 @@ private static void WriteMapInternal( writer.WriteEndObject(); } - - private static void CheckArguments(IOpenApiWriter writer, string name, Action action) - { - CheckArguments(writer, name); - - Utils.CheckArgumentNull(action); - } - - private static void CheckArguments(IOpenApiWriter writer, string name, Action action) - { - CheckArguments(writer, name); - - Utils.CheckArgumentNull(action); - } - - private static void CheckArguments(IOpenApiWriter writer, string name) - { - Utils.CheckArgumentNull(writer); - - Utils.CheckArgumentNullOrEmpty(name); - } } } From fe74c3d5f722985d2d6ad740db37743ad0e948a1 Mon Sep 17 00:00:00 2001 From: Lars Johansen Date: Mon, 9 Oct 2023 09:50:52 +0200 Subject: [PATCH 37/61] Use lookup collections --- .../SpecialCharacterStringExtensions.cs | 176 ++++++++---------- 1 file changed, 74 insertions(+), 102 deletions(-) diff --git a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs index 02d30ec08..a3f5ad37a 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,47 +58,47 @@ 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 _yamlControlCharacterReplacements = 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"}, }; /// @@ -125,7 +126,7 @@ internal static string GetYamlCompatibleString(this string input) } // If string includes a control character, wrapping in double quote is required. - if (input.Any(c => _yamlControlCharacters.Contains(c))) + if (input.Any(c => _yamlControlCharacterReplacements.ContainsKey(c))) { // Replace the backslash first, so that the new backslashes created by other Replaces are not duplicated. input = input.Replace("\\", "\\\\"); @@ -134,39 +135,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 _yamlControlCharacterReplacements) + { + input = input.Replace(replacement.Key.ToString(), replacement.Value); + } + return $"\"{input}\""; } @@ -177,8 +150,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. @@ -215,21 +188,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 _); } } } From 2cf6873912c2ec2a52a6fdb700a84e157898e6fa Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 9 Oct 2023 21:21:57 +0000 Subject: [PATCH 38/61] Bump Verify.Xunit from 22.1.1 to 22.1.2 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 22.1.1 to 22.1.2. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/commits/22.1.2) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 331846dae..6268a65d1 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From 40621e06e6514d8e47aa4206784dfb18ebcb9a43 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 10 Oct 2023 21:42:11 +0000 Subject: [PATCH 39/61] Bump Verify.Xunit from 22.1.2 to 22.1.3 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 22.1.2 to 22.1.3. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/22.1.2...22.1.3) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 6268a65d1..c55637227 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From 1c4721a410e6a699c8c90463fedf7d3fdc4521ee Mon Sep 17 00:00:00 2001 From: Lars Johansen Date: Wed, 11 Oct 2023 07:24:24 +0200 Subject: [PATCH 40/61] Added secondary dictionary with string key for yaml control characters --- .../SpecialCharacterStringExtensions.cs | 42 +++++++++---------- 1 file changed, 20 insertions(+), 22 deletions(-) diff --git a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs index a3f5ad37a..708aa7237 100644 --- a/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs +++ b/src/Microsoft.OpenApi/Writers/SpecialCharacterStringExtensions.cs @@ -65,7 +65,7 @@ public static class SpecialCharacterStringExtensions // 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 Dictionary _yamlControlCharacterReplacements = new() + private static readonly Dictionary _yamlControlCharacterCharReplacements = new() { {'\0', "\\0"}, {'\x01', "\\x01"}, @@ -100,6 +100,9 @@ public static class SpecialCharacterStringExtensions {'\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 @@ -107,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 == "") + switch (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 == "~") - { - 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 => _yamlControlCharacterReplacements.ContainsKey(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("\\", "\\\\"); @@ -135,9 +133,9 @@ internal static string GetYamlCompatibleString(this string input) input = input.Replace("\"", "\\\""); // Escape all the control characters. - foreach (var replacement in _yamlControlCharacterReplacements) + foreach (var replacement in _yamlControlCharacterStringReplacements) { - input = input.Replace(replacement.Key.ToString(), replacement.Value); + input = input.Replace(replacement.Key, replacement.Value); } return $"\"{input}\""; @@ -162,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}'"; } From 3408bfc8285b8e866056478aa081113084fb3aa2 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 11 Oct 2023 22:04:20 +1100 Subject: [PATCH 41/61] Update OpenApiRemoteReferenceCollector.cs --- .../Services/OpenApiRemoteReferenceCollector.cs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs index 12b5f8a99..cc2879bd5 100644 --- a/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs +++ b/src/Microsoft.OpenApi.Readers/Services/OpenApiRemoteReferenceCollector.cs @@ -39,12 +39,10 @@ public override void Visit(IOpenApiReferenceable referenceable) /// private void AddReference(OpenApiReference reference) { - if (reference is {IsExternal: true}) + if (reference is {IsExternal: true} && + !_references.ContainsKey(reference.ExternalResource)) { - if (!_references.ContainsKey(reference.ExternalResource)) - { - _references.Add(reference.ExternalResource, reference); - } + _references.Add(reference.ExternalResource, reference); } } } From c5bc8d921fe9a7ef10fdd1960e71e0483f0da5b3 Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Wed, 11 Oct 2023 22:12:12 +1100 Subject: [PATCH 42/61] . --- .../V2/OpenApiDocumentDeserializer.cs | 5 ++--- .../V2/OpenApiSecuritySchemeDeserializer.cs | 20 ++++--------------- .../Models/OpenApiComponents.cs | 4 +--- .../Models/OpenApiDocument.cs | 5 +---- 4 files changed, 8 insertions(+), 26 deletions(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs index 3d674832f..07bdcb301 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiDocumentDeserializer.cs @@ -21,9 +21,8 @@ internal static partial class OpenApiV2Deserializer private static FixedFieldMap _openApiFixedFields = new() { { - "swagger", (_, _) => - { - } /* 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", (_, n) => n.Context.SetTempStorage("host", n.GetScalarValue())}, diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiSecuritySchemeDeserializer.cs index 40596cac7..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", (_, n) => - { - _flowValue = n.GetScalarValue(); - } + "flow", (_, n) => _flowValue = n.GetScalarValue() }, { "authorizationUrl", - (_, n) => - { - _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + (_, n) => _flow.AuthorizationUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { "tokenUrl", - (_, n) => - { - _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute); - } + (_, n) => _flow.TokenUrl = new(n.GetScalarValue(), UriKind.RelativeOrAbsolute) }, { - "scopes", (_, n) => - { - _flow.Scopes = n.CreateSimpleMap(LoadString); - } + "scopes", (_, n) => _flow.Scopes = n.CreateSimpleMap(LoadString) } }; diff --git a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs index ef8d261a0..5a52c9584 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiComponents.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiComponents.cs @@ -109,9 +109,7 @@ public void SerializeAsV3(IOpenApiWriter writer) writer.WriteOptionalMap( OpenApiConstants.Schemas, Schemas, - (w, _, component) => { - component.SerializeAsV3WithoutReference(w); - }); + (w, _, component) => component.SerializeAsV3WithoutReference(w)); } writer.WriteEndObject(); return; diff --git a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs index 1b9ad7b77..77ccef663 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiDocument.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiDocument.cs @@ -173,10 +173,7 @@ public void SerializeAsV2(IOpenApiWriter writer) writer.WriteOptionalMap( OpenApiConstants.Definitions, openApiSchemas, - (w, _, component) => - { - component.SerializeAsV2WithoutReference(w); - }); + (w, _, component) => component.SerializeAsV2WithoutReference(w)); } } else From 8599f87828f3ea9242e6ff33cc2139c2c81196ec Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 13 Oct 2023 21:25:47 +0000 Subject: [PATCH 43/61] Bump xunit from 2.5.1 to 2.5.2 Bumps [xunit](https://github.com/xunit/xunit) from 2.5.1 to 2.5.2. - [Commits](https://github.com/xunit/xunit/compare/2.5.1...2.5.2) --- updated-dependencies: - dependency-name: xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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..396d89f71 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -14,7 +14,7 @@ - + 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..edf22c439 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -21,7 +21,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 637e25583..0ee150aa1 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -12,7 +12,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index c55637227..a4d379cf9 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -16,7 +16,7 @@ - + From 08273f632b01606397cb2f9ec740dc1efced9909 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 14 Oct 2023 16:08:25 +0000 Subject: [PATCH 44/61] Bump xunit.runner.visualstudio from 2.5.1 to 2.5.3 Bumps [xunit.runner.visualstudio](https://github.com/xunit/visualstudio.xunit) from 2.5.1 to 2.5.3. - [Release notes](https://github.com/xunit/visualstudio.xunit/releases) - [Commits](https://github.com/xunit/visualstudio.xunit/compare/2.5.1...2.5.3) --- updated-dependencies: - dependency-name: xunit.runner.visualstudio dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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 396d89f71..c9ca053f1 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -15,7 +15,7 @@ - + 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 edf22c439..3f592d32b 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj +++ b/test/Microsoft.OpenApi.Readers.Tests/Microsoft.OpenApi.Readers.Tests.csproj @@ -22,7 +22,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index 0ee150aa1..da8759bbe 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -13,7 +13,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index a4d379cf9..0348083de 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -17,7 +17,7 @@ - + From b744048a1144a019d0a6a2a6545ffcb0debe3911 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Mon, 16 Oct 2023 21:02:29 +0000 Subject: [PATCH 45/61] Bump Verify.Xunit from 22.1.3 to 22.1.4 Bumps [Verify.Xunit](https://github.com/VerifyTests/Verify) from 22.1.3 to 22.1.4. - [Release notes](https://github.com/VerifyTests/Verify/releases) - [Commits](https://github.com/VerifyTests/Verify/compare/22.1.3...22.1.4) --- updated-dependencies: - dependency-name: Verify.Xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index 0348083de..cee965602 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -15,7 +15,7 @@ - + From 5ef48adc627812f9d674974124625692151fcf51 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 17 Oct 2023 21:05:39 +0000 Subject: [PATCH 46/61] Bump xunit from 2.5.2 to 2.5.3 Bumps [xunit](https://github.com/xunit/xunit) from 2.5.2 to 2.5.3. - [Commits](https://github.com/xunit/xunit/compare/2.5.2...2.5.3) --- updated-dependencies: - dependency-name: xunit dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- .../Microsoft.OpenApi.Readers.Tests.csproj | 2 +- .../Microsoft.OpenApi.SmokeTests.csproj | 2 +- test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) 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 c9ca053f1..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,7 +14,7 @@ - + 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 3f592d32b..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,7 +21,7 @@ - + diff --git a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj index da8759bbe..7fa988024 100644 --- a/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj +++ b/test/Microsoft.OpenApi.SmokeTests/Microsoft.OpenApi.SmokeTests.csproj @@ -12,7 +12,7 @@ - + diff --git a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj index cee965602..b5e18ee5c 100644 --- a/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj +++ b/test/Microsoft.OpenApi.Tests/Microsoft.OpenApi.Tests.csproj @@ -16,7 +16,7 @@ - + From c2ec5e15ca78c46ed839e6b8b6ff34c600c090e9 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 24 Oct 2023 15:11:02 +0300 Subject: [PATCH 47/61] Write out link extensions --- src/Microsoft.OpenApi/Models/OpenApiLink.cs | 3 +++ 1 file changed, 3 insertions(+) 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(); } From 41dce19c16f1018f0f544d5530f7071f7c270dc7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 24 Oct 2023 15:11:20 +0300 Subject: [PATCH 48/61] Add test to validate --- .../Models/OpenApiLinkTests.cs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs index 3f95fb9e3..ad02e1e4e 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs @@ -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()); + } } } From 7f71a4f25e987cda5681bfdd14474d9302cd66c7 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 24 Oct 2023 15:21:49 +0300 Subject: [PATCH 49/61] Address code smells --- test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiLinkTests.cs index ad02e1e4e..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() { From d183ad5f4a97b5378e6987c63d571272730319b1 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 24 Oct 2023 16:30:43 +0300 Subject: [PATCH 50/61] Add logic to walk OpenApiSchema.Not property --- src/Microsoft.OpenApi/Services/OpenApiWalker.cs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs index 4022793d5..a0d28d7af 100644 --- a/src/Microsoft.OpenApi/Services/OpenApiWalker.cs +++ b/src/Microsoft.OpenApi/Services/OpenApiWalker.cs @@ -773,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)); From 762976504e4d381b5ceabcd35656a581459e0364 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 24 Oct 2023 16:31:00 +0300 Subject: [PATCH 51/61] Add test to verify --- .../Models/OpenApiSchemaTests.cs | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index b4c331830..6659d3a42 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; @@ -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); + } } } From 67ce8f427636497f90c9f298b399f858878a81e4 Mon Sep 17 00:00:00 2001 From: Maggie Kimani Date: Tue, 24 Oct 2023 16:44:56 +0300 Subject: [PATCH 52/61] Make static fields readonly --- .../Models/OpenApiSchemaTests.cs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs index 6659d3a42..c4a9ddd53 100644 --- a/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs +++ b/test/Microsoft.OpenApi.Tests/Models/OpenApiSchemaTests.cs @@ -25,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, @@ -42,7 +42,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema AdvancedSchemaObject = new() + public static readonly OpenApiSchema AdvancedSchemaObject = new() { Title = "title1", Properties = new Dictionary @@ -91,7 +91,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema AdvancedSchemaWithAllOf = new() + public static readonly OpenApiSchema AdvancedSchemaWithAllOf = new() { Title = "title1", AllOf = new List @@ -143,7 +143,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema ReferencedSchema = new() + public static readonly OpenApiSchema ReferencedSchema = new() { Title = "title1", MultipleOf = 3, @@ -166,7 +166,7 @@ public class OpenApiSchemaTests } }; - public static OpenApiSchema AdvancedSchemaWithRequiredPropertiesObject = new() + public static readonly OpenApiSchema AdvancedSchemaWithRequiredPropertiesObject = new() { Title = "title1", Required = new HashSet { "property1" }, From a0bf1fd1c9ddbd9e47751c2fa174c0b585a83fba Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Oct 2023 15:35:57 -0400 Subject: [PATCH 53/61] - fixes filter for files copy --- .../Microsoft.OpenApi.Hidi.Tests.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 94593bafb..d5044b2cc 100644 --- a/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj +++ b/test/Microsoft.OpenApi.Hidi.Tests/Microsoft.OpenApi.Hidi.Tests.csproj @@ -25,7 +25,7 @@ - + Always From 9429da4f1ff62fca498892d37f993267c916a471 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Oct 2023 15:41:44 -0400 Subject: [PATCH 54/61] - cleans up duplicated method Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi/Validations/OpenApiValidator.cs | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs index 6678b3282..8e9ed4fc4 100644 --- a/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs +++ b/src/Microsoft.OpenApi/Validations/OpenApiValidator.cs @@ -137,12 +137,6 @@ public void AddWarning(OpenApiValidatorWarning warning) /// The object to be validated public override void Visit(OpenApiParameter item) => Validate(item); - /// - /// Execute validation rules against an - /// - /// The object to be validated - public override void Visit(OpenApiPaths item) => Validate(item); - /// /// Execute validation rules against an /// From 6bda890fc7f19db283123a7aa4327b2cc39bc99e Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Oct 2023 15:44:01 -0400 Subject: [PATCH 55/61] - makes regex static for performance Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs index 5fd200100..37587674b 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.OpenApi.Models; @@ -35,6 +36,7 @@ public static class OpenApiPathsRules } }); + private static readonly Regex regexPath = new Regex("\\{([^/]+)\\}", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100)); /// /// A relative path to an individual endpoint. The field name MUST begin with a slash. /// @@ -42,14 +44,13 @@ public static class OpenApiPathsRules new ValidationRule( (context, item) => { - const string regexPath = "\\{([^/]+)\\}"; var hashSet = new HashSet(); foreach (var path in item.Keys) { context.Enter(path); - var pathSignature = Regex.Replace(path, regexPath, "{}"); + var pathSignature = regexPath.Replace(path, "{}"); if (!hashSet.Add(pathSignature)) context.CreateError(nameof(PathMustBeUnique), From da035fad3bd418628bab2969cb01fec280342cf8 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Oct 2023 15:45:54 -0400 Subject: [PATCH 56/61] - fixes string comparison Signed-off-by: Vincent Biret --- src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs index 37587674b..c25ca8aff 100644 --- a/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs +++ b/src/Microsoft.OpenApi/Validations/Rules/OpenApiPathsRules.cs @@ -26,7 +26,7 @@ public static class OpenApiPathsRules { context.Enter(pathName); - if (pathName == null || !pathName.StartsWith("/")) + if (pathName == null || !pathName.StartsWith("/", StringComparison.OrdinalIgnoreCase)) { context.CreateError(nameof(PathNameMustBeginWithSlash), string.Format(SRResource.Validation_PathItemMustBeginWithSlash, pathName)); From 5140bafd7ebda60ad97126b66aa8df3afb9eb111 Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Tue, 24 Oct 2023 15:47:32 -0400 Subject: [PATCH 57/61] - fixes unit tests Signed-off-by: Vincent Biret --- test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt | 1 + .../Validations/ValidationRuleSetTests.cs | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt index b6828dff7..a5309e46d 100755 --- a/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt +++ b/test/Microsoft.OpenApi.Tests/PublicApi/PublicApi.approved.txt @@ -1431,6 +1431,7 @@ namespace Microsoft.OpenApi.Validations.Rules [Microsoft.OpenApi.Validations.Rules.OpenApiRule] public static class OpenApiPathsRules { + public static Microsoft.OpenApi.Validations.ValidationRule PathMustBeUnique { get; } public static Microsoft.OpenApi.Validations.ValidationRule PathNameMustBeginWithSlash { get; } } [Microsoft.OpenApi.Validations.Rules.OpenApiRule] diff --git a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs index fcafaab21..708d6ee64 100644 --- a/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs +++ b/test/Microsoft.OpenApi.Tests/Validations/ValidationRuleSetTests.cs @@ -35,7 +35,7 @@ public void DefaultRuleSetPropertyReturnsTheCorrectRules() Assert.NotEmpty(rules); // Update the number if you add new default rule(s). - Assert.Equal(22, rules.Count); + Assert.Equal(23, rules.Count); } } } From daf718644a5eaa177bb31f73214140516a55a509 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Tue, 24 Oct 2023 21:16:16 +0000 Subject: [PATCH 58/61] Bump Microsoft.OpenApi.OData from 1.5.0-preview5 to 1.5.0-preview6 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.5.0-preview5 to 1.5.0-preview6. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 5ee796e07..3e9efd49c 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -35,7 +35,7 @@ - + From 71c4eea851f94101233de28ce8608bee8196a837 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Thu, 26 Oct 2023 21:14:11 +0000 Subject: [PATCH 59/61] Bump Microsoft.OpenApi.OData from 1.5.0-preview6 to 1.5.0-preview7 Bumps [Microsoft.OpenApi.OData](https://github.com/Microsoft/OpenAPI.NET.OData) from 1.5.0-preview6 to 1.5.0-preview7. - [Release notes](https://github.com/Microsoft/OpenAPI.NET.OData/releases) - [Commits](https://github.com/Microsoft/OpenAPI.NET.OData/commits) --- updated-dependencies: - dependency-name: Microsoft.OpenApi.OData dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index 3e9efd49c..bf9808a8c 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -35,7 +35,7 @@ - + From 639aa7eba514adfde2f8dba656dfd560952e0b0a Mon Sep 17 00:00:00 2001 From: Vincent Biret Date: Fri, 27 Oct 2023 10:15:59 -0400 Subject: [PATCH 60/61] - fixes a bug where the conversion would ommit the schema type --- .../V2/OpenApiOperationDeserializer.cs | 3 +++ src/Microsoft.OpenApi/Models/OpenApiParameter.cs | 2 +- .../V2Tests/OpenApiOperationTests.cs | 3 +++ .../V2Tests/OpenApiPathItemTests.cs | 5 +++++ 4 files changed, 12 insertions(+), 1 deletion(-) diff --git a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs index 098222299..f47ca1c6c 100644 --- a/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs +++ b/src/Microsoft.OpenApi.Readers/V2/OpenApiOperationDeserializer.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Linq; +using System.Security.Cryptography.X509Certificates; using Microsoft.OpenApi.Any; using Microsoft.OpenApi.Extensions; using Microsoft.OpenApi.Models; @@ -171,6 +172,8 @@ private static OpenApiRequestBody CreateFormBody(ParsingContext context, List k, _ => mediaType) }; + foreach(var value in formBody.Content.Values.Where(static x => x.Schema is not null && x.Schema.Properties.Any() && string.IsNullOrEmpty(x.Schema.Type))) + value.Schema.Type = "object"; return formBody; } diff --git a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs index 263548a15..9d1651ad8 100644 --- a/src/Microsoft.OpenApi/Models/OpenApiParameter.cs +++ b/src/Microsoft.OpenApi/Models/OpenApiParameter.cs @@ -336,7 +336,7 @@ public void SerializeAsV2WithoutReference(IOpenApiWriter writer) // In V2 parameter's type can't be a reference to a custom object schema or can't be of type object // So in that case map the type as string. else - if (Schema?.UnresolvedReference == true || Schema?.Type == "object") + if (Schema?.UnresolvedReference == true || "object".Equals(Schema?.Type, StringComparison.OrdinalIgnoreCase)) { writer.WriteProperty(OpenApiConstants.Type, "string"); } diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs index d33aa5be2..326c16969 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiOperationTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Collections.Generic; using System.IO; using System.Text; @@ -80,6 +81,7 @@ public class OpenApiOperationTests { Schema = new() { + Type = "object", Properties = { ["name"] = new() @@ -103,6 +105,7 @@ public class OpenApiOperationTests { Schema = new() { + Type = "object", Properties = { ["name"] = new() diff --git a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs index 177109131..8891cb1bf 100644 --- a/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs +++ b/test/Microsoft.OpenApi.Readers.Tests/V2Tests/OpenApiPathItemTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. +using System; using System.Collections.Generic; using System.IO; using System.Linq; @@ -67,6 +68,7 @@ public class OpenApiPathItemTests { Schema = new() { + Type = "object", Properties = { ["name"] = new() @@ -90,6 +92,7 @@ public class OpenApiPathItemTests { Schema = new() { + Type = "object", Properties = { ["name"] = new() @@ -171,6 +174,7 @@ public class OpenApiPathItemTests { Schema = new() { + Type = "object", Properties = { ["name"] = new() @@ -199,6 +203,7 @@ public class OpenApiPathItemTests { Schema = new() { + Type = "object", Properties = { ["name"] = new() From 98c31680a6c40cba918ed5885d15663d6486e760 Mon Sep 17 00:00:00 2001 From: Irvine Sunday <40403681+irvinesunday@users.noreply.github.com> Date: Fri, 27 Oct 2023 17:24:47 +0300 Subject: [PATCH 61/61] Bump up lib. versions (#1443) * Bump up Hidi version * Bump up lib versions --- src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj | 2 +- src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj | 2 +- src/Microsoft.OpenApi/Microsoft.OpenApi.csproj | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj index bf9808a8c..4e47d6e82 100644 --- a/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj +++ b/src/Microsoft.OpenApi.Hidi/Microsoft.OpenApi.Hidi.csproj @@ -9,7 +9,7 @@ enable hidi ./../../artifacts - 1.3.1 + 1.3.2 OpenAPI.NET CLI tool for slicing OpenAPI documents true diff --git a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj index 33788cebd..dd422d6ef 100644 --- a/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj +++ b/src/Microsoft.OpenApi.Readers/Microsoft.OpenApi.Readers.csproj @@ -3,7 +3,7 @@ netstandard2.0 latest true - 1.6.9 + 1.6.10 OpenAPI.NET Readers for JSON and YAML documents true diff --git a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj index dc1e97a64..047a39f77 100644 --- a/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj +++ b/src/Microsoft.OpenApi/Microsoft.OpenApi.csproj @@ -3,7 +3,7 @@ netstandard2.0 Latest true - 1.6.9 + 1.6.10 .NET models with JSON and YAML writers for OpenAPI specification true