Exemple #1
0
        public void ReadMetadata_WithNoResponses_ReturnsApiDefinition()
        {
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""paths"": {
    ""/pets"": {
      ""post"": {
        ""summary"": ""Create a pet"",
        ""operationId"": ""createPets"",
        ""requestBody"": {
          ""content"": {

          }
        }
      }
    }
  }
}";

            OpenApiDotNetApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(json, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Single(apiDefinition.DirectoryStructure.DirectoryNames);
            Assert.Equal("pets", apiDefinition.DirectoryStructure.DirectoryNames.Single());

            IDirectoryStructure subDirectory = apiDefinition.DirectoryStructure.TraverseTo("/pets");

            Assert.Single(subDirectory.RequestInfo.Methods);
            Assert.Contains("Post", subDirectory.RequestInfo.Methods, StringComparer.Ordinal);
        }
        public void ReadMetadata_WithSpecifiedMethodName_ReturnsApiDefinitionWithCorrectNumberOfRequestMethods(string method, bool shouldHaveRequest)
        {
            string  json    = @"{
  ""openapi"": ""3.0.0"",
  ""paths"": {
    ""/pets"": {
      """ + method + @""": """"
    }
  }
}";
            JObject jobject = JObject.Parse(json);
            OpenApiV3ApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiV3ApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(jobject, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Single(apiDefinition.DirectoryStructure.DirectoryNames);
            Assert.Equal("pets", apiDefinition.DirectoryStructure.DirectoryNames.Single());

            IDirectoryStructure subDirectory = apiDefinition.DirectoryStructure.TraverseTo("/pets");

            if (shouldHaveRequest)
            {
                Assert.Single(subDirectory.RequestInfo.Methods);
                Assert.Contains(method, subDirectory.RequestInfo.Methods, StringComparer.Ordinal);
            }
            else
            {
                Assert.Null(subDirectory.RequestInfo);
            }
        }
        public void ReadDefinition_WithOneServer_BaseAddressesHasOneEntry()
        {
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""version"": ""v1""
  },
  ""servers"": [
    {
      ""url"": ""https://localhost/"",
      ""description"": ""First Server Address""
    }
  ],
  ""paths"": {
    ""/pets"": {
    }
  }
}";

            JObject jobject = JObject.Parse(json);
            OpenApiV3ApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiV3ApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(jobject, null);

            Assert.NotNull(apiDefinition?.BaseAddresses);
            Assert.Single(apiDefinition.BaseAddresses);
            Assert.Equal("https://localhost/", apiDefinition.BaseAddresses[0].Url.ToString());
            Assert.Equal("First Server Address", apiDefinition.BaseAddresses[0].Description);
        }
Exemple #4
0
        public ApiResponse <ApiDefinitionModel> Post([FromRoute] Guid packageId, [FromBody] ApiDefinitionModel request)
        {
            // Create the response object
            ApiResponse <ApiDefinitionModel> response = new ApiResponse <ApiDefinitionModel>();

            // Map the model to a domain object type
            ApiDefinition savedApiDefinition = mapper.Map <ApiDefinition>(request);

            // Did the mapping work ok?
            if (savedApiDefinition != null)
            {
                // Did we find a package?
                Package package = SessionHandler.PackageRepository.Get(packageId);
                if (package != null)
                {
                    // Get the repository to save the package for us
                    savedApiDefinition = package.Save <ApiDefinition>(savedApiDefinition);
                }

                // Saved ok?
                if (savedApiDefinition != null)
                {
                    // Map the api definition back to a model type and send it back to the user
                    response.Data = mapper.Map <ApiDefinitionModel>(savedApiDefinition);
                }

                // Nothing died .. Success
                response.Success = true;
            }

            // Send the response back
            return(response);
        }
Exemple #5
0
        public void GetApplicableContentTypes_WithPath_ReturnsCorrectOne()
        {
            DirectoryStructure parentDirectoryStructure = new DirectoryStructure(null);
            RequestInfo        parentRequestInfo        = new RequestInfo();

            parentRequestInfo.SetRequestBody("GET", "application/json", "");
            parentDirectoryStructure.RequestInfo = parentRequestInfo;
            DirectoryStructure childDirectoryStructure = parentDirectoryStructure.DeclareDirectory("child");
            RequestInfo        childRequestInfo        = new RequestInfo();

            childRequestInfo.SetRequestBody("GET", "application/xml", "");
            childDirectoryStructure.RequestInfo = childRequestInfo;

            HttpState httpState = SetupHttpState();

            httpState.BaseAddress = new Uri("https://localhost/");
            ApiDefinition apiDefinition = new ApiDefinition();

            apiDefinition.DirectoryStructure = parentDirectoryStructure;
            httpState.ApiDefinition          = apiDefinition;

            IEnumerable <string> result = httpState.GetApplicableContentTypes("GET", "child");

            Assert.Single(result);
            Assert.Contains("application/xml", result, StringComparer.OrdinalIgnoreCase);
        }
Exemple #6
0
        public void ReadDefinition_WithHostAndTwoSchemes_BaseAddressesHasTwoEntries()
        {
            string json = @"{
  ""swagger"": ""2.0"",
  ""info"": {
    ""version"": ""v1""
  },
  ""host"": ""localhost"",
  ""schemes"": [
    ""https"",
    ""http""
  ],
  ""paths"": {
  }
}";

            OpenApiDotNetApiDefinitionReader swaggerV2ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = swaggerV2ApiDefinitionReader.ReadDefinition(json, new Uri("http://localhost/swagger.json"));

            Assert.NotNull(apiDefinition?.BaseAddresses);
            Assert.Equal(2, apiDefinition.BaseAddresses.Count);
            Assert.Equal("https://localhost/", apiDefinition.BaseAddresses[0].Url.ToString(), StringComparer.Ordinal);
            Assert.Equal("http://localhost/", apiDefinition.BaseAddresses[1].Url.ToString(), StringComparer.Ordinal);
        }
Exemple #7
0
        public void GetApplicableContentTypes_NoMethod_ReturnsAll()
        {
            DirectoryStructure directoryStructure = new DirectoryStructure(null);
            RequestInfo        requestInfo        = new RequestInfo();

            requestInfo.SetRequestBody("GET", "application/json", "");
            requestInfo.SetRequestBody("PUT", "application/xml", "");
            directoryStructure.RequestInfo = requestInfo;

            HttpState httpState = SetupHttpState();

            httpState.BaseAddress = new Uri("https://localhost/");
            ApiDefinition apiDefinition = new ApiDefinition();

            apiDefinition.DirectoryStructure = directoryStructure;
            httpState.ApiDefinition          = apiDefinition;

            IEnumerable <string> result = httpState.GetApplicableContentTypes(null, "");

            Assert.NotNull(result);

            Assert.Equal(2, result.Count());
            Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase);
            Assert.Contains("application/xml", result, StringComparer.OrdinalIgnoreCase);
        }
        public void GetValueCompletions_NoMethod_ReturnsAll()
        {
            DirectoryStructure directoryStructure = new DirectoryStructure(null);
            RequestInfo        requestInfo        = new RequestInfo();

            requestInfo.SetRequestBody("GET", "application/json", "");
            requestInfo.SetRequestBody("GET", "text/plain", "");
            requestInfo.SetRequestBody("PUT", "application/xml", "");
            directoryStructure.RequestInfo = requestInfo;

            HttpState httpState = SetupHttpState();

            httpState.BaseAddress = new Uri("https://localhost/");
            ApiDefinition apiDefinition = new ApiDefinition();

            apiDefinition.DirectoryStructure = directoryStructure;
            httpState.ApiDefinition          = apiDefinition;

            IEnumerable <string> result = HeaderCompletion.GetValueCompletions(method: null, path: "", header: "Content-Type", "", httpState);

            Assert.Equal(3, result.Count());
            Assert.Contains("application/json", result, StringComparer.OrdinalIgnoreCase);
            Assert.Contains("text/plain", result, StringComparer.OrdinalIgnoreCase);
            Assert.Contains("application/xml", result, StringComparer.OrdinalIgnoreCase);
        }
Exemple #9
0
        public void ReadDefinition_WithHostAndNoScheme_BaseAddressesHasOneEntryWithSchemeFromSourceUri()
        {
            string json = @"{
  ""swagger"": ""2.0"",
  ""info"": {
    ""version"": ""v1""
  },
  ""host"": ""localhost"",
  ""paths"": {
  }
}";

            OpenApiDotNetApiDefinitionReader swaggerV2ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = swaggerV2ApiDefinitionReader.ReadDefinition(json, new Uri("https://localhost/swagger.json"));

            Assert.NotNull(apiDefinition?.BaseAddresses);
            Assert.Single(apiDefinition.BaseAddresses);
            Assert.Equal("https://localhost/", apiDefinition.BaseAddresses[0].Url.ToString(), StringComparer.Ordinal);

            apiDefinition = swaggerV2ApiDefinitionReader.ReadDefinition(json, new Uri("http://localhost/swagger.json"));

            Assert.NotNull(apiDefinition?.BaseAddresses);
            Assert.Single(apiDefinition.BaseAddresses);
            Assert.Equal("http://localhost/", apiDefinition.BaseAddresses[0].Url.ToString(), StringComparer.Ordinal);
        }
Exemple #10
0
        public async Task ExecuteAsync_NoSwagger_ShowsWarning()
        {
            ArrangeInputs(commandText: "ls",
                          baseAddress: "http://localhost/",
                          path: "/",
                          urlsWithResponse: null,
                          out MockedShellState shellState,
                          out HttpState httpState,
                          out ICoreParseResult parseResult,
                          out _,
                          out IPreferences preferences);

            httpState.SwaggerEndpoint = null;
            ApiDefinition apiDefinition = new ApiDefinition()
            {
                DirectoryStructure = new DirectoryStructure(null)
            };

            httpState.ApiDefinition = apiDefinition;

            ListCommand listCommand = new ListCommand(preferences);

            await listCommand.ExecuteAsync(shellState, httpState, parseResult, CancellationToken.None);

            string actualOutput = string.Join(Environment.NewLine, shellState.Output);

            Assert.Equal(Resources.Strings.ListCommand_Error_NoDirectoryStructure, actualOutput);
        }
        public void ParseSpecDefinition(string name, Listing spec)
        {
            ConvertJsonSchemaToPoco schemaConverter = new ConvertJsonSchemaToPoco();

            JObject rootSchema = new JObject();

            rootSchema["properties"] = spec.Models;
            rootSchema["type"]       = "object";

            //We need to remove all empty "requires ellements since newtonsoft errors on those
            removeFields(rootSchema, new[] { "required" });
            string modelsCSharp = schemaConverter.Generate(rootSchema.ToString());


            ApiDefinition apiModel = ConvertApiSpecToCode.GenerateApiDefinition(name, spec);


            var assembly     = Assembly.GetExecutingAssembly();
            var resourceName = "SwaggerParser.Templates.Api.template.cshtml";

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (StreamReader reader = new StreamReader(stream))
                {
                    string template = reader.ReadToEnd();
                    string ret      = Razor.Parse(template, apiModel);
                }
        }
        public void ExecuteAsync_KnownEndpointWithRequestMethods_NoWarning()
        {
            ChangeDirectoryCommand command = new ChangeDirectoryCommand();

            Setup(commandText: "cd AnEndpoint", out MockedShellState mockedShellState, out HttpState httpState, out ICoreParseResult parseResult);

            DirectoryStructure directoryStructure = new DirectoryStructure(null);
            DirectoryStructure childDirectory     = directoryStructure.DeclareDirectory("AnEndpoint");
            RequestInfo        childRequestInfo   = new RequestInfo();

            childRequestInfo.AddMethod("GET");
            childDirectory.RequestInfo = childRequestInfo;
            ApiDefinition apiDefinition = new ApiDefinition()
            {
                DirectoryStructure = directoryStructure
            };

            httpState.ApiDefinition = apiDefinition;

            string expectedOutput = "/AnEndpoint    [GET]";

            command.ExecuteAsync(mockedShellState, httpState, parseResult, CancellationToken.None);

            Assert.Single(mockedShellState.Output);
            Assert.Equal(expectedOutput, mockedShellState.Output[0]);
        }
Exemple #13
0
        public async Task <ApiResource> Parse(IHttpResponse response, ApiDefinition definition)
        {
            var obj      = JObject.Parse(await response.ReadRawBody().ConfigureAwait(false));
            var resource = ParseRootResourceObject(obj, definition);

            return(resource);
        }
Exemple #14
0
        private void AssertDefinition(ApiDefinition expected, ApiDefinition actual)
        {
            // Core properties
            Assert.NotNull(actual);
            Assert.NotNull(actual.BaseAddresses);
            Assert.NotNull(actual.DirectoryStructure);

            // Base Addresses/Servers
            IEnumerator <ApiDefinition.Server> expectedBaseAddressEnumerator = expected.BaseAddresses.GetEnumerator();
            IEnumerator <ApiDefinition.Server> actualBaseAddressEnumerator   = actual.BaseAddresses.GetEnumerator();

            int index = 0;

            while (expectedBaseAddressEnumerator.MoveNext())
            {
                Assert.True(actualBaseAddressEnumerator.MoveNext(), $"Missing BaseAddress: {expectedBaseAddressEnumerator.Current}");

                Assert.True(expectedBaseAddressEnumerator.Current.Url == actualBaseAddressEnumerator.Current.Url, $"BaseAddress[{index}].Url does not match.");
                Assert.True(string.Equals(expectedBaseAddressEnumerator.Current.Description, actualBaseAddressEnumerator.Current.Description, System.StringComparison.InvariantCulture), $"BaseAddress[{index}].Description does not match.");

                index++;
            }
            Assert.False(actualBaseAddressEnumerator.MoveNext(), $"Extra BaseAddress: {actualBaseAddressEnumerator.Current}");

            // Directory Structure
            AssertDirectoryStructure(expected.DirectoryStructure, actual.DirectoryStructure, "/");
        }
Exemple #15
0
        public void ReadDefinition_WithRelativeServer_BaseAddressesCorrectEntry()
        {
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""version"": ""v1""
  },
  ""servers"": [
    {
      ""url"": ""/api/v2"",
      ""description"": ""First Server Address""
    }
  ],
  ""paths"": {
    ""/pets"": {
    }
  }
}";


            OpenApiDotNetApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(json, new Uri("https://localhost/swagger.json"));

            Assert.NotNull(apiDefinition?.BaseAddresses);
            Assert.Single(apiDefinition.BaseAddresses);
            Assert.Equal("https://localhost/api/v2/", apiDefinition.BaseAddresses[0].Url.ToString());
            Assert.Equal("First Server Address", apiDefinition.BaseAddresses[0].Description);
        }
Exemple #16
0
        public void ReadMetadata_WithValidInput_ReturnsApiDefinition()
        {
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""paths"": {
    ""/pets"": {
      ""get"": {
        ""summary"": ""List all pets"",
        ""operationId"": ""listPets"",
        ""parameters"": [
          {
            ""name"": ""limit"",
            ""in"": ""query"",
            ""required"": false,
            ""schema"": {
              ""type"": ""integer"",
              ""format"": ""int32""
            }
          }
        ],
        ""responses"": {
          ""200"": {
            ""description"": ""An paged array of pets""
          }
        }
      },
      ""post"": {
        ""summary"": ""Create a pet"",
        ""operationId"": ""createPets"",
        ""responses"": {
          ""201"": {
            ""description"": ""Null response""
          }
        },
        ""requestBody"": {
          ""content"": {
            
          }
        }
      }
    }
  }
}";

            OpenApiDotNetApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(json, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Single(apiDefinition.DirectoryStructure.DirectoryNames);
            Assert.Equal("pets", apiDefinition.DirectoryStructure.DirectoryNames.Single());

            IDirectoryStructure subDirectory = apiDefinition.DirectoryStructure.TraverseTo("/pets");

            Assert.Equal(2, subDirectory.RequestInfo.Methods.Count);
            Assert.Contains("Get", subDirectory.RequestInfo.Methods, StringComparer.Ordinal);
            Assert.Contains("Post", subDirectory.RequestInfo.Methods, StringComparer.Ordinal);
        }
Exemple #17
0
        private static ApiResource ParseRootResourceObject(JObject outer, ApiDefinition definition)
        {
            var links    = new List <ApiLink>();
            var embedded = new List <ApiResource>();
            var forms    = new List <ApiForm>();

            ParseResourceObject(outer, links, forms, embedded, definition);

            return(new ApiResource("root", forms, embedded, links, definition, outer.ToObject));
        }
Exemple #18
0
 public bool AddMapping(ApiDefinition action)
 {
     if (Prefixes.Contains(action.URI))
     {
         return(false);
     }
     ContainedCollection.Add(action);
     Prefixes.Add(action.URI);
     return(true);
 }
        public void API_Definition_RunAsync_Test()
        {
            //Assign
            HttpRequest req = new Mock <HttpRequest>().Object;
            ISwaggerDocumentGenerator swaggerGenerator = new SwaggerDocumentGenerator();

            //Act
            var res = ApiDefinition.RunAsync(req, MockingHelper.GetMockLogger(), swaggerGenerator);

            //Assert
            Assert.IsNotNull(res);
        }
Exemple #20
0
        public async Task ReadDefinition_RealOpenApiDescriptions_ReturnsExpectedDocument(string resourcePath, ApiDefinition expected)
        {
            // Arrange
            string content = await GetResourceContent(resourcePath);

            OpenApiDotNetApiDefinitionReader apiDefinitionReader = new();

            // Act
            ApiDefinition actual = apiDefinitionReader.ReadDefinition(content, null);

            // Assert
            AssertDefinition(expected, actual);
        }
Exemple #21
0
        private static ApiLink ParseLinkObject(JObject outer, string rel, ApiDefinition definition)
        {
            var link = new ApiLink {
                Rel = rel
            };

            foreach (var inner in outer.Properties())
            {
                var value = inner.Value.ToString();

                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                switch (inner.Name.ToLowerInvariant())
                {
                case "href":
                    link.Href = TryCreateUri(value, UriKind.RelativeOrAbsolute);
                    break;

                case "templated":
                    link.Templated = value.Equals("true", StringComparison.OrdinalIgnoreCase);
                    break;

                case "type":
                    link.Type = value;
                    break;

                case "deprication":
                    link.Deprecation = TryCreateUri(value, UriKind.Absolute);
                    break;

                case "profile":
                    link.Profile = TryCreateUri(value, UriKind.Absolute);
                    break;

                case "title":
                    link.Title = value;
                    break;

                case "hreflang":
                    link.HrefLang = value;
                    break;
                }
            }

            return(link);
        }
Exemple #22
0
        private static ApiForm ParseFormsResourceObject(JObject outer, string name, ApiDefinition definition)
        {
            var form = new ApiForm {
                Name = name
            };

            foreach (var inner in outer.Properties())
            {
                var value = inner.Value.ToString();

                if (string.IsNullOrEmpty(value))
                {
                    continue;
                }

                switch (inner.Name.ToLowerInvariant())
                {
                case "action":
                    form.Action = TryCreateUri(value, UriKind.RelativeOrAbsolute);
                    break;

                case "templated":
                    form.Templated = value.Equals("true", StringComparison.OrdinalIgnoreCase);
                    break;

                case "method":
                    form.Method = value;
                    break;

                case "type":
                    form.Type = value;
                    break;

                case "title":
                    form.Title = value;
                    break;

                case "headers":
                    form.Headers = inner.Value.ToObject <IReadOnlyDictionary <string, string> >();
                    break;

                case "schema":
                    form.Schema = inner.Value.ToObject <IReadOnlyDictionary <string, object> >();
                    break;
                }
            }

            return(form);
        }
Exemple #23
0
        public void ReadMetadata_WithSpecifiedMethodName_ReturnsApiDefinitionWithCorrectNumberOfRequestMethods(string method, bool shouldHaveRequest)
        {
            // The method must be lowercase to be valid in the json
            string methodForJson = method.ToLower();
            string json          = @"{
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""title"": ""OpenAPI v3 Spec"",
    ""version"": ""v1""
  },
  ""paths"": {
    ""/pets"": {
      """ + methodForJson + @""": {
        ""summary"": ""Do something"",
        ""operationId"": ""doSomething"",
        ""responses"": {
          ""200"": {
            ""description"": ""Null response""
          }
        },
        ""requestBody"": {
          ""description"": ""A Request Body"",
          ""required"": false
        }
      }
    }
  }
}";

            OpenApiDotNetApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(json, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Single(apiDefinition.DirectoryStructure.DirectoryNames);
            Assert.Equal("pets", apiDefinition.DirectoryStructure.DirectoryNames.Single());

            IDirectoryStructure subDirectory = apiDefinition.DirectoryStructure.TraverseTo("/pets");

            if (shouldHaveRequest)
            {
                Assert.Single(subDirectory.RequestInfo.Methods);
                Assert.Contains(method, subDirectory.RequestInfo.Methods, StringComparer.OrdinalIgnoreCase);
            }
            else
            {
                Assert.Null(subDirectory.RequestInfo);
            }
        }
        public void Read_WithJObjectFormatNotSupportedByAnyExistingReader_ReturnsNull()
        {
            string json = @"{
  ""info"": {
    ""version"": ""v1"",
    ""title"": ""My API""
  }
}";

            ApiDefinitionReader apiDefinitionReader = new ApiDefinitionReader();

            ApiDefinition definition = apiDefinitionReader.Read(json, null);

            Assert.Null(definition);
        }
Exemple #25
0
        public void ReadMetadata_WithNoApis_ReturnsApiDefinitionWithNoDirectories()
        {
            string  json    = @"{
  ""swaggerVersion"": ""1.0.0"",
  ""info"": {
    ""version"": ""v1""
  }
}";
            JObject jobject = JObject.Parse(json);
            SwaggerV1ApiDefinitionReader swaggerV1ApiDefinitionReader = new SwaggerV1ApiDefinitionReader();

            ApiDefinition apiDefinition = swaggerV1ApiDefinitionReader.ReadDefinition(jobject, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Empty(apiDefinition.DirectoryStructure.DirectoryNames);
        }
Exemple #26
0
        public void ReadMetadata_WithNoPaths_ReturnsEmptyDirectoryStructure()
        {
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""info"": {
    ""version"": ""v1""
  }
}";

            OpenApiDotNetApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(json, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Empty(apiDefinition.DirectoryStructure.DirectoryNames);
        }
Exemple #27
0
        public void ReadMetadata_WithNoPaths_ReturnsApiDefinitionWithNoDirectories()
        {
            string json = @"{
  ""swagger"": ""2.0"",
  ""info"": {
    ""version"": ""v1""
  }
}";

            OpenApiDotNetApiDefinitionReader swaggerV2ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = swaggerV2ApiDefinitionReader.ReadDefinition(json, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Empty(apiDefinition.DirectoryStructure.DirectoryNames);
        }
Exemple #28
0
        public void ReadMetadata_WithNoMethods_ReturnsApiDefinitionWithStructure()
        {
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""paths"": {
    ""/pets"": {
    }
  }
}";

            OpenApiDotNetApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(json, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
        }
Exemple #29
0
        public void ReadMetadata_WithNoOperations_ReturnsApiDefinitionWithStructure()
        {
            string  json    = @"{
  ""swaggerVersion"": ""1.2"",
  ""apis"": [
    {
      ""path"": ""/user/logout"",
    }
  ]
}";
            JObject jobject = JObject.Parse(json);
            SwaggerV1ApiDefinitionReader swaggerV1ApiDefinitionReader = new SwaggerV1ApiDefinitionReader();

            ApiDefinition apiDefinition = swaggerV1ApiDefinitionReader.ReadDefinition(jobject, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
        }
Exemple #30
0
        public void ReadMetadata_WithContentAndMultipleContentTypes_ReturnsApiDefinitionWithContentTypes()
        {
            string json = @"{
  ""openapi"": ""3.0.0"",
  ""paths"": {
    ""/pets"": {
      ""post"": {
        ""summary"": ""Create a pet"",
        ""operationId"": ""createPets"",
        ""responses"": {
          ""201"": {
            ""description"": ""Null response""
          }
        },
        ""requestBody"": {
          ""description"": ""A Request Body"",
          ""required"": false,
          ""content"": {
            ""application/json"": {
            },
            ""text/plain"": {
            }
          }
        }
      }
    }
  }
}";

            OpenApiDotNetApiDefinitionReader openApiV3ApiDefinitionReader = new OpenApiDotNetApiDefinitionReader();

            ApiDefinition apiDefinition = openApiV3ApiDefinitionReader.ReadDefinition(json, null);

            Assert.NotNull(apiDefinition?.DirectoryStructure);
            Assert.Single(apiDefinition.DirectoryStructure.DirectoryNames);
            Assert.Equal("pets", apiDefinition.DirectoryStructure.DirectoryNames.Single());

            IDirectoryStructure subDirectory = apiDefinition.DirectoryStructure.TraverseTo("/pets");

            Assert.Single(subDirectory.RequestInfo.Methods);
            Assert.Contains("Post", subDirectory.RequestInfo.Methods, StringComparer.Ordinal);
            Assert.Equal(2, subDirectory.RequestInfo.ContentTypesByMethod["post"].Count);
            Assert.Contains("application/json", subDirectory.RequestInfo.ContentTypesByMethod["post"]);
            Assert.Contains("text/plain", subDirectory.RequestInfo.ContentTypesByMethod["post"]);
        }