public async Task <IActionResult> GetAsync()
        {
            var baseUri = "http://gateway-api/swagger/docs";
            var client  = new HttpClient();
            var doc     = new OpenApiDocument();

            doc.Paths      = new OpenApiPaths();
            doc.Components = new OpenApiComponents();
            doc.Tags       = new List <OpenApiTag>();

            foreach (var api in _ocelotSwaggerOptions.SwaggerEndpoints)
            {
                var firstConfig = api.Config[0];
                var apiUri      = $"{baseUri}/{firstConfig.Version}/{api.Key}";

                if (firstConfig.Url.StartsWith("http://orderprovider"))
                {
                    apiUri = firstConfig.Url;
                }

                var response = await client.GetAsync(apiUri);

                var responseContent = await response.Content.ReadAsStringAsync();

                var responseDoc = new OpenApiStringReader().Read(responseContent, out var diagnostic);

                foreach (var path in responseDoc.Paths)
                {
                    var pathKey = path.Key;

                    if (firstConfig.Url.StartsWith("http://orderprovider"))
                    {
                        pathKey = $"{path.Key.Replace("/api", "").ToLower()} ({firstConfig.Name})";
                    }

                    doc.Paths.Add(pathKey, path.Value);
                }

                foreach (var schema in responseDoc.Components.Schemas)
                {
                    doc.Components.Schemas.Add(schema.Key, schema.Value);
                }

                foreach (var tag in responseDoc.Tags)
                {
                    doc.Tags.Add(tag);
                }
            }

            string json;

            using (var outputString = new StringWriter())
            {
                var writer = new OpenApiJsonWriter(outputString);
                doc.SerializeAsV3(writer);
                json = outputString.ToString();
            }

            return(Ok(json));
        }
        private static OpenApiDocument LoadOpenApiDocument(string json)
        {
            var             reader   = new OpenApiStringReader();
            OpenApiDocument document = reader.Read(json, out OpenApiDiagnostic _);

            return(document);
        }
        public void ShouldThrowWhenReferenceDoesNotExist()
        {
            var input = @"
swagger: 2.0
info: 
  title: test
  version: 1.0.0
paths: 
  '/':
    get:
      produces: ['application/json']
      responses:
        '200':
          description: ok
          schema:
            $ref: '#/definitions/doesnotexist'
";

            var reader = new OpenApiStringReader();

            var doc = reader.Read(input, out var diagnostic);

            diagnostic.Errors.ShouldBeEquivalentTo(new List <OpenApiError> {
                new OpenApiError(new OpenApiException("Invalid Reference identifier 'doesnotexist'."))
            });
            doc.Should().NotBeNull();
        }
        public void ShouldThrowWhenReferenceTypeIsInvalid()
        {
            var input = @"
swagger: 2.0
info: 
  title: test
  version: 1.0.0
paths: 
  '/':
    get:
      responses:
        '200':
          description: ok
          schema:
            $ref: '#/defi888nition/does/notexist'
";

            var reader = new OpenApiStringReader();
            var doc    = reader.Read(input, out var diagnostic);

            diagnostic.Errors.ShouldBeEquivalentTo(new List <OpenApiError> {
                new OpenApiError(new OpenApiException("Unknown reference type 'defi888nition'"))
            });
            doc.Should().NotBeNull();
        }
Esempio n. 5
0
        public void ParseExampleStringFragmentShouldSucceed()
        {
            var input      = @"
{ 
  ""foo"": ""bar"",
  ""baz"": [ 1,2]
}";
            var reader     = new OpenApiStringReader();
            var diagnostic = new OpenApiDiagnostic();

            // Act
            var openApiAny = reader.ReadFragment <IOpenApiAny>(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic);

            // Assert
            diagnostic.ShouldBeEquivalentTo(new OpenApiDiagnostic());

            openApiAny.ShouldBeEquivalentTo(
                new OpenApiObject
            {
                ["foo"] = new OpenApiString("bar"),
                ["baz"] = new OpenApiArray()
                {
                    new OpenApiInteger(1),
                    new OpenApiInteger(2)
                }
            });
        }
