Пример #1
0
        public void ServersShouldBeReferencedByIndex()
        {
            var openApiDocument = new OpenApiDocument();

            openApiDocument.Info = new OpenApiInfo()
            {
                Title   = "foo",
                Version = "1.2.2"
            };
            openApiDocument.Servers = new List <OpenApiServer> {
                new OpenApiServer
                {
                    Url = "http://example.org"
                },
                new OpenApiServer
                {
                }
            };

            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(openApiDocument);

            validator.Errors.ShouldBeEquivalentTo(
                new List <OpenApiError>
            {
                new OpenApiValidatorError(nameof(OpenApiServerRules.ServerRequiredFields), "#/servers/1/url",
                                          String.Format(SRResource.Validation_FieldIsRequired, "url", "server"))
            });
        }
        public void ValidateExampleAndDefaultShouldNotHaveDataTypeMismatchForSimpleSchema()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            var schema = new OpenApiSchema()
            {
                Example = new OpenApiLong(55),
                Default = new OpenApiPassword("1234"),
                Type    = "string",
            };

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(schema);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            result.Should().BeFalse();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage
            });
            errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[]
            {
                "#/default",
                "#/example",
            });
        }
Пример #3
0
        public void ValidateExampleShouldNotHaveDataTypeMismatchForSimpleSchema()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            var header = new OpenApiHeader()
            {
                Required = true,
                Example  = new OpenApiInteger(55),
                Schema   = new OpenApiSchema()
                {
                    Type = "string",
                }
            };

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(header);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            result.Should().BeFalse();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                RuleHelpers.DataTypeMismatchedErrorMessage
            });
            errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[]
            {
                "#/example",
            });
        }
Пример #4
0
        private static OpenApiDocument GetOpenApiDocument(string url)
        {
            HttpClient httpClient = CreateHttpClient();

            var response = httpClient.GetAsync(url)
                           .GetAwaiter().GetResult();

            if (!response.IsSuccessStatusCode)
            {
                throw new Exception("Failed to retrieve OpenApi document");
            }

            var stream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();;

            var newrules = ValidationRuleSet.GetDefaultRuleSet().Rules
                           .Where(r => r.GetType() != typeof(ValidationRule <OpenApiSchema>)).ToList();


            var reader = new OpenApiStreamReader(new OpenApiReaderSettings()
            {
                RuleSet = new ValidationRuleSet(newrules)
            });
            var openApiDoc = reader.Read(stream, out var diagnostic);

            if (diagnostic.Errors.Count > 0)
            {
                throw new Exception("OpenApi document has errors : " + String.Join("\n", diagnostic.Errors));
            }
            return(openApiDoc);
        }
Пример #5
0
        private string ConvertToOpenAPI(string text)
        {
            Stream stream = CreateStream(text);

            var document = new OpenApiStreamReader(new OpenApiReaderSettings
            {
                ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences,
                RuleSet             = ValidationRuleSet.GetDefaultRuleSet()
            }
                                                   ).Read(stream, out var context);

            if (context.Errors.Any())
            {
                var errorReport = new StringBuilder();

                foreach (var error in context.Errors)
                {
                    errorReport.AppendLine(error.ToString());
                }

                throw new ConversionException(errorReport.ToString());
            }

            return(WriteContents(document));
        }
Пример #6
0
        internal static async void ValidateOpenApiDocument(string openapi, LogLevel loglevel)
        {
            if (string.IsNullOrEmpty(openapi))
            {
                throw new ArgumentNullException(nameof(openapi));
            }
            var logger = ConfigureLoggerInstance(loglevel);
            var stream = await GetStream(openapi, logger);

            OpenApiDocument document;

            logger.LogTrace("Parsing the OpenApi file");
            document = new OpenApiStreamReader(new OpenApiReaderSettings
            {
                RuleSet = ValidationRuleSet.GetDefaultRuleSet()
            }
                                               ).Read(stream, out var context);

            if (context.Errors.Count != 0)
            {
                foreach (var error in context.Errors)
                {
                    Console.WriteLine(error.ToString());
                }
            }

            var statsVisitor = new StatsVisitor();
            var walker       = new OpenApiWalker(statsVisitor);

            walker.Walk(document);

            logger.LogTrace("Finished walking through the OpenApi document. Generating a statistics report..");
            Console.WriteLine(statsVisitor.GetStatisticsReport());
        }
