public void ClientModelWithCircularDependencyThrowsError() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-allOf-circular.json") }); Assert.Throws<ArgumentException>(() => modeler.Build()); }
public void TestClientModelFromSimpleSwagger() { Generator.Modeler modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-simple-spec.json") }); var clientModel = modeler.Build(); var description = "The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order."; var summary = "Product Types"; Assert.NotNull(clientModel); Assert.Equal(2, clientModel.Properties.Count); Assert.True(clientModel.Properties.Any(p => p.Name.Equals("subscriptionId", StringComparison.OrdinalIgnoreCase))); Assert.True(clientModel.Properties.Any(p => p.Name.Equals("apiVersion", StringComparison.OrdinalIgnoreCase))); Assert.Equal("2014-04-01-preview", clientModel.ApiVersion); Assert.Equal("https://management.azure.com/", clientModel.BaseUrl); Assert.Equal("Some cool documentation.", clientModel.Documentation); Assert.Equal(0, clientModel.Methods.Count(m => m.Group != null)); Assert.Equal(2, clientModel.Methods.Count); Assert.Equal("list", clientModel.Methods[0].Name); Assert.NotEmpty(clientModel.Methods[0].Description); Assert.Equal(description, clientModel.Methods[0].Description); Assert.NotEmpty(clientModel.Methods[0].Summary); Assert.Equal(summary, clientModel.Methods[0].Summary); Assert.Equal(HttpMethod.Get, clientModel.Methods[0].HttpMethod); Assert.Equal(3, clientModel.Methods[0].Parameters.Count); Assert.Equal("subscriptionId", clientModel.Methods[0].Parameters[0].Name); Assert.NotNull(clientModel.Methods[0].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", clientModel.Methods[0].Parameters[1].Name); Assert.Equal("resourceGroupName", clientModel.Methods[0].Parameters[1].SerializedName); Assert.Equal("Resource Group ID.", clientModel.Methods[0].Parameters[1].Documentation); Assert.Equal(true, clientModel.Methods[0].Parameters[0].IsRequired); Assert.Equal(ParameterLocation.Path, clientModel.Methods[0].Parameters[0].Location); Assert.Equal("String", clientModel.Methods[0].Parameters[0].Type.ToString()); Assert.Equal("reset", clientModel.Methods[1].Name); Assert.Equal("Product", clientModel.ModelTypes.First(m=>m.Name == "Product").Name); Assert.Equal("Product", clientModel.ModelTypes.First(m => m.Name == "Product").SerializedName); Assert.Equal("The product title.", clientModel.ModelTypes.First(m => m.Name == "Product").Summary); Assert.Equal("The product documentation.", clientModel.ModelTypes.First(m => m.Name == "Product").Documentation); Assert.Equal("A product id.", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[0].Summary); Assert.Equal("product_id", clientModel.ModelTypes.First(m=>m.Name == "Product").Properties[0].Name); Assert.Equal("product_id", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[0].SerializedName); Assert.Null(clientModel.Methods[1].ReturnType.Body); Assert.Null(clientModel.Methods[1].Responses[HttpStatusCode.NoContent].Body); Assert.Equal(3, clientModel.Methods[1].Parameters.Count); Assert.Equal("subscriptionId", clientModel.Methods[1].Parameters[0].Name); Assert.Null(clientModel.Methods[1].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", clientModel.Methods[1].Parameters[1].Name); Assert.Equal("apiVersion", clientModel.Methods[1].Parameters[2].Name); Assert.Equal("capacity", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Name); Assert.Equal("100", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[3].DefaultValue); }
public void ClientModelWithCircularDependencyThrowsError() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-allOf-circular.json") }); var ex = Assert.Throws<InvalidOperationException>(() => modeler.Build()); Assert.Contains("circular", ex.Message, StringComparison.OrdinalIgnoreCase); Assert.Contains("siamese", ex.Message, StringComparison.OrdinalIgnoreCase); }
public void TestExternalReferences() { Generator.Modeler modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-external-ref-no-definitions.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal(2, clientModel.ModelTypes.Count); }
public void GlobalResponsesReference() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-global-responses.json") }); var clientModel = modeler.Build(); Assert.Equal(1, clientModel.Methods[0].Responses.Count); Assert.NotNull(clientModel.Methods[0].Responses[HttpStatusCode.OK]); }
public void DefaultReturnsCorrectType() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-multiple-response-schemas.json") }); var clientModel = modeler.Build(); var retType = clientModel.Methods.First(m => m.Name == "patchDefaultResponse"); Assert.Equal("pet", retType.ReturnType.ToString()); }
public void TestExternalReferencesWithAllOf() { Generator.Modeler modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = @"Swagger\swagger-external-ref.json" }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal(3, clientModel.ModelTypes.Count); Assert.Equal("ChildProduct", clientModel.ModelTypes[0].Name); Assert.Equal("Product", clientModel.ModelTypes[0].BaseModelType.Name); }
public void AllowVendorExtensionInPath() { SwaggerModeler modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "vendor-extension-in-path.json") }); var clientModel = modeler.Build(); // should return a valid model. Assert.NotNull(clientModel); // there should be one method in this generated api. Assert.Equal(1, modeler.ServiceClient.Methods.Count); }
private IEnumerable<ValidationMessage> ValidateSwagger(string input) { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = input }); IEnumerable<ValidationMessage> messages; modeler.Build(out messages); // remove debug-level messages messages = messages.Where(each => each.Severity > LogEntrySeverity.Debug); return messages; }
public void TestClientModelFromSimpleSwagger() { Generator.Modeler modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-simple-spec.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal(2, clientModel.Properties.Count); Assert.True(clientModel.Properties.Any(p => p.Name.Equals("subscriptionId", StringComparison.OrdinalIgnoreCase))); Assert.True(clientModel.Properties.Any(p => p.Name.Equals("apiVersion", StringComparison.OrdinalIgnoreCase))); Assert.Equal("2014-04-01-preview", clientModel.ApiVersion); Assert.Equal("https://management.azure.com/", clientModel.BaseUrl); Assert.Equal("Some cool documentation.", clientModel.Documentation); Assert.Equal(0, clientModel.Methods.Count(m => m.Group != null)); Assert.Equal(2, clientModel.Methods.Count); Assert.Equal("list", clientModel.Methods[0].Name); Assert.NotEmpty(clientModel.Methods[0].Documentation); Assert.Equal(HttpMethod.Get, clientModel.Methods[0].HttpMethod); Assert.Equal(3, clientModel.Methods[0].Parameters.Count); Assert.Equal("subscriptionId", clientModel.Methods[0].Parameters[0].Name); Assert.NotNull(clientModel.Methods[0].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", clientModel.Methods[0].Parameters[1].Name); Assert.Equal("resourceGroupName", clientModel.Methods[0].Parameters[1].SerializedName); Assert.Equal("Resource Group ID.", clientModel.Methods[0].Parameters[1].Documentation); Assert.Equal(true, clientModel.Methods[0].Parameters[0].IsRequired); Assert.Equal(ParameterLocation.Path, clientModel.Methods[0].Parameters[0].Location); Assert.Equal("String", clientModel.Methods[0].Parameters[0].Type.ToString()); Assert.Equal("reset", clientModel.Methods[1].Name); Assert.Equal("Product", clientModel.ModelTypes[0].Name); Assert.Equal("Product", clientModel.ModelTypes[0].SerializedName); Assert.Equal("The product documentation.", clientModel.ModelTypes[0].Documentation); Assert.Equal("product_id", clientModel.ModelTypes[0].Properties[0].Name); Assert.Equal("product_id", clientModel.ModelTypes[0].Properties[0].SerializedName); Assert.Null(clientModel.Methods[1].ReturnType); Assert.Null(clientModel.Methods[1].Responses[HttpStatusCode.NoContent]); Assert.Equal(3, clientModel.Methods[1].Parameters.Count); Assert.Equal("subscriptionId", clientModel.Methods[1].Parameters[0].Name); Assert.Null(clientModel.Methods[1].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", clientModel.Methods[1].Parameters[1].Name); Assert.Equal("apiVersion", clientModel.Methods[1].Parameters[2].Name); }
public void TestClientNameJavaNormalization() { var setting = new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json") }; var modeler = new SwaggerModeler(setting); var clientModel = modeler.Build(); Extensions.NormalizeClientModel(clientModel, setting); var namer = new Microsoft.Rest.Generator.Java.JavaCodeNamer(setting.Namespace); namer.NormalizeClientModel(clientModel); Assert.NotNull(clientModel); Assert.Equal(2, clientModel.Methods.Count); Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count()); Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName()); Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName()); Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].Name); Assert.Equal("version", clientModel.Methods[0].Parameters[1].Name); Assert.Equal(2, clientModel.Properties.Count); Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count()); Assert.Equal("subscription", clientModel.Properties[0].GetClientName()); Assert.Equal("_version", clientModel.Properties[1].GetClientName()); Assert.Equal("subscription", clientModel.Properties[0].Name); Assert.Equal("_version", clientModel.Properties[1].Name); var type = clientModel.ModelTypes.First(); Assert.Equal("errorCode", type.Properties[0].Name); Assert.Equal("errorMessage", type.Properties[1].Name); Assert.Equal("parentError", type.Properties[2].Name); }
public void ConvertsPageResultsToPageTypeTest() { using (NewContext) { var input = Path.Combine(Core.Utilities.Extensions.CodeBaseDirectory(typeof(CSharpAzureCodeNamingFrameworkTests)), "Resource", "azure-paging.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); var plugin = new AutoRest.CSharp.Azure.PluginCsa(); using (plugin.Activate()) { codeModel = plugin.Serializer.Load(codeModel); codeModel = plugin.Transformer.TransformCodeModel(codeModel); var methods = codeModel.Methods.ToList(); Assert.Equal(7, methods.Count); Assert.Equal(1, methods.Count(m => m.Name == "GetSinglePage")); Assert.Equal(0, methods.Count(m => m.Name == "GetSinglePageNext")); Assert.Equal(1, methods.Count(m => m.Name == "PutSinglePage")); Assert.Equal(1, methods.Count(m => m.Name == "PutSinglePageSpecialNext")); Assert.Equal("Page<Product>", methods[0].ReturnType.Body.Name); Assert.Equal("object", methods[1].ReturnType.Body.Name.ToLowerInvariant()); Assert.Equal("Page1<Product>", methods[1].Responses.ElementAt(0).Value.Body.Name); Assert.Equal("string", methods[1].Responses.ElementAt(1).Value.Body.Name.ToLowerInvariant()); Assert.Equal("object", methods[2].ReturnType.Body.Name.ToLowerInvariant()); Assert.Equal("Page1<Product>", methods[2].Responses.ElementAt(0).Value.Body.Name); Assert.Equal("Page1<Product>", methods[2].Responses.ElementAt(1).Value.Body.Name); Assert.Equal("object", methods[3].ReturnType.Body.Name.ToLowerInvariant()); Assert.Equal("Page1<Product>", methods[3].Responses.ElementAt(0).Value.Body.Name); Assert.Equal("Page1<ProductChild>", methods[3].Responses.ElementAt(1).Value.Body.Name); Assert.Equal(5, codeModel.ModelTypes.Count); Assert.False( codeModel.ModelTypes.Any(t => t.Name.EqualsIgnoreCase("ProducResult"))); Assert.False( codeModel.ModelTypes.Any(t => t.Name.EqualsIgnoreCase("ProducResult2"))); Assert.False( codeModel.ModelTypes.Any(t => t.Name.EqualsIgnoreCase("ProducResult3"))); } } }
public void SwaggerODataSpecParsingTest() { using (NewContext) { var settings = new Settings { Namespace = "Test", Input = @"Swagger\swagger-odata-spec.json" }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); var transformer = new SampleAzureTransformer(); codeModel = transformer.TransformCodeModel(codeModel); Assert.NotNull(codeModel); Assert.Equal(5, codeModel.Methods[0].Parameters.Count); Assert.Equal("$filter", codeModel.Methods[0].Parameters[2].Name.FixedValue); Assert.Equal("Product", codeModel.Methods[0].Parameters[2].ModelType.Name); } }
public void SwaggerODataSpecParsingTest() { using (NewContext) { var settings = new Settings { Namespace = "Test", Input = Path.Combine(Core.Utilities.Extensions.CodeBaseDirectory, "Resource", "swagger-odata-spec.json") }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); var transformer = new SampleAzureTransformer(); codeModel = transformer.TransformCodeModel(codeModel); Assert.NotNull(codeModel); Assert.Equal(5, codeModel.Methods[0].Parameters.Count); Assert.Equal("$filter", codeModel.Methods[0].Parameters[2].Name.FixedValue); Assert.Equal("Product", codeModel.Methods[0].Parameters[2].ModelType.Name); } }
public void TestcodeModelWithManyAllOfRelationships() { using (NewContext) { new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-ref-allOf-inheritance.json") }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); // the model has a few base type relationships which should be observed: // RedisResource is a Resource var resourceModel = codeModel.ModelTypes.Single(x => x.Name == "Resource"); var redisResourceModel = codeModel.ModelTypes.Single(x => x.Name == "RedisResource"); Assert.Equal(resourceModel, redisResourceModel.BaseModelType); // RedisResourceWithAccessKey is a RedisResource var redisResponseWithAccessKeyModel = codeModel.ModelTypes.Single(x => x.Name == "RedisResourceWithAccessKey"); Assert.Equal(redisResourceModel, redisResponseWithAccessKeyModel.BaseModelType); // RedisCreateOrUpdateParameters is a Resource var redisCreateUpdateParametersModel = codeModel.ModelTypes.Single(x => x.Name == "RedisCreateOrUpdateParameters"); Assert.Equal(resourceModel, redisCreateUpdateParametersModel.BaseModelType); // RedisReadableProperties is a RedisProperties var redisPropertiesModel = codeModel.ModelTypes.Single(x => x.Name == "RedisProperties"); var redisReadablePropertieModel = codeModel.ModelTypes.Single(x => x.Name == "RedisReadableProperties"); Assert.Equal(redisPropertiesModel, redisReadablePropertieModel.BaseModelType); // RedisReadablePropertiesWithAccessKey is a RedisReadableProperties var redisReadablePropertiesWithAccessKeysModel = codeModel.ModelTypes.Single(x => x.Name == "RedisReadablePropertiesWithAccessKey"); Assert.Equal(redisReadablePropertieModel, redisReadablePropertiesWithAccessKeysModel.BaseModelType); } }
public void TestcodeModelWithDifferentReturnsTypesBasedOnStatusCode() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-multiple-response-schemas.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); Assert.Equal("GetSameResponse", codeModel.Methods[0].Name); Assert.Equal("IList<Pet>", CreateCSharpResponseType(codeModel.Methods[0].ReturnType)); Assert.Equal("IList<Pet>", CreateCSharpResponseType(codeModel.Methods[0].Responses[HttpStatusCode.OK])); Assert.Equal("IList<Pet>", CreateCSharpResponseType(codeModel.Methods[0].Responses[HttpStatusCode.Accepted])); Assert.Equal("PostInheretedTypes", codeModel.Methods[1].Name); Assert.Equal("Pet", CreateCSharpResponseType(codeModel.Methods[1].ReturnType)); Assert.Equal("Dog", CreateCSharpResponseType(codeModel.Methods[1].Responses[HttpStatusCode.OK])); Assert.Equal("Cat", CreateCSharpResponseType(codeModel.Methods[1].Responses[HttpStatusCode.Accepted])); Assert.Equal("PatchDifferentStreamTypesNoContent", codeModel.Methods[6].Name); Assert.Equal("VirtualMachineGetRemoteDesktopFileResponse", CreateCSharpResponseType(codeModel.Methods[6].ReturnType)); Assert.Equal("VirtualMachineGetRemoteDesktopFileResponse", CreateCSharpResponseType(codeModel.Methods[6].Responses[HttpStatusCode.OK])); Assert.Null(codeModel.Methods[6].Responses[HttpStatusCode.NoContent].Body); }
public void TestClientNameCSharpNormalization() { using (NewContext) { var setting = new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-x-ms-client-name.json") }; var modeler = new SwaggerModeler(); var clientModel = modeler.Build(); SwaggerExtensions.NormalizeClientModel(clientModel); Assert.NotNull(clientModel); Assert.Equal(2, clientModel.Methods.Count); Assert.Equal(2, clientModel.Methods[0].Parameters.Where(p => !p.IsClientProperty).Count()); Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].GetClientName()); Assert.Equal("version", clientModel.Methods[0].Parameters[1].GetClientName()); Assert.Equal("subscription", clientModel.Methods[0].Parameters[0].Name); Assert.Equal("version", clientModel.Methods[0].Parameters[1].Name); Assert.Equal(2, clientModel.Properties.Count); Assert.Equal(0, clientModel.Methods[1].Parameters.Where(p => !p.IsClientProperty).Count()); Assert.Equal("subscription", clientModel.Properties[0].GetClientName()); Assert.Equal("_version", clientModel.Properties[1].GetClientName()); Assert.Equal("Subscription", clientModel.Properties[0].Name); Assert.Equal("_version", clientModel.Properties[1].Name); var type = clientModel.ModelTypes.First(); Assert.Equal("ErrorCode", type.Properties[0].Name); Assert.Equal("ErrorMessage", type.Properties[1].Name); Assert.Equal("ParentError", type.Properties[2].Name); } }
public void TestClientWithValidation() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = @"Swagger\swagger-validation.json" }); var clientModel = modeler.Build(); Assert.Equal("resourceGroupName", clientModel.Methods[0].Parameters[1].Name); Assert.Equal(true, clientModel.Methods[0].Parameters[1].IsRequired); Assert.Equal(3, clientModel.Methods[0].Parameters[1].Constraints.Count); Assert.Equal("10", clientModel.Methods[0].Parameters[1].Constraints[Constraint.MaxLength]); Assert.Equal("3", clientModel.Methods[0].Parameters[1].Constraints[Constraint.MinLength]); Assert.Equal("[a-zA-Z0-9]+", clientModel.Methods[0].Parameters[1].Constraints[Constraint.Pattern]); Assert.Equal("id", clientModel.Methods[0].Parameters[2].Name); Assert.Equal(3, clientModel.Methods[0].Parameters[2].Constraints.Count); Assert.Equal("10", clientModel.Methods[0].Parameters[2].Constraints[Constraint.MultipleOf]); Assert.Equal("100", clientModel.Methods[0].Parameters[2].Constraints[Constraint.InclusiveMinimum]); Assert.Equal("1000", clientModel.Methods[0].Parameters[2].Constraints[Constraint.InclusiveMaximum]); Assert.Equal("apiVersion", clientModel.Methods[0].Parameters[3].Name); Assert.NotNull(clientModel.Methods[0].Parameters[3].ClientProperty); Assert.Equal(1, clientModel.Methods[0].Parameters[3].Constraints.Count); Assert.Equal("\\d{2}-\\d{2}-\\d{4}", clientModel.Methods[0].Parameters[3].Constraints[Constraint.Pattern]); Assert.Equal("Product", clientModel.ModelTypes.First(m => m.Name == "Product").Name); Assert.Equal("display_names", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Name); Assert.Equal(3, clientModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.Count); Assert.Equal("6", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints[Constraint.MaxItems]); Assert.Equal("0", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints[Constraint.MinItems]); Assert.Equal("true", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints[Constraint.UniqueItems]); Assert.Equal("capacity", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Name); Assert.Equal(2, clientModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Constraints.Count); Assert.Equal("100", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Constraints[Constraint.ExclusiveMaximum]); Assert.Equal("0", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Constraints[Constraint.ExclusiveMinimum]); }
public void TestInputMapping() { using (NewContext) { var settings = new Settings { Namespace = "Test", Input = Path.Combine(Core.Utilities.Extensions.CodeBaseDirectory, "Resource", "swagger-payload-flatten.json"), PayloadFlatteningThreshold = 3, OutputDirectory = Path.GetTempPath() }; settings.FileSystem = new MemoryFileSystem(); settings.FileSystem.WriteFile("AutoRest.json", File.ReadAllText(Path.Combine(Core.Utilities.Extensions.CodeBaseDirectory, "Resource", "AutoRest.json"))); settings.FileSystem.CreateDirectory(Path.GetDirectoryName(settings.Input)); settings.FileSystem.WriteFile(settings.Input, File.ReadAllText(settings.Input)); var modeler = new SwaggerModeler(); var clientModel = modeler.Build(); var plugin = new PluginCs(); using (plugin.Activate()) { clientModel = plugin.Serializer.Load(clientModel); clientModel = plugin.Transformer.TransformCodeModel(clientModel); CodeGeneratorCs generator = new CodeGeneratorCs(); generator.Generate(clientModel).GetAwaiter().GetResult(); string body = settings.FileSystem.ReadFileAsText(Path.Combine(settings.OutputDirectory, "Payload.cs")); Assert.True(body.ContainsMultiline(@" MinProduct minProduct = new MinProduct(); if (baseProductId != null || baseProductDescription != null || maxProductReference != null) { minProduct.BaseProductId = baseProductId; minProduct.BaseProductDescription = baseProductDescription; minProduct.MaxProductReference = maxProductReference; }")); } } }
public void TestcodeModelWithInheritance() { using (NewContext) { new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-allOf.json") }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.NotNull(codeModel); Assert.Equal("Pet", codeModel.ModelTypes.First(m => m.Name == "Pet").Name); Assert.Equal("Cat", codeModel.ModelTypes.First(m => m.Name == "Cat").Name); Assert.Equal("Pet", codeModel.ModelTypes.First(m => m.Name == "Cat").BaseModelType.Name); Assert.Equal("Breed", codeModel.ModelTypes.First(m => m.Name == "Cat").Properties[0].Name); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Cat").Properties[0].IsRequired); Assert.Equal("Color", codeModel.ModelTypes.First(m => m.Name == "Cat").Properties[1].Name); Assert.Equal("Siamese", codeModel.ModelTypes.First(m => m.Name == "Siamese").Name); Assert.Equal("Cat", codeModel.ModelTypes.First(m => m.Name == "Siamese").BaseModelType.Name); } }
public void TestRealPathIrregular() { var input = Path.Combine("Resource", "Swagger", "swagger-xml-paths.yaml"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); foreach (var property in codeModel.ModelTypes.SelectMany(m => m.Properties)) { var expectedRealPath = property.Documentation.StartsWith("CUSTOM_") ? property.Documentation.Substring("CUSTOM_".Length) : null; var expectedRealXmlPath = property.Summary; if (expectedRealPath != null) { Assert.Equal(expectedRealPath, string.Join(".", property.RealPath)); } if (expectedRealXmlPath != null) { Assert.Equal(expectedRealXmlPath, string.Join(".", property.RealXmlPath)); } } }
public void TestcodeModelWithManyAllOfRelationships() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-ref-allOf-inheritance.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); // the model has a few base type relationships which should be observed: // RedisResource is a Resource var resourceModel = codeModel.ModelTypes.Single(x => x.Name == "Resource"); var redisResourceModel = codeModel.ModelTypes.Single(x => x.Name == "RedisResource"); Assert.Equal(resourceModel, redisResourceModel.BaseModelType); // RedisResourceWithAccessKey is a RedisResource var redisResponseWithAccessKeyModel = codeModel.ModelTypes.Single(x => x.Name == "RedisResourceWithAccessKey"); Assert.Equal(redisResourceModel, redisResponseWithAccessKeyModel.BaseModelType); // RedisCreateOrUpdateParameters is a Resource var redisCreateUpdateParametersModel = codeModel.ModelTypes.Single(x => x.Name == "RedisCreateOrUpdateParameters"); Assert.Equal(resourceModel, redisCreateUpdateParametersModel.BaseModelType); // RedisReadableProperties is a RedisProperties var redisPropertiesModel = codeModel.ModelTypes.Single(x => x.Name == "RedisProperties"); var redisReadablePropertieModel = codeModel.ModelTypes.Single(x => x.Name == "RedisReadableProperties"); Assert.Equal(redisPropertiesModel, redisReadablePropertieModel.BaseModelType); // RedisReadablePropertiesWithAccessKey is a RedisReadableProperties var redisReadablePropertiesWithAccessKeysModel = codeModel.ModelTypes.Single(x => x.Name == "RedisReadablePropertiesWithAccessKey"); Assert.Equal(redisReadablePropertieModel, redisReadablePropertiesWithAccessKeysModel.BaseModelType); }
public void ConvertsPageResultsToPageTypeTest() { var settings = new Settings { Input = Path.Combine("Swagger", "azure-paging.json"), Header = "NONE", Modeler = "Swagger", CodeGenerator = "CSharp" }; settings.FileSystem = new MemoryFileSystem(); settings.FileSystem.CreateDirectory(Path.GetDirectoryName(settings.Input)); settings.FileSystem.WriteFile(settings.Input, File.ReadAllText(settings.Input)); SwaggerModeler modeler = new SwaggerModeler(settings); var serviceClient = modeler.Build(); var codeNamer = new AzureCSharpCodeNamer(); var objName = codeNamer.NormalizeTypeReference(PrimaryType.Object).Name; var strName = codeNamer.NormalizeTypeReference(PrimaryType.String).Name; IDictionary <KeyValuePair <string, string>, string> pageClass = new Dictionary <KeyValuePair <string, string>, string>(); codeNamer.NormalizePaginatedMethods(serviceClient, pageClass); Assert.Equal("Page<Product>", serviceClient.Methods[0].ReturnType.Body.Name); Assert.Equal(objName, serviceClient.Methods[1].ReturnType.Body.Name); Assert.Equal("Page<Product>", serviceClient.Methods[1].Responses.ElementAt(0).Value.Body.Name); Assert.Equal(strName, serviceClient.Methods[1].Responses.ElementAt(1).Value.Body.Name); Assert.Equal(objName, serviceClient.Methods[2].ReturnType.Body.Name); Assert.Equal("Page<Product>", serviceClient.Methods[2].Responses.ElementAt(0).Value.Body.Name); Assert.Equal("Page<Product>", serviceClient.Methods[2].Responses.ElementAt(1).Value.Body.Name); Assert.Equal(objName, serviceClient.Methods[3].ReturnType.Body.Name); Assert.Equal("Page<Product>", serviceClient.Methods[3].Responses.ElementAt(0).Value.Body.Name); Assert.Equal("Page<ProductChild>", serviceClient.Methods[3].Responses.ElementAt(1).Value.Body.Name); Assert.Equal(4, serviceClient.ModelTypes.Count); Assert.False(serviceClient.ModelTypes.Any(t => t.Name.Equals("ProducResult", StringComparison.OrdinalIgnoreCase))); Assert.False(serviceClient.ModelTypes.Any(t => t.Name.Equals("ProducResult2", StringComparison.OrdinalIgnoreCase))); Assert.False(serviceClient.ModelTypes.Any(t => t.Name.Equals("ProducResult3", StringComparison.OrdinalIgnoreCase))); }
public void TestParameterLocationExtension() { var setting = new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-parameter-location.json"), PayloadFlatteningThreshold = 3 }; var modeler = new SwaggerModeler(setting); var clientModel = modeler.Build(); SwaggerExtensions.NormalizeClientModel(clientModel, setting); Assert.NotNull(clientModel); Assert.Equal(2, clientModel.Properties.Count); Assert.Equal(clientModel.Properties[0].Name, "subscriptionId"); Assert.Equal(clientModel.Properties[1].Name, "apiVersion"); Assert.True(clientModel.Methods[0].Parameters.Any(p => p.Name == "resourceGroupName" && !p.IsClientProperty)); Assert.True(clientModel.Methods[0].Parameters.Any(p => p.Name == "subscriptionId" && p.IsClientProperty)); Assert.True(clientModel.Methods[0].Parameters.Any(p => p.Name == "apiVersion" && p.IsClientProperty)); Assert.True(clientModel.Methods[1].Parameters.Any(p => p.Name == "resourceGroupName" && !p.IsClientProperty)); Assert.True(clientModel.Methods[1].Parameters.Any(p => p.Name == "subscriptionId" && p.IsClientProperty)); Assert.True(clientModel.Methods[1].Parameters.Any(p => p.Name == "apiVersion" && p.IsClientProperty)); }
public void FlatteningTest() { var settings = new Settings { Namespace = "Test", Input = @"Swagger\swagger-resource-flattening.json" }; var modeler = new SwaggerModeler(settings); var serviceClient = modeler.Build(); var codeGen = new SampleAzureCodeGenerator(settings); codeGen.NormalizeClientModel(serviceClient); Assert.NotNull(serviceClient); Assert.True(serviceClient.ModelTypes.Any(t => t.Name == "Product")); // ProductProperties type is not removed because it is referenced in response of one of the methods Assert.True(serviceClient.ModelTypes.Any(t => t.Name == "ProductProperties")); Assert.Equal(serviceClient.ModelTypes.First(t => t.Name == "ProductProperties").Properties.Count, serviceClient.ModelTypes.First(t => t.Name == "Product").Properties.Count); Assert.Equal("product_id", serviceClient.ModelTypes.First(t => t.Name == "ProductProperties").Properties[0].SerializedName); Assert.Equal("properties.product_id", serviceClient.ModelTypes.First(t => t.Name == "Product").Properties[0].SerializedName); }
public void TestcodeModelWithResponseHeaders() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-response-headers.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); Assert.Equal(2, codeModel.Methods.Count); Assert.Equal(2, codeModel.Methods[0].Responses.Count); Assert.Equal("ListHeaders", codeModel.Methods[0].Responses[HttpStatusCode.OK].Headers.Name); Assert.Equal(3, ((CompositeType)codeModel.Methods[0].Responses[HttpStatusCode.OK].Headers).Properties.Count); Assert.Equal("ListHeaders", codeModel.Methods[0].Responses[HttpStatusCode.Created].Headers.Name); Assert.Equal(3, ((CompositeType)codeModel.Methods[0].Responses[HttpStatusCode.Created].Headers).Properties.Count); Assert.Equal("ListHeaders", codeModel.Methods[0].ReturnType.Headers.Name); Assert.Equal(3, ((CompositeType)codeModel.Methods[0].ReturnType.Headers).Properties.Count); Assert.Equal(1, codeModel.Methods[1].Responses.Count); Assert.Equal("CreateHeaders", codeModel.Methods[1].Responses[HttpStatusCode.OK].Headers.Name); Assert.Equal(3, ((CompositeType)codeModel.Methods[1].Responses[HttpStatusCode.OK].Headers).Properties.Count); Assert.Equal("CreateHeaders", codeModel.Methods[1].ReturnType.Headers.Name); Assert.Equal(3, ((CompositeType)codeModel.Methods[1].ReturnType.Headers).Properties.Count); Assert.True(codeModel.HeaderTypes.Any(c => c.Name == "ListHeaders")); Assert.True(codeModel.HeaderTypes.Any(c => c.Name == "CreateHeaders")); }
public void TestYamlParsing() { using (NewContext) { var settings = new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-simple-spec.yaml") }; Modeler modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.NotNull(codeModel); } }
public void TestExternalReferencesWithAllOf() { Generator.Modeler modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-external-ref.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal(3, clientModel.ModelTypes.Count); Assert.Equal("ChildProduct", clientModel.ModelTypes.First(m => m.Name == "ChildProduct").Name); Assert.Equal("Product", clientModel.ModelTypes.First(m => m.Name == "ChildProduct").BaseModelType.Name); }
public void TestAdditionalProperties() { using (NewContext) { new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-additional-properties.yaml") }; Modeler modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.NotNull(codeModel); Assert.Equal(5, codeModel.ModelTypes.Count); // did we find the type? var wtd = codeModel.ModelTypes.FirstOrDefault(each => each.Name == "WithTypedDictionary"); Assert.NotNull(wtd); // did we find the member called 'additionalProperties' var prop = wtd.Properties.FirstOrDefault(each => each.Name == "AdditionalProperties"); Assert.NotNull(prop); // is it a DictionaryType? var dictionaryProperty = prop.ModelType as DictionaryType; Assert.NotNull(dictionaryProperty); // is a string,string dictionary? Assert.Equal("Dictionary<string,Feature>", dictionaryProperty.Name); Assert.Equal("Feature", dictionaryProperty.ValueType.Name); // is it marked as an 'additionalProperties' bucket? Assert.True(dictionaryProperty.SupportsAdditionalProperties); // did we find the type? var wud = codeModel.ModelTypes.FirstOrDefault(each => each.Name == "WithUntypedDictionary"); Assert.NotNull(wud); // did we find the member called 'additionalProperties' prop = wud.Properties.FirstOrDefault(each => each.Name == "AdditionalProperties"); Assert.NotNull(prop); // is it a DictionaryType? dictionaryProperty = prop.ModelType as DictionaryType; Assert.NotNull(dictionaryProperty); // is a string,string dictionary? Assert.Equal("Dictionary<string,Object>", dictionaryProperty.Name); Assert.Equal("Object", dictionaryProperty.ValueType.Name); // is it marked as an 'additionalProperties' bucket? Assert.True(dictionaryProperty.SupportsAdditionalProperties); var wsd = codeModel.ModelTypes.FirstOrDefault(each => each.Name == "WithStringDictionary"); Assert.NotNull(wsd); // did we find the member called 'additionalProperties' prop = wsd.Properties.FirstOrDefault(each => each.Name == "AdditionalProperties"); Assert.NotNull(prop); // is it a DictionaryType? dictionaryProperty = prop.ModelType as DictionaryType; Assert.NotNull(dictionaryProperty); // is a string,string dictionary? Assert.Equal("Dictionary<string,String>", dictionaryProperty.Name); Assert.Equal("String", dictionaryProperty.ValueType.Name); // is it marked as an 'additionalProperties' bucket? Assert.True(dictionaryProperty.SupportsAdditionalProperties); } }
public void TestCustomPaths() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-x-ms-paths.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal(3, clientModel.Methods.Count); Assert.True(clientModel.Methods.All(m => m.Url == "/values/foo")); }
public void TestDataTypes() { using (NewContext) { new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-data-types.json") }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.NotNull(codeModel); Assert.Equal("Int integer", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[0])); Assert.Equal("Int int", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[1])); Assert.Equal("Long long", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[2])); Assert.Equal("Double number", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[3])); Assert.Equal("Double float", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[4])); Assert.Equal("Double double", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[5])); Assert.Equal("Decimal decimal", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[6])); Assert.Equal("String string", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[7])); Assert.Equal("enum color", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[8])); Assert.Equal("ByteArray byte", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[9])); Assert.Equal("Boolean boolean", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[10])); Assert.Equal("Date date", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[11])); Assert.Equal("DateTime dateTime", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[12])); Assert.Equal("Base64Url base64url", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[13])); Assert.Equal("IList<String> array", CreateCSharpDeclarationString(codeModel.Methods[0].Parameters[14])); var variableEnumInPath = codeModel.Methods.First(m => m.Name == "List" && m.Group.IsNullOrEmpty()) .Parameters.First(p => p.Name == "color" && p.Location == ParameterLocation.Path) .ModelType as EnumType; Assert.NotNull(variableEnumInPath); Assert.Equal(variableEnumInPath.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" } } .ToList()); Assert.True(variableEnumInPath.ModelAsString); Assert.Empty(variableEnumInPath.Name.RawValue); var variableEnumInQuery = codeModel.Methods.First(m => m.Name == "List" && m.Group.IsNullOrEmpty()) .Parameters.First(p => p.Name == "color1" && p.Location == ParameterLocation.Query) .ModelType as EnumType; Assert.NotNull(variableEnumInQuery); Assert.Equal(variableEnumInQuery.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" }, new EnumValue { Name = "purple" } }.ToList()); Assert.True(variableEnumInQuery.ModelAsString); Assert.Empty(variableEnumInQuery.Name.RawValue); var differentEnum = codeModel.Methods.First(m => m.Name == "List" && m.Group == "DiffEnums") .Parameters.First(p => p.Name == "color" && p.Location == ParameterLocation.Query) .ModelType as EnumType; Assert.NotNull(differentEnum); Assert.Equal(differentEnum.Values, new[] { new EnumValue { Name = "cyan" }, new EnumValue { Name = "yellow" } }.ToList()); Assert.True(differentEnum.ModelAsString); Assert.Empty(differentEnum.Name.RawValue); var sameEnum = codeModel.Methods.First(m => m.Name == "Get" && m.Group == "SameEnums") .Parameters.First(p => p.Name == "color2" && p.Location == ParameterLocation.Query) .ModelType as EnumType; Assert.NotNull(sameEnum); Assert.Equal(sameEnum.Values, new[] { new EnumValue { Name = "blue" }, new EnumValue { Name = "green" }, new EnumValue { Name = "red" } } .ToList()); Assert.True(sameEnum.ModelAsString); Assert.Empty(sameEnum.Name.RawValue); var modelEnum = codeModel.ModelTypes.First(m => m.Name == "Product") .Properties.First(p => p.Name == "Color2") .ModelType as EnumType; Assert.NotNull(modelEnum); Assert.Equal(modelEnum.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" } } .ToList()); Assert.True(modelEnum.ModelAsString); Assert.Empty(modelEnum.Name.RawValue); var fixedEnum = codeModel.ModelTypes.First(m => m.Name == "Product") .Properties.First(p => p.Name == "Color") .ModelType as EnumType; Assert.NotNull(fixedEnum); Assert.Equal(fixedEnum.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" } } .ToList()); Assert.False(fixedEnum.ModelAsString); Assert.Equal("Colors", fixedEnum.Name); var fixedEnum2 = codeModel.ModelTypes.First(m => m.Name == "Product") .Properties.First(p => p.Name == "Color3") .ModelType as EnumType; Assert.Equal(fixedEnum2, fixedEnum); var refEnum = codeModel.ModelTypes.First(m => m.Name == "Product") .Properties.First(p => p.Name == "RefColor") .ModelType as EnumType; Assert.NotNull(refEnum); Assert.Equal(refEnum.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "green" }, new EnumValue { Name = "blue" } } .ToList()); Assert.True(refEnum.ModelAsString); Assert.Equal("RefColors", refEnum.Name); Assert.Equal(2, codeModel.EnumTypes.Count); Assert.Equal("Colors", codeModel.EnumTypes.First().Name); } }
public void TestAdditionalProperties() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-additional-properties.yaml"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); Assert.Equal(5, codeModel.ModelTypes.Count); // did we find the type? var wtd = codeModel.ModelTypes.FirstOrDefault(each => each.Name == "WithTypedDictionary"); Assert.NotNull(wtd); // did we find the member called 'additionalProperties' var prop = wtd.Properties.FirstOrDefault(each => each.Name == "AdditionalProperties"); Assert.NotNull(prop); // is it a DictionaryType? var dictionaryProperty = prop.ModelType as DictionaryType; Assert.NotNull(dictionaryProperty); // is a string,string dictionary? Assert.Equal("Dictionary<string,Feature>", dictionaryProperty.Name); Assert.Equal("Feature", dictionaryProperty.ValueType.Name); // is it marked as an 'additionalProperties' bucket? Assert.True(dictionaryProperty.SupportsAdditionalProperties); // did we find the type? var wud = codeModel.ModelTypes.FirstOrDefault(each => each.Name == "WithUntypedDictionary"); Assert.NotNull(wud); // did we find the member called 'additionalProperties' prop = wud.Properties.FirstOrDefault(each => each.Name == "AdditionalProperties"); Assert.NotNull(prop); // is it a DictionaryType? dictionaryProperty = prop.ModelType as DictionaryType; Assert.NotNull(dictionaryProperty); // is a string,string dictionary? Assert.Equal("Dictionary<string,Object>", dictionaryProperty.Name); Assert.Equal("Object", dictionaryProperty.ValueType.Name); // is it marked as an 'additionalProperties' bucket? Assert.True(dictionaryProperty.SupportsAdditionalProperties); var wsd = codeModel.ModelTypes.FirstOrDefault(each => each.Name == "WithStringDictionary"); Assert.NotNull(wsd); // did we find the member called 'additionalProperties' prop = wsd.Properties.FirstOrDefault(each => each.Name == "AdditionalProperties"); Assert.NotNull(prop); // is it a DictionaryType? dictionaryProperty = prop.ModelType as DictionaryType; Assert.NotNull(dictionaryProperty); // is a string,string dictionary? Assert.Equal("Dictionary<string,String>", dictionaryProperty.Name); Assert.Equal("String", dictionaryProperty.ValueType.Name); // is it marked as an 'additionalProperties' bucket? Assert.True(dictionaryProperty.SupportsAdditionalProperties); }
public void TestConstants() { using (NewContext) { new Settings { Namespace = "Test", Input = @"Swagger\swagger-validation.json" }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.Equal("myintconst", codeModel.Methods[0].Parameters[4].Name); Assert.Equal(true, codeModel.Methods[0].Parameters[4].ModelType.IsPrimaryType(KnownPrimaryType.Int)); Assert.Equal(true, codeModel.Methods[0].Parameters[4].IsConstant); Assert.Equal("0", codeModel.Methods[0].Parameters[4].DefaultValue); Assert.Equal("mystrconst", codeModel.Methods[0].Parameters[5].Name); Assert.Equal(true, codeModel.Methods[0].Parameters[5].ModelType.IsPrimaryType(KnownPrimaryType.String)); Assert.Equal(true, codeModel.Methods[0].Parameters[5].IsConstant); Assert.Equal("constant", codeModel.Methods[0].Parameters[5].DefaultValue); Assert.Equal("Myintconst", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[5].Name); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[5].ModelType.IsPrimaryType(KnownPrimaryType.Int)); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[5].IsConstant); Assert.Equal("0", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[5].DefaultValue); Assert.Equal("Mystrconst", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[6].Name); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[6].ModelType.IsPrimaryType(KnownPrimaryType.String)); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[6].IsConstant); Assert.Equal("constant", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[6].DefaultValue); Assert.Equal("RefStrEnumRequiredConstant", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[7].Name); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[7].ModelType.IsPrimaryType(KnownPrimaryType.String)); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[7].IsConstant); Assert.Equal("ReferenceEnum1", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[7].DefaultValue); Assert.Equal("RefIntEnumRequiredConstant", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[8].Name); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[8].ModelType.IsPrimaryType(KnownPrimaryType.Int)); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[8].IsConstant); Assert.Equal("0", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[8].DefaultValue); Assert.Equal("RefStrEnum", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[9].Name); Assert.Equal("enum", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[9].ModelType.ToString()); Assert.Equal(false, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[9].IsConstant); Assert.True(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[9].DefaultValue.IsNullOrEmpty()); Assert.Equal("RefIntEnum", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[10].Name); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[10].ModelType.IsPrimaryType(KnownPrimaryType.Int)); Assert.Equal(false, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[10].IsConstant); Assert.True(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[10].DefaultValue.IsNullOrEmpty()); Assert.Equal(true, codeModel.ModelTypes.First(m => m.Name == "Product").ContainsConstantProperties); Assert.Equal(false, codeModel.ModelTypes.First(m => m.Name == "Error").ContainsConstantProperties); } }
public void TestDataTypes() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-data-types.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal("Int integer", clientModel.Methods[0].Parameters[0].ToString()); Assert.Equal("Int int", clientModel.Methods[0].Parameters[1].ToString()); Assert.Equal("Long long", clientModel.Methods[0].Parameters[2].ToString()); Assert.Equal("Double number", clientModel.Methods[0].Parameters[3].ToString()); Assert.Equal("Double float", clientModel.Methods[0].Parameters[4].ToString()); Assert.Equal("Double double", clientModel.Methods[0].Parameters[5].ToString()); Assert.Equal("Decimal decimal", clientModel.Methods[0].Parameters[6].ToString()); Assert.Equal("String string", clientModel.Methods[0].Parameters[7].ToString()); Assert.Equal("enum color", clientModel.Methods[0].Parameters[8].ToString()); Assert.Equal("ByteArray byte", clientModel.Methods[0].Parameters[9].ToString()); Assert.Equal("Boolean boolean", clientModel.Methods[0].Parameters[10].ToString()); Assert.Equal("Date date", clientModel.Methods[0].Parameters[11].ToString()); Assert.Equal("DateTime dateTime", clientModel.Methods[0].Parameters[12].ToString()); Assert.Equal("IList<String> array", clientModel.Methods[0].Parameters[13].ToString()); var variableEnumInPath = clientModel.Methods.First(m => m.Name == "list" && m.Group == null).Parameters.First(p => p.Name == "color" && p.Location == ParameterLocation.Path).Type as EnumType; Assert.NotNull(variableEnumInPath); Assert.Equal(variableEnumInPath.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" } }.ToList()); Assert.True(variableEnumInPath.ModelAsString); Assert.Empty(variableEnumInPath.Name); var variableEnumInQuery = clientModel.Methods.First(m => m.Name == "list" && m.Group == null).Parameters.First(p => p.Name == "color" && p.Location == ParameterLocation.Query).Type as EnumType; Assert.NotNull(variableEnumInQuery); Assert.Equal(variableEnumInQuery.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" }, new EnumValue { Name = "purple" } }.ToList()); Assert.True(variableEnumInQuery.ModelAsString); Assert.Empty(variableEnumInQuery.Name); var differentEnum = clientModel.Methods.First(m => m.Name == "list" && m.Group == "DiffEnums").Parameters.First(p => p.Name == "color" && p.Location == ParameterLocation.Query).Type as EnumType; Assert.NotNull(differentEnum); Assert.Equal(differentEnum.Values, new[] { new EnumValue { Name = "cyan" }, new EnumValue { Name = "yellow" } }.ToList()); Assert.True(differentEnum.ModelAsString); Assert.Empty(differentEnum.Name); var sameEnum = clientModel.Methods.First(m => m.Name == "get" && m.Group == "SameEnums").Parameters.First(p => p.Name == "color2" && p.Location == ParameterLocation.Query).Type as EnumType; Assert.NotNull(sameEnum); Assert.Equal(sameEnum.Values, new[] { new EnumValue { Name = "blue" }, new EnumValue { Name = "green" }, new EnumValue { Name = "red" } }.ToList()); Assert.True(sameEnum.ModelAsString); Assert.Empty(sameEnum.Name); var modelEnum = clientModel.ModelTypes.First(m => m.Name == "Product").Properties.First(p => p.Name == "color2").Type as EnumType; Assert.NotNull(modelEnum); Assert.Equal(modelEnum.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" } }.ToList()); Assert.True(modelEnum.ModelAsString); Assert.Empty(modelEnum.Name); var fixedEnum = clientModel.ModelTypes.First(m => m.Name == "Product").Properties.First(p => p.Name == "color").Type as EnumType; Assert.NotNull(fixedEnum); Assert.Equal(fixedEnum.Values, new[] { new EnumValue { Name = "red" }, new EnumValue { Name = "blue" }, new EnumValue { Name = "green" } }.ToList()); Assert.False(fixedEnum.ModelAsString); Assert.Equal("Colors", fixedEnum.Name); var fixedEnum2 = clientModel.ModelTypes.First(m => m.Name == "Product").Properties.First(p => p.Name == "color3").Type as EnumType; Assert.Equal(fixedEnum2, fixedEnum); Assert.Equal(1, clientModel.EnumTypes.Count); Assert.Equal("Colors", clientModel.EnumTypes.First().Name); }
public void TestcodeModelWithNoContent() { using (NewContext) { new Settings { Namespace = "Test", Input = @"Swagger\swagger-no-content.json" }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.Equal("DeleteBlob", codeModel.Methods[4].Name); Assert.True(codeModel.Methods[4].ReturnType.Body.IsPrimaryType(KnownPrimaryType.Object)); Assert.True( codeModel.Methods[4].Responses[HttpStatusCode.OK].Body.IsPrimaryType(KnownPrimaryType.Object)); Assert.Null(codeModel.Methods[4].Responses[HttpStatusCode.BadRequest].Body); } }
public void TestExternalReferences() { using (NewContext) { new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-external-ref-no-definitions.json") }; Modeler modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.NotNull(codeModel); Assert.Equal(2, codeModel.ModelTypes.Count); } }
public void TestClientModelWithDifferentReturnsTypesBasedOnStatusCode() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-multiple-response-schemas.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal("getSameResponse", clientModel.Methods[0].Name); Assert.Equal("IList<pet>", clientModel.Methods[0].ReturnType.ToString()); Assert.Equal("IList<pet>", clientModel.Methods[0].Responses[HttpStatusCode.OK].ToString()); Assert.Equal("IList<pet>", clientModel.Methods[0].Responses[HttpStatusCode.Accepted].ToString()); Assert.Equal("postInheretedTypes", clientModel.Methods[1].Name); Assert.Equal("pet", clientModel.Methods[1].ReturnType.ToString()); Assert.Equal("dog", clientModel.Methods[1].Responses[HttpStatusCode.OK].ToString()); Assert.Equal("cat", clientModel.Methods[1].Responses[HttpStatusCode.Accepted].ToString()); Assert.Equal("patchDifferentStreamTypesNoContent", clientModel.Methods[6].Name); Assert.Equal("VirtualMachineGetRemoteDesktopFileResponse", clientModel.Methods[6].ReturnType.ToString()); Assert.Equal("VirtualMachineGetRemoteDesktopFileResponse", clientModel.Methods[6].Responses[HttpStatusCode.OK].ToString()); Assert.Null(clientModel.Methods[6].Responses[HttpStatusCode.NoContent].Body); }
public void TestClientModelWithNoContent() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = @"Swagger\swagger-no-content.json" }); var clientModel = modeler.Build(); Assert.Equal("DeleteBlob", clientModel.Methods[4].Name); Assert.Equal(PrimaryType.Object, clientModel.Methods[4].ReturnType.Body); Assert.Equal(PrimaryType.Object, clientModel.Methods[4].Responses[HttpStatusCode.OK].Body); Assert.Null(clientModel.Methods[4].Responses[HttpStatusCode.BadRequest].Body); }
public void TestClientModelWithRecursiveTypes() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-recursive-type.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal("Product", clientModel.ModelTypes.First(m => m.Name == "Product").Name); Assert.Equal("product_id", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[0].Name); Assert.Equal("String", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[0].Type.ToString()); }
public void TestCompositeConstants() { using (NewContext) { new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-composite-constants.json") }; var modeler = new SwaggerModeler(); var codeModel = modeler.Build(); Assert.Equal(false, codeModel.ModelTypes.First(m => m.Name == "NetworkInterfaceIPConfigurationPropertiesFormat").ContainsConstantProperties); Assert.Equal(false, codeModel.ModelTypes.First(m => m.Name == "IPConfigurationPropertiesFormat").ContainsConstantProperties); } }
public void TestClientModelWithPayloadFlatteningViaXMSClientFlatten() { using (NewContext) { var setting = new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-x-ms-client-flatten.json") }; var modeler = new SwaggerModeler(); var clientModel = modeler.Build(); SwaggerExtensions.NormalizeClientModel(clientModel); Assert.NotNull(clientModel); Assert.Equal(8, clientModel.ModelTypes.Count); Assert.True(clientModel.ModelTypes.Any(m => m.Name == "BaseProduct")); Assert.True(clientModel.ModelTypes.Any(m => m.Name == "SimpleProduct")); Assert.True(clientModel.ModelTypes.Any(m => m.Name == "ConflictedProduct")); Assert.True(clientModel.ModelTypes.Any(m => m.Name == "ConflictedProductProperties")); // Since it's referenced in the response Assert.True(clientModel.ModelTypes.Any(m => m.Name == "RecursiveProduct")); Assert.True(clientModel.ModelTypes.Any(m => m.Name == "Error")); Assert.True(clientModel.ModelTypes.Any(m => m.Name == "ProductWithInheritance")); Assert.True(clientModel.ModelTypes.Any(m => m.Name == "BaseFlattenedProduct")); var simpleProduct = clientModel.ModelTypes.First(m => m.Name == "SimpleProduct"); Assert.True(simpleProduct.Properties.Any(p => (p.SerializedName == "details.max_product_display_name") && (p.Name == "MaxProductDisplayName"))); Assert.True(simpleProduct.Properties.Any(p => (p.SerializedName == "details.max_product_capacity") && (p.Name == "MaxProductCapacity"))); Assert.Equal("@odata.value", simpleProduct.Properties.FirstOrDefault( p => p.SerializedName == "details.max_product_image.@odata\\\\.value").Name.FixedValue); var conflictedProduct = clientModel.ModelTypes.First(m => m.Name == "ConflictedProduct"); Assert.True(conflictedProduct.Properties.Any(p => (p.SerializedName == "max_product_display_name") && (p.Name.FixedValue == "max_product_display_name"))); Assert.Equal("MaxProductDisplayName2", conflictedProduct.Properties.FirstOrDefault( p => p.SerializedName == "details.max_product_display_name").Name); Assert.Equal("MaxProductDisplayName1", conflictedProduct.Properties.First(p => p.SerializedName == "simpleDetails.max_product_display_name") .Name); Assert.Equal("ConflictedProductBaseProductDescription", conflictedProduct.Properties.First(p => p.SerializedName == "details.base_product_description").Name); var recursiveProduct = clientModel.ModelTypes.First(m => m.Name == "RecursiveProduct"); Assert.Equal("Name", recursiveProduct.Properties.First(p => p.SerializedName == "properties.name").Name); Assert.Equal("Parent", recursiveProduct.Properties.First(p => p.SerializedName == "properties.parent").Name); var error = clientModel.ModelTypes.First(m => m.Name == "Error"); Assert.Equal(3, error.Properties.Count); Assert.Equal("Code", error.Properties.First(p => p.SerializedName == "code").Name); Assert.Equal("Message", error.Properties.First(p => p.SerializedName == "message").Name); Assert.Equal("ParentError", error.Properties.First(p => p.SerializedName == "parentError").Name); } }
public void TestConstants() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = @"Swagger\swagger-validation.json" }); var clientModel = modeler.Build(); Assert.Equal("myintconst", clientModel.Methods[0].Parameters[4].Name); Assert.Equal(PrimaryType.Int, clientModel.Methods[0].Parameters[4].Type); Assert.Equal(true, clientModel.Methods[0].Parameters[4].IsConstant); Assert.Equal("0", clientModel.Methods[0].Parameters[4].DefaultValue); Assert.Equal("mystrconst", clientModel.Methods[0].Parameters[5].Name); Assert.Equal(PrimaryType.String, clientModel.Methods[0].Parameters[5].Type); Assert.Equal(true, clientModel.Methods[0].Parameters[5].IsConstant); Assert.Equal("constant", clientModel.Methods[0].Parameters[5].DefaultValue); Assert.Equal("myintconst", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[5].Name); Assert.Equal(PrimaryType.Int, clientModel.ModelTypes.First(m => m.Name == "Product").Properties[5].Type); Assert.Equal(true, clientModel.ModelTypes.First(m => m.Name == "Product").Properties[5].IsConstant); Assert.Equal("0", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[5].DefaultValue); Assert.Equal("mystrconst", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[6].Name); Assert.Equal(PrimaryType.String, clientModel.ModelTypes.First(m => m.Name == "Product").Properties[6].Type); Assert.Equal(true, clientModel.ModelTypes.First(m => m.Name == "Product").Properties[6].IsConstant); Assert.Equal("constant", clientModel.ModelTypes.First(m => m.Name == "Product").Properties[6].DefaultValue); }
public void TestClientWithValidation() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-validation.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); var methods = codeModel.Methods.ToList(); Assert.Equal("resourceGroupName", methods[0].Parameters[1].Name); Assert.Equal(true, methods[0].Parameters[1].IsRequired); Assert.Equal(3, methods[0].Parameters[1].Constraints.Count); Assert.Equal("10", methods[0].Parameters[1].Constraints[Constraint.MaxLength]); Assert.Equal("3", methods[0].Parameters[1].Constraints[Constraint.MinLength]); Assert.Equal("[a-zA-Z0-9]+", methods[0].Parameters[1].Constraints[Constraint.Pattern]); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.MultipleOf)); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.ExclusiveMaximum)); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.ExclusiveMinimum)); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.InclusiveMinimum)); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.InclusiveMaximum)); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.MinItems)); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.MaxItems)); Assert.False(methods[0].Parameters[1].Constraints.ContainsKey(Constraint.UniqueItems)); Assert.Equal("id", methods[0].Parameters[2].Name); Assert.Equal(3, methods[0].Parameters[2].Constraints.Count); Assert.Equal("10", methods[0].Parameters[2].Constraints[Constraint.MultipleOf]); Assert.Equal("100", methods[0].Parameters[2].Constraints[Constraint.InclusiveMinimum]); Assert.Equal("1000", methods[0].Parameters[2].Constraints[Constraint.InclusiveMaximum]); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.ExclusiveMaximum)); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.ExclusiveMinimum)); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.MaxLength)); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.MinLength)); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.Pattern)); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.MinItems)); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.MaxItems)); Assert.False(methods[0].Parameters[2].Constraints.ContainsKey(Constraint.UniqueItems)); Assert.Equal("apiVersion", methods[0].Parameters[3].Name); Assert.NotNull(methods[0].Parameters[3].ClientProperty); Assert.Equal(1, methods[0].Parameters[3].Constraints.Count); Assert.Equal("\\d{2}-\\d{2}-\\d{4}", methods[0].Parameters[3].Constraints[Constraint.Pattern]); Assert.Equal("Product", codeModel.ModelTypes.First(m => m.Name == "Product").Name); Assert.Equal("DisplayNames", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Name); Assert.Equal(3, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.Count); Assert.Equal("6", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints[Constraint.MaxItems]); Assert.Equal("0", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints[Constraint.MinItems]); Assert.Equal("true", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints[Constraint.UniqueItems]); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.ExclusiveMaximum)); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.ExclusiveMinimum)); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.InclusiveMaximum)); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.InclusiveMinimum)); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.MultipleOf)); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.MinLength)); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.MaxLength)); Assert.False(codeModel.ModelTypes.First(m => m.Name == "Product").Properties[2].Constraints.ContainsKey(Constraint.Pattern)); Assert.Equal("Capacity", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Name); Assert.Equal(2, codeModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Constraints.Count); Assert.Equal("100", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Constraints[Constraint.ExclusiveMaximum]); Assert.Equal("0", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Constraints[Constraint.ExclusiveMinimum]); }
public void TestClientModelWithResponseHeaders() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-response-headers.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal(2, clientModel.Methods.Count); Assert.Equal(2, clientModel.Methods[0].Responses.Count); Assert.Equal("list-Headers", clientModel.Methods[0].Responses[HttpStatusCode.OK].Headers.Name); Assert.Equal(3, ((CompositeType)clientModel.Methods[0].Responses[HttpStatusCode.OK].Headers).Properties.Count); Assert.Equal("list-Headers", clientModel.Methods[0].Responses[HttpStatusCode.Created].Headers.Name); Assert.Equal(3, ((CompositeType)clientModel.Methods[0].Responses[HttpStatusCode.Created].Headers).Properties.Count); Assert.Equal("list-Headers", clientModel.Methods[0].ReturnType.Headers.Name); Assert.Equal(3, ((CompositeType)clientModel.Methods[0].ReturnType.Headers).Properties.Count); Assert.Equal(1, clientModel.Methods[1].Responses.Count); Assert.Equal("create-Headers", clientModel.Methods[1].Responses[HttpStatusCode.OK].Headers.Name); Assert.Equal(3, ((CompositeType)clientModel.Methods[1].Responses[HttpStatusCode.OK].Headers).Properties.Count); Assert.Equal("create-Headers", clientModel.Methods[1].ReturnType.Headers.Name); Assert.Equal(3, ((CompositeType)clientModel.Methods[1].ReturnType.Headers).Properties.Count); Assert.True(clientModel.HeaderTypes.Any(c => c.Name == "list-Headers")); Assert.True(clientModel.HeaderTypes.Any(c => c.Name == "create-Headers")); }
public void TestClientModelWithStreamAndByteArray() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-streaming.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal("GetWithStreamFormData", clientModel.Methods[0].Name); Assert.Equal("Stream", clientModel.Methods[0].Parameters[0].Type.Name); Assert.Equal("Stream", clientModel.Methods[0].ReturnType.ToString()); Assert.Equal("Stream", clientModel.Methods[0].Responses[HttpStatusCode.OK].ToString()); Assert.Equal("PostWithByteArrayFormData", clientModel.Methods[1].Name); Assert.Equal("ByteArray", clientModel.Methods[1].Parameters[0].Type.Name); Assert.Equal("ByteArray", clientModel.Methods[1].ReturnType.ToString()); Assert.Equal("ByteArray", clientModel.Methods[1].Responses[HttpStatusCode.OK].ToString()); Assert.Equal("GetWithStream", clientModel.Methods[2].Name); Assert.Equal("Stream", clientModel.Methods[2].ReturnType.ToString()); Assert.Equal("Stream", clientModel.Methods[2].Responses[HttpStatusCode.OK].ToString()); Assert.Equal("PostWithByteArray", clientModel.Methods[3].Name); Assert.Equal("ByteArray", clientModel.Methods[3].ReturnType.ToString()); Assert.Equal("ByteArray", clientModel.Methods[3].Responses[HttpStatusCode.OK].ToString()); }
public override CodeModel Build() { var compositeSwaggerModel = Parse(Settings.Input); if (compositeSwaggerModel == null) { throw ErrorManager.CreateError(Resources.ErrorParsingSpec); } if (!compositeSwaggerModel.Documents.Any()) { throw ErrorManager.CreateError(string.Format(CultureInfo.InvariantCulture, "{0}. {1}", Resources.ErrorParsingSpec, "Documents collection can not be empty.")); } if (compositeSwaggerModel.Info == null) { throw ErrorManager.CreateError(Resources.InfoSectionMissing); } // Ensure all the docs are absolute URIs or rooted paths for (var i = 0; i < compositeSwaggerModel.Documents.Count; i++) { var compositeDocument = compositeSwaggerModel.Documents[i]; if (!Settings.FileSystemInput.IsCompletePath(compositeDocument) || !Settings.FileSystemInput.FileExists(compositeDocument)) { // Otherwise, root it from the current path compositeSwaggerModel.Documents[i] = Settings.FileSystemInput.MakePathRooted(Settings.FileSystemInput.GetParentDir(Settings.Input), compositeDocument); } } // construct merged swagger document var mergedSwagger = new YamlMappingNode(); mergedSwagger.Set("info", (Settings.FileSystemInput.ReadAllText(Settings.Input).ParseYaml() as YamlMappingNode)?.Get("info") as YamlMappingNode); // merge child swaggers foreach (var childSwaggerPath in compositeSwaggerModel.Documents) { var childSwaggerRaw = Settings.FileSystemInput.ReadAllText(childSwaggerPath); childSwaggerRaw = SwaggerParser.Normalize(childSwaggerPath, childSwaggerRaw); var childSwagger = childSwaggerRaw.ParseYaml() as YamlMappingNode; if (childSwagger == null) { throw ErrorManager.CreateError("Failed parsing referenced Swagger file {0}.", childSwaggerPath); } // remove info var info = childSwagger.Get("info") as YamlMappingNode; var version = info.Get("version"); info.Remove("title"); info.Remove("description"); info.Remove("version"); // fix up api version var apiVersionParam = (childSwagger.Get("parameters") as YamlMappingNode)?.Children?.FirstOrDefault(param => ((param.Value as YamlMappingNode)?.Get("name") as YamlScalarNode)?.Value == "api-version"); var apiVersionParamName = (apiVersionParam?.Key as YamlScalarNode)?.Value; if (apiVersionParamName != null) { var paths = ((childSwagger.Get("paths") as YamlMappingNode)?.Children?.Values ?? Enumerable.Empty <YamlNode>()).Concat ((childSwagger.Get("x-ms-paths") as YamlMappingNode)?.Children?.Values ?? Enumerable.Empty <YamlNode>()); var methods = paths.OfType <YamlMappingNode>().SelectMany(path => path.Children.Values.OfType <YamlMappingNode>()); var parameters = methods.SelectMany(method => (method.Get("parameters") as YamlSequenceNode)?.Children?.OfType <YamlMappingNode>() ?? Enumerable.Empty <YamlMappingNode>()); var apiVersionParams = parameters.Where(param => (param.Get("$ref") as YamlScalarNode)?.Value == $"#/parameters/{apiVersionParamName}"); foreach (var param in apiVersionParams) { param.Remove("$ref"); foreach (var child in (apiVersionParam?.Value as YamlMappingNode).Children) { param.Children.Add(child); } param.Set("enum", new YamlSequenceNode(version)); } } // merge mergedSwagger = mergedSwagger.MergeWith(childSwagger); } // remove apiVersion client property var mergedSwaggerApiVersionParam = (mergedSwagger.Get("parameters") as YamlMappingNode)?.Children?.FirstOrDefault(param => ((param.Value as YamlMappingNode)?.Get("name") as YamlScalarNode)?.Value == "api-version"); var mergedSwaggerApiVersionParamName = (mergedSwaggerApiVersionParam?.Key as YamlScalarNode)?.Value; if (mergedSwaggerApiVersionParamName != null) { (mergedSwagger.Get("parameters") as YamlMappingNode).Remove(mergedSwaggerApiVersionParamName); } // CodeModel compositeClient = InitializeServiceClient(compositeSwaggerModel); using (NewContext) { var swaggerModeler = new SwaggerModeler(); return(swaggerModeler.Build(SwaggerParser.Parse(Settings.Input, mergedSwagger.Serialize()))); } }
public void TestClientModelWithMethodGroups() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = @"Swagger\swagger-optional-params.json" }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal(0, clientModel.Methods.Count(m => m.Group == null)); Assert.Equal(2, clientModel.Methods.Count(m => m.Group == "Widgets")); Assert.Equal("List", clientModel.Methods[0].Name); }
public void TestcodeModelFromSimpleSwagger() { using (NewContext) { new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-simple-spec.json") }; Modeler modeler = new SwaggerModeler(); var codeModel = modeler.Build(); var description = "The Products endpoint returns information about the Uber products offered at a given location. The response includes the display name and other details about each product, and lists the products in the proper display order."; var summary = "Product Types"; Assert.NotNull(codeModel); Assert.Equal(2, codeModel.Properties.Count); Assert.True( codeModel.Properties.Any(p => p.Name.EqualsIgnoreCase("subscriptionId"))); Assert.True( codeModel.Properties.Any(p => p.Name.EqualsIgnoreCase("apiVersion"))); Assert.Equal("2014-04-01-preview", codeModel.ApiVersion); Assert.Equal("https://management.azure.com/", codeModel.BaseUrl); Assert.Equal("Some cool documentation.", codeModel.Documentation); //var allMethods = codeModel.Operations.SelectMany(each => each.Methods); Assert.Equal(2, codeModel.Methods.Count); Assert.Equal("List", codeModel.Methods[0].Name); Assert.NotEmpty(codeModel.Methods[0].Description); Assert.Equal(description, codeModel.Methods[0].Description); Assert.NotEmpty(codeModel.Methods[0].Summary); Assert.Equal(summary, codeModel.Methods[0].Summary); Assert.Equal(HttpMethod.Get, codeModel.Methods[0].HttpMethod); Assert.Equal(3, codeModel.Methods[0].Parameters.Count); Assert.Equal("subscriptionId", codeModel.Methods[0].Parameters[0].Name); Assert.NotNull(codeModel.Methods[0].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", codeModel.Methods[0].Parameters[1].Name); Assert.Equal("resourceGroupName", codeModel.Methods[0].Parameters[1].SerializedName); Assert.Equal("Resource Group ID.", codeModel.Methods[0].Parameters[1].Documentation); Assert.Equal(true, codeModel.Methods[0].Parameters[0].IsRequired); Assert.Equal(ParameterLocation.Path, codeModel.Methods[0].Parameters[0].Location); Assert.Equal("String", codeModel.Methods[0].Parameters[0].ModelType.Name); Assert.Equal("Reset", codeModel.Methods[1].Name); Assert.Equal("Product", codeModel.ModelTypes.First(m => m.Name == "Product").Name); Assert.Equal("Product", codeModel.ModelTypes.First(m => m.Name == "Product").SerializedName); Assert.Equal("The product title.", codeModel.ModelTypes.First(m => m.Name == "Product").Summary); Assert.Equal("The product documentation.", codeModel.ModelTypes.First(m => m.Name == "Product").Documentation); Assert.Equal("A product id.", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[0].Summary); Assert.Equal("ProductId", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[0].Name); Assert.Equal("product_id", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[0].SerializedName); Assert.Null(codeModel.Methods[1].ReturnType.Body); Assert.Null(codeModel.Methods[1].Responses[HttpStatusCode.NoContent].Body); Assert.Equal(3, codeModel.Methods[1].Parameters.Count); Assert.Equal("subscriptionId", codeModel.Methods[1].Parameters[0].Name); Assert.Null(codeModel.Methods[1].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", codeModel.Methods[1].Parameters[1].Name); Assert.Equal("apiVersion", codeModel.Methods[1].Parameters[2].Name); Assert.Equal("Capacity", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[3].Name); Assert.Equal("100", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[3].DefaultValue); } }
public void TestExternalReferencesWithExtension() { Generator.Modeler modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-external-ref-no-definitions.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.True(clientModel.ModelTypes.First().Extensions.ContainsKey("x-ms-external")); }
public void TestClientModelWithInheritance() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-allOf.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal("pet", clientModel.ModelTypes.First(m => m.Name == "pet").Name); Assert.Equal("cat", clientModel.ModelTypes.First(m => m.Name == "cat").Name); Assert.Equal("pet", clientModel.ModelTypes.First(m => m.Name == "cat").BaseModelType.Name); Assert.Equal("breed", clientModel.ModelTypes.First(m => m.Name == "cat").Properties[0].Name); Assert.Equal(true, clientModel.ModelTypes.First(m => m.Name == "cat").Properties[0].IsRequired); Assert.Equal("color", clientModel.ModelTypes.First(m => m.Name == "cat").Properties[1].Name); Assert.Equal("siamese", clientModel.ModelTypes.First(m => m.Name == "siamese").Name); Assert.Equal("cat", clientModel.ModelTypes.First(m => m.Name == "siamese").BaseModelType.Name); }
public static void ProcessParameterizedHost(CodeModel codeModel) { using (NewContext) { if (codeModel == null) { throw new ArgumentNullException("codeModel"); } if (codeModel.Extensions.ContainsKey(ParameterizedHostExtension) && !hostChecked) { SwaggerModeler modeler = new SwaggerModeler(); modeler.Build(); var hostExtension = codeModel.Extensions[ParameterizedHostExtension] as JObject; if (hostExtension != null) { var hostTemplate = (string)hostExtension["hostTemplate"]; var parametersJson = hostExtension["parameters"].ToString(); var useSchemePrefix = true; if (hostExtension[UseSchemePrefix] != null) { useSchemePrefix = bool.Parse(hostExtension[UseSchemePrefix].ToString()); } var position = "first"; if (hostExtension[PositionInOperation] != null) { var pat = "^(fir|la)st$"; Regex r = new Regex(pat, RegexOptions.IgnoreCase); var text = hostExtension[PositionInOperation].ToString(); Match m = r.Match(text); if (!m.Success) { throw new InvalidOperationException(string.Format(CultureInfo.InvariantCulture, Resources.InvalidExtensionProperty, text, PositionInOperation, ParameterizedHostExtension, "first, last")); } position = text; } if (!string.IsNullOrEmpty(parametersJson)) { var jsonSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.None, MetadataPropertyHandling = MetadataPropertyHandling.Ignore }; var swaggerParams = JsonConvert.DeserializeObject <List <SwaggerParameter> >(parametersJson, jsonSettings); List <Parameter> hostParamList = new List <Parameter>(); foreach (var swaggerParameter in swaggerParams) { // Build parameter var parameterBuilder = new ParameterBuilder(swaggerParameter, modeler); var parameter = parameterBuilder.Build(); // check to see if the parameter exists in properties, and needs to have its name normalized if (codeModel.Properties.Any(p => p.SerializedName.EqualsIgnoreCase(parameter.SerializedName))) { parameter.ClientProperty = codeModel.Properties.Single( p => p.SerializedName.Equals(parameter.SerializedName)); } parameter.Extensions["hostParameter"] = true; hostParamList.Add(parameter); } foreach (var method in codeModel.Methods) { if (position.EqualsIgnoreCase("first")) { method.InsertRange(((IEnumerable <Parameter>)hostParamList).Reverse()); } else { method.AddRange(hostParamList); } } if (useSchemePrefix) { codeModel.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}{2}", modeler.ServiceDefinition.Schemes[0].ToString().ToLowerInvariant(), hostTemplate, modeler.ServiceDefinition.BasePath); } else { codeModel.BaseUrl = string.Format(CultureInfo.InvariantCulture, "{0}{1}", hostTemplate, modeler.ServiceDefinition.BasePath); } } } } } hostChecked = true; }
public void TestClientModelPolymorhism() { var modeler = new SwaggerModeler(new Settings { Namespace = "Test", Input = Path.Combine("Swagger", "swagger-polymorphism.json") }); var clientModel = modeler.Build(); Assert.NotNull(clientModel); Assert.Equal("Pet", clientModel.ModelTypes.First(m => m.Name == "Pet").Name); Assert.Equal("dtype", clientModel.ModelTypes.First(m => m.Name == "Pet").PolymorphicDiscriminator); Assert.Equal(2, clientModel.ModelTypes.First(m => m.Name == "Pet").Properties.Count); Assert.Equal("id", clientModel.ModelTypes.First(m => m.Name == "Pet").Properties[0].Name); Assert.Equal("description", clientModel.ModelTypes.First(m => m.Name == "Pet").Properties[1].Name); Assert.Equal("Cat", clientModel.ModelTypes.First(m => m.Name == "Cat").Name); Assert.Equal("Pet", clientModel.ModelTypes.First(m => m.Name == "Cat").BaseModelType.Name); Assert.Equal(1, clientModel.ModelTypes.First(m => m.Name == "Cat").Properties.Count); Assert.Equal("Lizard", clientModel.ModelTypes.First(m => m.Name == "Lizard").Name); Assert.Equal("lzd", clientModel.ModelTypes.First(m => m.Name == "Lizard").SerializedName); }