Esempio n. 6
0
        public void MultipleServers()
        {
            var input  = @"
swagger: 2.0
info: 
  title: test
  version: 1.0.0
schemes:
  - http
  - https
paths: {}
";
            var reader = new OpenApiStringReader(new OpenApiReaderSettings()
            {
                BaseUrl = new Uri("https://dev.bing.com/api")
            });

            var doc = reader.Read(input, out var diagnostic);

            var server = doc.Servers.First();

            Assert.Equal(2, doc.Servers.Count);
            Assert.Equal("http://dev.bing.com/api", server.Url);
            Assert.Equal("https://dev.bing.com/api", doc.Servers.Last().Url);
        }
Esempio n. 7
0
        public void ParsePrimitiveStringSchemaFragmentShouldSucceed()
        {
            var input      = @"
{ ""type"": ""integer"",
""format"": ""int64"",
""default"": 88
}
";
            var reader     = new OpenApiStringReader();
            var diagnostic = new OpenApiDiagnostic();

            // Act
            var schema = reader.ReadFragment <OpenApiSchema>(input, OpenApiSpecVersion.OpenApi3_0, out diagnostic);

            // Assert
            diagnostic.ShouldBeEquivalentTo(new OpenApiDiagnostic());

            schema.ShouldBeEquivalentTo(
                new OpenApiSchema
            {
                Type    = "integer",
                Format  = "int64",
                Default = new OpenApiInteger(88)
            });
        }
Esempio n. 8
0
        public void InvalidHostShouldYieldError()
        {
            var input  = @"
swagger: 2.0
info: 
  title: test
  version: 1.0.0
host: http://test.microsoft.com
paths: {}
";
            var reader = new OpenApiStringReader(new OpenApiReaderSettings()
            {
                BaseUrl = new Uri("https://bing.com")
            });

            var doc = reader.Read(input, out var diagnostic);

            doc.Servers.Count.Should().Be(0);
            diagnostic.Should().BeEquivalentTo(
                new OpenApiDiagnostic
            {
                Errors =
                {
                    new OpenApiError("#/", "Invalid host")
                },
                SpecificationVersion = OpenApiSpecVersion.OpenApi2_0
            });
        }
Esempio n. 9
0
        public void ExecuteContractWithAnotherFormatWordHealth(string healthPath)
        {
            var contractWithHealthCheck =
                @"openapi: 3.0.0
info:
  title: heatlh
  version: '1.0'
servers:
  - url: 'http://*****:*****@": 
    get:
      summary: Your GET endpoint
      tags: []
      responses:
        '200':
          description: OK
      operationId: get-health-check
  /clientes:
    get:
      summary: Your GET endpoint
      tags: []
      responses:
        '200':
          description: OK
      operationId: get-clientes
components:
  schemas: {}
";
            var openApiContractWithHealthCheck = new OpenApiStringReader().Read(contractWithHealthCheck, out OpenApiDiagnostic _);

            List <ResultItem> results = new HealthCheckRule(openApiContractWithHealthCheck, supressions, ruleSettings, cache).Execute();

            Assert.Equal("Adicione um Health Check na sua API.", results[0].Description);
        }
Esempio n. 10
0
        public void BadSchema()
        {
            var input = @"openapi: 3.0.0
info:
  title: foo
  version: bar
paths:
  '/foo':
    get:
      responses:
        200: 
          description: ok
          content:
            application/json:  
              schema: asdasd
";

            var reader = new OpenApiStringReader();

            reader.Read(input, out var diagnostic);

            diagnostic.Errors.Should().BeEquivalentTo(new List <OpenApiError>()
            {
                new OpenApiError(new OpenApiReaderException("schema must be a map/object")
                {
                    Pointer = "#/paths/~1foo/get/responses/200/content/application~1json/schema"
                })
            });
        }