Пример #7
0
        public void ValidateExtensionNameStartsWithXDashInTag()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            OpenApiTag tag = new OpenApiTag
            {
                Name = "tag"
            };

            tag.Extensions.Add("tagExt", new OpenApiString("value"));

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());

            validator.Visit(tag as IOpenApiExtensible);
            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            OpenApiError error = Assert.Single(errors);

            Assert.Equal(String.Format(SRResource.Validation_ExtensionNameMustBeginWithXDash, "tagExt", "#/extensions"), error.Message);
        }
        public void ValidateEnumShouldNotHaveDataTypeMismatchForSimpleSchema()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            var schema = new OpenApiSchema()
            {
                Enum =
                {
                    new OpenApiString("1"),
                    new OpenApiObject()
                    {
                        ["x"] = new OpenApiInteger(2),
                        ["y"] = new OpenApiString("20"),
                        ["z"] = new OpenApiString("200")
                    },
                    new OpenApiArray()
                    {
                        new OpenApiInteger(3)
                    },
                    new OpenApiObject()
                    {
                        ["x"] = new OpenApiInteger(4),
                        ["y"] = new OpenApiInteger(40),
                    },
                },
                Type = "object",
                AdditionalProperties = new OpenApiSchema()
                {
                    Type = "integer",
                }
            };

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(schema);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            result.Should().BeFalse();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
            });
            errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[]
            {
                // #enum/0 is not an error since the spec allows
                // representing an object using a string.
                "#/enum/1/y",
                "#/enum/1/z",
                "#/enum/2"
            });
        }
        /// <summary>
        /// Runs the OpenApiValidator against the OpenApiDocument object. Returns true if the document is valid, false otherwise
        /// </summary>
        /// <param name="doc">The OpenApiDocument to test against</param>
        /// <param name="context"></param>
        /// <returns></returns>
        private void IsValidOpenAPIDocument(OpenApiDocument doc, CustomContext context)
        {
            var openApiValidator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());

            openApiValidator.Visit(doc);
            foreach (var error in openApiValidator.Errors)
            {
                context.AddFailure(error.Message);
            }
        }
        public OpenApiDocument Read(string text)
        {
            var document = new OpenApiStringReader(new OpenApiReaderSettings
            {
                ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences,
                RuleSet             = ValidationRuleSet.GetDefaultRuleSet()
            }).Read(text, out var context);

            return(!_validator.IsValid(document) ? null : document);
        }
Пример #11
0
        private static void ValidateDocument(FileStream stream)
        {
            OpenApiStreamReader reader   = new();
            OpenApiDocument     document = reader.Read(stream, out OpenApiDiagnostic diagnostic);

            Assert.Empty(diagnostic.Errors);

            IEnumerable <OpenApiError> errors = document.Validate(ValidationRuleSet.GetDefaultRuleSet());

            Assert.Empty(errors);
        }
Пример #12
0
    public OpenApiDocument Parse(string json)
    {
        var stream = CreateStream(json);
        var parsed = new OpenApiStreamReader(new OpenApiReaderSettings
        {
            ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences,
            RuleSet             = ValidationRuleSet.GetDefaultRuleSet()
        }).Read(stream, out var openApiDiagnostic);

        Debug.Log("Successfully parsed API Description: " + parsed.Info.Title);
        return(parsed);
    }
        public OpenApiDocument Read(FileInfo input)
        {
            using Stream stream = input.OpenRead();
            var document = new OpenApiStreamReader(new OpenApiReaderSettings
            {
                ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences,
                RuleSet             = ValidationRuleSet.GetDefaultRuleSet()
            }
                                                   ).Read(stream, out var context);

            return(!_validator.IsValid(document) ? null : document);
        }
        public void DefaultRuleSetPropertyReturnsTheCorrectRules()
        {
            // Arrange & Act
            var ruleSet = ValidationRuleSet.GetDefaultRuleSet();

            Assert.NotNull(ruleSet); // guard

            var rules = ruleSet.Rules;

            // Assert
            Assert.NotNull(rules);
            Assert.NotEmpty(rules);

            // Update the number if you add new default rule(s).
            Assert.Equal(23, rules.Count);
        }
Пример #15
0
        public void ValidateFieldIsRequiredInParameter()
        {
            // Arrange
            string nameError = String.Format(SRResource.Validation_FieldIsRequired, "name", "parameter");
            string inError   = String.Format(SRResource.Validation_FieldIsRequired, "in", "parameter");
            var    parameter = new OpenApiParameter();

            // Act
            var errors = parameter.Validate(ValidationRuleSet.GetDefaultRuleSet());

            // Assert
            errors.Should().NotBeEmpty();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                nameError,
                inError
            });
        }
Пример #16
0
        public void ValidateUrlIsRequiredInExternalDocs()
        {
            // Arrange
            OpenApiExternalDocs externalDocs = new OpenApiExternalDocs();

            // Act
            var errors = externalDocs.Validate(ValidationRuleSet.GetDefaultRuleSet());

            // Assert

            bool result = !errors.Any();

            Assert.False(result);
            Assert.NotNull(errors);
            OpenApiError error = Assert.Single(errors);

            Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "url", "External Documentation"), error.Message);
        }
Пример #17
0
        public void ValidateFieldIsRequiredInInfo()
        {
            // Arrange
            string      urlError     = String.Format(SRResource.Validation_FieldIsRequired, "title", "info");
            string      versionError = String.Format(SRResource.Validation_FieldIsRequired, "version", "info");
            OpenApiInfo info         = new OpenApiInfo();

            // Act
            var errors = info.Validate(ValidationRuleSet.GetDefaultRuleSet());

            // Assert
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);

            Assert.Equal(new[] { urlError, versionError }, errors.Select(e => e.Message));
        }
Пример #18
0
        public void ValidateCustomExtension()
        {
            var ruleset = ValidationRuleSet.GetDefaultRuleSet();

            ruleset.Add(
                new ValidationRule <FooExtension>(
                    (context, item) =>
            {
                if (item.Bar == "hey")
                {
                    context.AddError(new OpenApiValidatorError("FooExtensionRule", context.PathString, "Don't say hey"));
                }
            }));

            var openApiDocument = new OpenApiDocument
            {
                Info = new OpenApiInfo()
                {
                    Title   = "foo",
                    Version = "1.2.2"
                },
                Paths = new OpenApiPaths()
            };

            var fooExtension = new FooExtension()
            {
                Bar = "hey",
                Baz = "baz"
            };

            openApiDocument.Info.Extensions.Add("x-foo", fooExtension);

            var validator = new OpenApiValidator(ruleset);
            var walker    = new OpenApiWalker(validator);

            walker.Walk(openApiDocument);

            validator.Errors.Should().BeEquivalentTo(
                new List <OpenApiError>
            {
                new OpenApiValidatorError("FooExtensionRule", "#/info/x-foo", "Don't say hey")
            });
        }
Пример #19
0
        public void ValidateRequiredIsTrueWhenInIsPathInParameter()
        {
            // Arrange
            var parameter = new OpenApiParameter()
            {
                Name = "name",
                In   = ParameterLocation.Path
            };

            // Act
            var errors = parameter.Validate(ValidationRuleSet.GetDefaultRuleSet());

            // Assert
            errors.Should().NotBeEmpty();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                "\"required\" must be true when parameter location is \"path\""
            });
        }
Пример #20
0
        public void ValidateFieldIsRequiredInServer()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            OpenApiServer server = new OpenApiServer();

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());

            validator.Visit(server);
            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            OpenApiError error = Assert.Single(errors);

            Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "url", "server"), error.Message);
        }
        public void ValidateEmailFieldIsEmailAddressInContact()
        {
            // Arrange
            const string testEmail = "support/example.com";

            OpenApiContact contact = new OpenApiContact()
            {
                Email = testEmail
            };

            // Act
            var  errors = contact.Validate(ValidationRuleSet.GetDefaultRuleSet());
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            OpenApiError error = Assert.Single(errors);

            Assert.Equal(String.Format(SRResource.Validation_StringMustBeEmailAddress, testEmail), error.Message);
        }
        public void ValidateSchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator()
        {
            IEnumerable <OpenApiError> errors;
            var components = new OpenApiComponents
            {
                Schemas =
                {
                    {
                        "schema1",
                        new OpenApiSchema
                        {
                            Type          = "object",
                            Discriminator = new OpenApiDiscriminator{
                                PropertyName = "property1"
                            },
                            Reference = new OpenApiReference{
                                Id = "schema1"
                            }
                        }
                    }
                }
            };
            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(components);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            result.Should().BeFalse();
            errors.Should().BeEquivalentTo(new List <OpenApiValidatorError>
            {
                new OpenApiValidatorError(nameof(OpenApiSchemaRules.ValidateSchemaDiscriminator), "#/schemas/schema1/discriminator",
                                          string.Format(SRResource.Validation_SchemaRequiredFieldListMustContainThePropertySpecifiedInTheDiscriminator,
                                                        "schema1", "property1"))
            });
        }
        public void ValidateFieldIsRequiredInLicense()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            OpenApiLicense             license = new OpenApiLicense();

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(license);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            OpenApiError error = Assert.Single(errors);

            Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "name", "license"), error.Message);
        }