Esempio n. 11
0
        public OpenApiDocument ConvertToOpenAPISpec(string json)
        {
            OpenApiStringReader reader = new OpenApiStringReader();
            OpenApiDocument     doc    = reader.Read(json, out var diagnostic);

            return(doc);
        }
Esempio n. 12
0
        public static KindSchema FromKindDefinition(ResourceDefinition resourceDefinition)
        {
            var reader         = new OpenApiStringReader();
            var metadataSchema = reader.ReadFragment <OpenApiSchema>(resourceDefinition["metadataSchema"]?.GetString() ?? throw new MissingResourceFieldException("metadataSchema"),
                                                                     Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0, out var _);

            var definitionSchema = reader.ReadFragment <OpenApiSchema>(resourceDefinition["definitionSchema"]?.GetString() ?? throw new MissingResourceFieldException("definitionSchema"),
                                                                       Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0, out var _);

            var specSchema  = default(OpenApiSchema);
            var stateSchema = default(OpenApiSchema);

            if (resourceDefinition["specSchema"] != null)
            {
                specSchema = reader.ReadFragment <OpenApiSchema>(resourceDefinition["specSchema"].GetString(),
                                                                 Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0, out var _);
            }

            if (resourceDefinition["stateSchema"] != null)
            {
                stateSchema = reader.ReadFragment <OpenApiSchema>(resourceDefinition["stateSchema"].GetString(),
                                                                  Microsoft.OpenApi.OpenApiSpecVersion.OpenApi3_0, out var _);
            }

            return(new KindSchema(metadataSchema, definitionSchema, specSchema, stateSchema));
        }
Esempio n. 13
0
        public void ParseCustomExtension()
        {
            var description = @"
openapi: 3.0.0
info: 
    title: A doc with an extension
    version: 1.0.0
    x-foo: 
        bar: hey
        baz: hi!
paths: {}
";
            var settings    = new OpenApiReaderSettings()
            {
                ExtensionParsers = { { "x-foo", (a, v) => {
                                           var fooNode = (OpenApiObject)a;
                                           return(new FooExtension()
                            {
                                Bar = (fooNode["bar"] as OpenApiString)?.Value,
                                Baz = (fooNode["baz"] as OpenApiString)?.Value
                            });
                                       } } }
            };

            var reader = new OpenApiStringReader(settings);

            var diag = new OpenApiDiagnostic();
            var doc  = reader.Read(description, out diag);

            var fooExtension = doc.Info.Extensions["x-foo"] as FooExtension;

            fooExtension.Should().NotBeNull();
            fooExtension.Bar.Should().Be("hey");
            fooExtension.Baz.Should().Be("hi!");
        }
        public void InvalidDocumentationShouldYieldFailure(
            string testCaseName,
            IList <string> inputXmlFiles,
            IList <string> inputBinaryFiles,
            int expectedOperationGenerationResultsCount,
            string expectedJsonFile,
            DocumentGenerationDiagnostic expectedDocumentGenerationResult,
            IList <OperationGenerationDiagnostic> expectedFailureOperationGenerationResults)
        {
            _output.WriteLine(testCaseName);

            var documents = new List <XDocument>();

            documents.AddRange(inputXmlFiles.Select(XDocument.Load));

            var input = new OpenApiGeneratorConfig(documents, inputBinaryFiles, "1.0.0", FilterSetVersion.V1);

            GenerationDiagnostic result;

            var generator = new OpenApiGenerator();

            var openApiDocuments = generator.GenerateDocuments(input, out result);

            openApiDocuments.Should().NotBeNull();

            result.DocumentGenerationDiagnostic.Should().BeEquivalentTo(expectedDocumentGenerationResult);
            result.OperationGenerationDiagnostics.Count.Should().Be(expectedOperationGenerationResultsCount);

            openApiDocuments[DocumentVariantInfo.Default].Should().NotBeNull();

            var failurePaths = result.OperationGenerationDiagnostics.Where(
                p => p.Errors.Count > 0)
                               .ToList();

            var actualDocument = openApiDocuments[DocumentVariantInfo.Default]
                                 .SerializeAsJson(OpenApiSpecVersion.OpenApi3_0);
            var expectedDocument = File.ReadAllText(expectedJsonFile);


            _output.WriteLine(actualDocument);

            failurePaths.Should().BeEquivalentTo(expectedFailureOperationGenerationResults);

            // We are doing serialization and deserialization to force the resulting actual document
            // to have the exact fields we will see in the resulting document based on the contract resolver.
            // Without serialization and deserialization, the actual document may have fields that should
            // not be present, such as empty list fields.
            var openApiStringReader = new OpenApiStringReader();

            var actualDeserializedDocument = openApiStringReader.Read(
                actualDocument,
                out OpenApiDiagnostic diagnostic);

            diagnostic.Errors.Count.Should().Be(0);

            actualDeserializedDocument
            .Should()
            .BeEquivalentTo(openApiStringReader.Read(expectedDocument, out var _));
        }