Пример #24
0
        public void ResponseMustHaveADescription()
        {
            var openApiDocument = new OpenApiDocument();

            openApiDocument.Info = new OpenApiInfo()
            {
                Title   = "foo",
                Version = "1.2.2"
            };
            openApiDocument.Paths = new OpenApiPaths();
            openApiDocument.Paths.Add(
                "/test",
                new OpenApiPathItem
            {
                Operations =
                {
                    [OperationType.Get] = new OpenApiOperation
                        {
                        Responses =
                        {
                        ["200"] = new OpenApiResponse()
                        }
                        }
                }
            });

            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(openApiDocument);

            validator.Errors.Should().BeEquivalentTo(
                new List <OpenApiError>
            {
                new OpenApiValidatorError(nameof(OpenApiResponseRules.ResponseRequiredFields), "#/paths/~1test/get/responses/200/description",
                                          String.Format(SRResource.Validation_FieldIsRequired, "description", "response"))
            });
        }
        public void ValidateDescriptionIsRequiredInResponse()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            OpenApiResponse            response = new OpenApiResponse();

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(response);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            OpenApiValidatorError error = Assert.Single(errors) as OpenApiValidatorError;

            Assert.Equal(String.Format(SRResource.Validation_FieldIsRequired, "description", "response"), error.Message);
            Assert.Equal("#/description", error.Pointer);
        }
Пример #26
0
        public void ValidateFixedFieldsIsRequiredInResponse()
        {
            // Arrange
            string authorizationUrlError = String.Format(SRResource.Validation_FieldIsRequired, "authorizationUrl", "OAuth Flow");
            string tokenUrlError         = String.Format(SRResource.Validation_FieldIsRequired, "tokenUrl", "OAuth Flow");
            IEnumerable <OpenApiError> errors;
            OpenApiOAuthFlow           oAuthFlow = new OpenApiOAuthFlow();

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(oAuthFlow);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            Assert.False(result);
            Assert.NotNull(errors);
            Assert.Equal(2, errors.Count());
            Assert.Equal(new[] { authorizationUrlError, tokenUrlError }, errors.Select(e => e.Message));
        }
Пример #27
0
        public void PathParameterNotInThePathShouldReturnAnError()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;

            var parameter = new OpenApiParameter()
            {
                Name     = "parameter1",
                In       = ParameterLocation.Path,
                Required = true,
                Schema   = new OpenApiSchema()
                {
                    Type = "string",
                }
            };

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());

            var walker = new OpenApiWalker(validator);

            walker.Walk(parameter);

            errors = validator.Errors;
            bool result = errors.Any();

            // Assert
            result.Should().BeTrue();
            errors.OfType <OpenApiValidatorError>().Select(e => e.RuleName).Should().BeEquivalentTo(new[]
            {
                "PathParameterShouldBeInThePath"
            });
            errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[]
            {
                "#/in"
            });
        }
        public void ValidateDefaultShouldNotHaveDataTypeMismatchForComplexSchema()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;
            var schema = new OpenApiSchema()
            {
                Type       = "object",
                Properties =
                {
                    ["property1"] = new OpenApiSchema()
                            {
                            Type  = "array",
                            Items = new OpenApiSchema()
                            {
                            Type   = "integer",
                            Format = "int64"
                            }
                            },
                    ["property2"] = new OpenApiSchema()
                            {
                            Type  = "array",
                            Items = new OpenApiSchema()
                            {
                            Type = "object",
                            AdditionalProperties = new OpenApiSchema()
                            {
                            Type = "boolean"
                            }
                            }
                            },
                    ["property3"] = new OpenApiSchema()
                            {
                            Type   = "string",
                            Format = "password"
                            },
                    ["property4"] = new OpenApiSchema()
                            {
                            Type = "string"
                            }
                },
                Default = new OpenApiObject()
                {
                    ["property1"] = new OpenApiArray()
                    {
                        new OpenApiInteger(12),
                        new OpenApiLong(13),
                        new OpenApiString("1"),
                    },
                    ["property2"] = new OpenApiArray()
                    {
                        new OpenApiInteger(2),
                        new OpenApiObject()
                        {
                            ["x"] = new OpenApiBoolean(true),
                            ["y"] = new OpenApiBoolean(false),
                            ["z"] = new OpenApiString("1234"),
                        }
                    },
                    ["property3"] = new OpenApiPassword("123"),
                    ["property4"] = new OpenApiDateTime(DateTime.UtcNow)
                }
            };

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());
            var walker    = new OpenApiWalker(validator);

            walker.Walk(schema);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            result.Should().BeFalse();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
            });
            errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[]
            {
                "#/default/property1/0",
                "#/default/property1/2",
                "#/default/property2/0",
                "#/default/property2/1/z",
                "#/default/property4",
            });
        }