Esempio n. 15
0
        private static OpenApiDocument Deserialize(string data)
        {
            var reader = new OpenApiStringReader(new OpenApiReaderSettings().AddTypedRest());
            var doc    = reader.Read(data, out _);

            doc.GetTypedRest(); // Resolves references
            return(doc);
        }
Esempio n. 16
0
        public Result Validate(string oasContent, List <Supression> supressionList = null)
        {
            OpenApiDocument openApiContract = new OpenApiStringReader().Read(oasContent, out OpenApiDiagnostic diagnostic);

            if (diagnostic.Errors.Count > 0)
            {
                throw new InvalidOpenApiDocumentException(diagnostic.Errors);
            }

            var supressions = new Supressions(supressionList);

            var analisysResult = new Result();

            //TODO revisar o modelo de "percorrer em loop desde o path", pois é possível validar as definitions na raiz do contrato e não revalidá-las toda as vezes path por path.

            //Error
            analisysResult.ResultItens.TryAddEmptiableRange(new VersionFormatRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new BaseUrlRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PathTrailingSlashRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new DoubleSlashesRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new ContentEnvelopeRule(openApiContract, supressions, ruleSettings, cache).Execute());

            //Warnings
            analisysResult.ResultItens.TryAddEmptiableRange(new NestingDepthRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PathCaseRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PathPluralRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PathParameterRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PathAndIdStructureRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PathWithCrudNamesRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new IdPropertyResponseRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PropertyCaseRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new OperationSuccessResponseRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new Empty200Rule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new ContentIn204Rule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new Http3xxWithoutLocationHeaderRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PaginationEnvelopeFormatRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new MessagesEnvelopeFormatRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new ErrorResponseFormatRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new ValidResponseCodesRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new Http201WithoutContentLocationHeaderRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new ResponseWithout4xxAnd500Rule(openApiContract, supressions, ruleSettings, cache).Execute());

            //Information
            analisysResult.ResultItens.TryAddEmptiableRange(new InfoContactRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new DescriptionRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new DescriptionQualityRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new EmptyExamplesRule(openApiContract, supressions, ruleSettings, cache).Execute());
            //TODO Checar se os exemplos são válidos em relação aos schemas. Verificar também o tipo de dado deles. Inspiração: EmptyExamplesRule > Newtonsoft.Json. Lembrete: se vazio, ignora.

            //Hints
            analisysResult.ResultItens.TryAddEmptiableRange(new PropertyStartingWithTypeRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new PropertyNamingMatchingPathRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new StringCouldBeNumberRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new DateWithoutFormatRule(openApiContract, supressions, ruleSettings, cache).Execute());
            analisysResult.ResultItens.TryAddEmptiableRange(new Http200WithoutPaginationRule(openApiContract, supressions, ruleSettings, cache).Execute());

            return(analisysResult);
        }
Esempio n. 17
0
        /// <summary>
        /// This method is only needed because the output of ConvertToOpenApi isn't quite a valid OpenApiDocument instance.
        /// So we write it out, and read it back in again to fix it up
        /// </summary>
        /// <param name="document">The OpenAPI document to be actioned.</param>
        /// <returns></returns>
        private static OpenApiDocument FixReferences(OpenApiDocument document)
        {
            var sb = new StringBuilder();

            document.SerializeAsV3(new OpenApiYamlWriter(new StringWriter(sb)));
            var doc = new OpenApiStringReader().Read(sb.ToString(), out _);

            return(doc);
        }
        public static IEnumerable <object[]> GetTestCasesForXElementExtensionExampleShouldSucceed()
        {
            yield return(new object[]
            {
                "Empty example element",
                XElement.Parse("<parent><example></example></parent>"),
                new Dictionary <string, FieldValueInfo>(),
                new Dictionary <string, OpenApiExample>()
            });

            yield return(new object[]
            {
                "Example with url",
                XElement.Parse(
                    "<parent><example><summary>Test Example</summary><url>https://localhost/test.json</url></example></parent>"),
                new Dictionary <string, FieldValueInfo>(),
                new Dictionary <string, OpenApiExample>()
                {
                    {
                        "example1",
                        new OpenApiExample
                        {
                            ExternalValue = "https://localhost/test.json",
                            Summary = "Test Example"
                        }
                    }
                }
            });

            yield return(new object[]
            {
                "Example element with cref",
                XElement.Parse(@"<parent><example name=""BodyExample"">"
                               + @"<value><see cref=""F:Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.Examples.SampleObject1Example""/></value></example></parent>"),
                new Dictionary <string, FieldValueInfo>()
                {
                    {
                        "F:Microsoft.OpenApi.CSharpAnnotations.DocumentGeneration.Tests.Contracts.Examples.SampleObject1Example",
                        new FieldValueInfo
                        {
                            Value = ExpectedExamples.SampleObject1Example
                        }
                    }
                },
                new Dictionary <string, OpenApiExample>()
                {
                    {
                        "BodyExample",
                        new OpenApiExample {
                            Value = new OpenApiStringReader().ReadFragment <IOpenApiAny>(
                                ExpectedExamples.SampleObject1Example,
                                OpenApiSpecVersion.OpenApi3_0,
                                out OpenApiDiagnostic _)
                        }
                    }
                }
            });
        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);
        }
Esempio n. 20
0
        private static OpenApiDocument FixReferences(OpenApiDocument document)
        {
            // This method is only needed because the output of ConvertToOpenApi isn't quite a valid OpenApiDocument instance.
            // So we write it out, and read it back in again to fix it up.
            var sb = new StringBuilder();

            document.SerializeAsV3(new OpenApiYamlWriter(new StringWriter(sb)));
            var doc = new OpenApiStringReader().Read(sb.ToString(), out var diag);

            return(doc);
        }
Esempio n. 21
0
        public void ExecuteContractWithHealthCheck()
        {
            var contractWithHealthCheck =
                "{\n  \"swagger\" : \"2.0\",\n  \"info\" : {\n    \"version\" : \"v1\",\n    \"title\" : \"Swagger Test\",\n  },\n  \"consumes\" : [ \"application/json\" ],\n  \"produces\" : [ \"application/json\" ],\n  \"paths\" : {\n    \"/health\" : {\n      \"get\" : {\n        \"responses\" : {\n          \"200\" : {\n            \"description\" : \"\",\n            \"schema\" : {\n              \"type\" : \"object\",\n              \"properties\" : {\n                \"data\" : {\n                  \"type\" : \"object\",\n                  \"properties\" : {\n                    \"propertyOne\" : {\n                      \"type\" : \"string\"\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/apagar-path-two\" : {\n      \"get\" : {\n        \"responses\" : {\n          \"200\" : {\n            \"description\": \"Status 200\",\n            \"schema\" : {\n              \"type\" : \"object\",\n              \"properties\" : {\n                \"data\" : {\n                  \"type\" : \"object\",\n                  \"properties\" : {\n                    \"propertyOne\" : {\n                      \"type\" : \"string\"\n                    }\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}";

            var openApiContractWithHealthCheck = new OpenApiStringReader().Read(contractWithHealthCheck, out OpenApiDiagnostic _);

            List <ResultItem> results = new HealthCheckRule(openApiContractWithHealthCheck, supressions, ruleSettings, cache).Execute();

            Assert.Empty(results);
        }