Пример #29
0
        public void ValidateExamplesShouldNotHaveDataTypeMismatchForSimpleSchema()
        {
            // Arrange
            IEnumerable <OpenApiError> errors;

            var parameter = new OpenApiParameter()
            {
                Name     = "parameter1",
                In       = ParameterLocation.Path,
                Required = true,
                Schema   = new OpenApiSchema()
                {
                    Type = "object",
                    AdditionalProperties = new OpenApiSchema()
                    {
                        Type = "integer",
                    }
                },
                Examples =
                {
                    ["example0"] = new OpenApiExample()
                        {
                        Value = new OpenApiString("1"),
                        },
                    ["example1"] = new OpenApiExample()
                        {
                        Value = new OpenApiObject()
                        {
                        ["x"] = new OpenApiInteger(2),
                        ["y"] = new OpenApiString("20"),
                        ["z"] = new OpenApiString("200")
                        }
                        },
                    ["example2"] = new OpenApiExample()
                        {
                        Value =
                            new OpenApiArray()
                        {
                        new OpenApiInteger(3)
                        }
                        },
                    ["example3"] = new OpenApiExample()
                        {
                        Value = new OpenApiObject()
                        {
                        ["x"] = new OpenApiInteger(4),
                        ["y"] = new OpenApiInteger(40),
                        }
                        },
                }
            };

            // Act
            var validator = new OpenApiValidator(ValidationRuleSet.GetDefaultRuleSet());

            validator.Enter("{parameter1}");
            var walker = new OpenApiWalker(validator);

            walker.Walk(parameter);

            errors = validator.Errors;
            bool result = !errors.Any();

            // Assert
            result.Should().BeFalse();
            errors.Select(e => e.Message).Should().BeEquivalentTo(new[]
            {
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
                RuleHelpers.DataTypeMismatchedErrorMessage,
            });
            errors.Select(e => e.Pointer).Should().BeEquivalentTo(new[]
            {
                // #enum/0 is not an error since the spec allows
                // representing an object using a string.
                "#/{parameter1}/examples/example1/value/y",
                "#/{parameter1}/examples/example1/value/z",
                "#/{parameter1}/examples/example2/value"
            });
        }
Пример #30
0
        public static void ProcessOpenApiDocument(
            FileInfo input,
            FileInfo output,
            OpenApiSpecVersion version,
            OpenApiFormat format,
            bool inline)
        {
            OpenApiDocument document;

            using (Stream stream = input.OpenRead())
            {
                document = new OpenApiStreamReader(new OpenApiReaderSettings
                {
                    ReferenceResolution = ReferenceResolutionSetting.ResolveLocalReferences,
                    RuleSet             = ValidationRuleSet.GetDefaultRuleSet()
                }
                                                   ).Read(stream, out var context);
                if (context.Errors.Count != 0)
                {
                    var errorReport = new StringBuilder();

                    foreach (var error in context.Errors)
                    {
                        errorReport.AppendLine(error.ToString());
                    }

                    throw new ArgumentException(String.Join(Environment.NewLine, context.Errors.Select(e => e.Message).ToArray()));
                }
            }

            using (var outputStream = output?.Create())
            {
                TextWriter textWriter;

                if (outputStream != null)
                {
                    textWriter = new StreamWriter(outputStream);
                }
                else
                {
                    textWriter = Console.Out;
                }

                var settings = new OpenApiWriterSettings()
                {
                    ReferenceInline = inline == true ? ReferenceInlineSetting.InlineLocalReferences : ReferenceInlineSetting.DoNotInlineReferences
                };
                IOpenApiWriter writer;
                switch (format)
                {
                case OpenApiFormat.Json:
                    writer = new OpenApiJsonWriter(textWriter, settings);
                    break;

                case OpenApiFormat.Yaml:
                    writer = new OpenApiYamlWriter(textWriter, settings);
                    break;

                default:
                    throw new ArgumentException("Unknown format");
                }

                document.Serialize(writer, version);

                textWriter.Flush();
            }
        }