Esempio n. 22
0
        public override IEnumerable <object[]> GetData(MethodInfo testMethod)
        {
            var openApiDoc = new OpenApiStringReader().Read(File.ReadAllText(_specLocation), out var _);

            foreach (var path in openApiDoc.Paths)
            {
                foreach (var operation in path.Value.Operations)
                {
                    yield return(new object[] { OperationToMethod(operation.Key), path.Key });
                }
            }
        }
        /// <summary>
        /// Reads json into an OpenApiDocument Object using the OpenApiStringReader from Microsoft.OpenApi.Readers
        /// </summary>
        /// <param name="reader">The JsonReader that reads the incoming json</param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            var openApiStringReader = new OpenApiStringReader();
            var openApiString       = JObject.Load(reader).ToString();
            var openApiDocument     = openApiStringReader.Read(openApiString, out var diagnostic);

            openApiDocument.Tags.Add(new OpenApiTag()
            {
                Name = "openapi", Description = diagnostic.SpecificationVersion.ToString()
            });
            return(openApiDocument);
        }
Esempio n. 24
0
        public void GivenTheSchema(string schema)
        {
            var           reader        = new OpenApiStringReader();
            OpenApiSchema openApiSchema = reader.ReadFragment <OpenApiSchema>(schema, OpenApiSpecVersion.OpenApi3_0, out OpenApiDiagnostic diagnostic);

            if (diagnostic.Errors.Count > 0)
            {
                throw new ArgumentException("Invalid schema", nameof(schema));
            }

            this.scenarioContext.Set(openApiSchema);
        }
        /// <summary>
        /// Deserializes the json to a<see cref="OpenApiDocument"/>
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public static OpenApiDocument ReadFromJson(string json)
        {
            var openApiReader = new OpenApiStringReader();
            var document      = openApiReader.Read(json, out var diagnostic);

            if (diagnostic.Errors.Count > 0)
            {
                throw new JsonReaderException("Error reading OpenApi document. " + string.Join(Environment.NewLine, diagnostic.Errors.Select(e => e.Message)));
            }

            return(document);
        }
        public void ValidDocumentationShouldReturnCorrectDocument(
            string testCaseName,
            IList <string> inputXmlFiles,
            IList <string> inputBinaryFiles,
            string openApiDocumentVersion,
            int expectedOperationGenerationResultsCount,
            string expectedJsonFile)
        {
            _output.WriteLine(testCaseName);

            var documents = new List <XDocument>();

            documents.AddRange(inputXmlFiles.Select(XDocument.Load));

            var input = new OpenApiGeneratorConfig(
                documents,
                inputBinaryFiles,
                openApiDocumentVersion,
                FilterSetVersion.V1);

            GenerationDiagnostic result;

            var generator        = new OpenApiGenerator();
            var openApiDocuments = generator.GenerateDocuments(input, out result);

            result.Should().NotBeNull();

            result.DocumentGenerationDiagnostic.Errors.Count.Should().Be(0);

            openApiDocuments[DocumentVariantInfo.Default].Should().NotBeNull();

            result.OperationGenerationDiagnostics.Count(p => p.Errors.Count > 0).Should().Be(0);
            result.OperationGenerationDiagnostics.Count.Should().Be(expectedOperationGenerationResultsCount);

            var actualDocument = openApiDocuments[DocumentVariantInfo.Default]
                                 .SerializeAsJson(OpenApiSpecVersion.OpenApi3_0);
            var expectedDocument = File.ReadAllText(expectedJsonFile);

            _output.WriteLine(actualDocument);

            var openApiStringReader = new OpenApiStringReader();

            var actualDeserializedDocument = openApiStringReader.Read(
                actualDocument,
                out OpenApiDiagnostic diagnostic);

            diagnostic.Errors.Count.Should().Be(0);

            actualDeserializedDocument
            .Should()
            .BeEquivalentTo(openApiStringReader.Read(expectedDocument, out var _));
        }
Esempio n. 27
0
        public void GenerateDocumentWithOperationConfigShouldSucceed(
            string testCaseName,
            IList <string> inputXmlFiles,
            IList <string> inputBinaryFiles,
            string configXmlFile,
            int expectedOperationGenerationResultsCount,
            string expectedJsonFile)
        {
            _output.WriteLine(testCaseName);

            var documents = new List <XDocument>();

            documents.AddRange(inputXmlFiles.Select(XDocument.Load));
            var configDocument = XDocument.Load(configXmlFile);

            var generator = new OpenApiGenerator();
            var input     = new OpenApiGeneratorConfig(documents, inputBinaryFiles, "1.0.0", FilterSetVersion.V1)
            {
                AdvancedConfigurationXmlDocument = configDocument
            };

            GenerationDiagnostic result;

            var openApiDocuments = generator.GenerateDocuments(
                input,
                out result);

            result.Should().NotBeNull();
            result.DocumentGenerationDiagnostic.Errors.Count.Should().Be(0);
            openApiDocuments[DocumentVariantInfo.Default].Should().NotBeNull();
            result.OperationGenerationDiagnostics.Count.Should().Be(expectedOperationGenerationResultsCount);

            var actualDocument = openApiDocuments[DocumentVariantInfo.Default]
                                 .SerializeAsJson(OpenApiSpecVersion.OpenApi3_0);
            var expectedDocument = File.ReadAllText(expectedJsonFile);

            _output.WriteLine(actualDocument);

            var openApiStringReader = new OpenApiStringReader();

            var actualDeserializedDocument = openApiStringReader.Read(
                actualDocument,
                out OpenApiDiagnostic diagnostic);

            diagnostic.Errors.Count.Should().Be(0);

            actualDeserializedDocument
            .Should()
            .BeEquivalentTo(
                openApiStringReader.Read(expectedDocument, out var _),
                o => o.WithStrictOrdering());
        }
Esempio n. 28
0
        public void Read(string filename, List <ITransferObject> transferObjects)
        {
            if (!FileSystem.FileExists(filename))
            {
                return;
            }
            string json = FileSystem.ReadAllText(filename);
            OpenApiStringReader reader   = new OpenApiStringReader();
            OpenApiDocument     document = reader.Read(json, out OpenApiDiagnostic diagnostic);

            diagnostic.Errors?.ForEach(error => Logger.Error(error.Message));
            transferObjects.Add(TransferObject.Create(document));
        }
Esempio n. 29
0
        public void Can_Write_OpenApiDocument_To_Json()
        {
            var document = new ApiDocumentBuilder().Build();
            var json     = JsonConvert.SerializeObject(document, new OpenApiDocumentJsonConverter());

            var reader      = new OpenApiStringReader();
            var newDocument = reader.Read(json, out var diagnostic);

            diagnostic.Errors.Should().BeEmpty();

            newDocument.Should().NotBeNull();
            newDocument.Info.Should().NotBeNull();
            newDocument.Info.Title.Should().Be("My Api");
        }
        public async Task <ActionResult> Get(string uri)
        {
            using var httpClient = new HttpClient();

            var str = await httpClient.GetStringAsync(uri);

            // Read V3 as YAML
            var openApiDocument = new OpenApiStringReader().Read(str, out var diagnostic); // new OpenApiStreamReader().Read(stream, out var diagnostic);

            // Write V2 as JSON
            var outputString = openApiDocument.Serialize(OpenApiSpecVersion.OpenApi2_0, OpenApiFormat.Json);

            return(Ok(openApiDocument));
        }