public void TestcodeModelFromSimpleSwagger() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-simple-spec.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); 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); var methods = codeModel.Methods.ToList(); Assert.Equal(2, methods.Count); Assert.Equal("List", methods[0].Name); Assert.NotEmpty(methods[0].Description); Assert.Equal(description, methods[0].Description); Assert.NotEmpty(methods[0].Summary); Assert.Equal(summary, methods[0].Summary); Assert.Equal(HttpMethod.Get, methods[0].HttpMethod); Assert.Equal(3, methods[0].Parameters.Count); Assert.Equal("subscriptionId", methods[0].Parameters[0].Name); Assert.NotNull(methods[0].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", methods[0].Parameters[1].Name); Assert.Equal("resourceGroupName", methods[0].Parameters[1].SerializedName); Assert.Equal("Resource Group ID.", methods[0].Parameters[1].Documentation); Assert.Equal(true, methods[0].Parameters[0].IsRequired); Assert.Equal(ParameterLocation.Path, methods[0].Parameters[0].Location); Assert.Equal("String", methods[0].Parameters[0].ModelType.Name); Assert.Equal("Reset", 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(methods[1].ReturnType.Body); Assert.Null(methods[1].Responses[HttpStatusCode.NoContent].Body); Assert.Equal(3, methods[1].Parameters.Count); Assert.Equal("subscriptionId", methods[1].Parameters[0].Name); Assert.Null(methods[1].Parameters[0].ClientProperty); Assert.Equal("resourceGroupName", methods[1].Parameters[1].Name); Assert.Equal("apiVersion", 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 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); var methods = codeModel.Methods.ToList(); Assert.Equal(2, methods.Count); Assert.Equal(2, methods[0].Responses.Count); Assert.Equal("ListHeaders", methods[0].Responses[HttpStatusCode.OK].Headers.Name); Assert.Equal(3, ((CompositeType)methods[0].Responses[HttpStatusCode.OK].Headers).Properties.Count); Assert.Equal("ListHeaders", methods[0].Responses[HttpStatusCode.Created].Headers.Name); Assert.Equal(3, ((CompositeType)methods[0].Responses[HttpStatusCode.Created].Headers).Properties.Count); Assert.Equal("ListHeaders", methods[0].ReturnType.Headers.Name); Assert.Equal(3, ((CompositeType)methods[0].ReturnType.Headers).Properties.Count); Assert.Equal(1, methods[1].Responses.Count); Assert.Equal("CreateHeaders", methods[1].Responses[HttpStatusCode.OK].Headers.Name); Assert.Equal(3, ((CompositeType)methods[1].Responses[HttpStatusCode.OK].Headers).Properties.Count); Assert.Equal("CreateHeaders", methods[1].ReturnType.Headers.Name); Assert.Equal(3, ((CompositeType)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 async Task <bool> Process() { try { using (Start) { AddMessageListener(); var files = await ListInputs(); if (files.Length != 1) { return(false); } var content = await ReadFile(files[0]); var fs = new MemoryFileSystem(); fs.VirtualStore.Add(files[0], new StringBuilder(content)); var serviceDefinition = SwaggerParser.Load(files[0], fs); var validator = new RecursiveObjectValidator(PropertyNameResolver.JsonName); foreach (var validationEx in validator.GetValidationExceptions(new Uri(files[0], UriKind.RelativeOrAbsolute), serviceDefinition)) { Logger.Instance.Log(validationEx); } } } catch { return(false); // replace by more verbose feedback } return(true); }
private IEnumerable <ValidationMessage> ValidateOpenAPISpec(string input, ServiceDefinitionMetadata metadata) { var validator = new RecursiveObjectValidator(PropertyNameResolver.JsonName); var serviceDefinition = SwaggerParser.Parse(input, File.ReadAllText(input)); return(validator.GetValidationExceptions(new Uri(input, UriKind.RelativeOrAbsolute), serviceDefinition, metadata).OfType <ValidationMessage>()); }
private async Task <bool> ShowSwaggerOperations() { AddAPIModelWizard.ProcessStarted(); bool parseSuccess = true; SwaggerParser SwaggerPar = new SwaggerParser(); ObservableList <ApplicationAPIModel> AAMTempList = new ObservableList <ApplicationAPIModel>(); ObservableList <ApplicationAPIModel> AAMCompletedList = new ObservableList <ApplicationAPIModel>(); foreach (TemplateFile XTF in AddAPIModelWizard.XTFList) { try { AAMTempList = await Task.Run(() => SwaggerPar.ParseDocument(XTF.FilePath)); AAMCompletedList = AAMTempList; } catch (Exception ex) { MessageBox.Show("Error Details:" + Environment.NewLine + ex.Message, "Failed to Parse the Swagger File" + XTF.FilePath, System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error, System.Windows.MessageBoxResult.None); GingerCoreNET.ReporterLib.Reporter.ToLog(GingerCoreNET.ReporterLib.eLogLevel.ERROR, "Error Details: " + ex.Message + " Failed to Parse the Swagger file " + XTF.FilePath); parseSuccess = false; } } AddAPIModelWizard.AAMList = AAMCompletedList; xApisSelectionGrid.DataSourceList = AddAPIModelWizard.AAMList; // AddAPIModelWizard.FinishEnabled = false; AddAPIModelWizard.ProcessEnded(); return(parseSuccess); }
public void GenerateSimpleService() { var service = new SwaggerParser().ConvertSwaggerService(s_swaggerService); service.Summary.Should().Be("TestApi"); service.Methods.Count.Should().Be(1); }
private async Task <bool> ShowSwaggerOperations() { AddAPIModelWizard.ProcessStarted(); bool parseSuccess = true; SwaggerParser SwaggerPar = new SwaggerParser(); ObservableList <ApplicationAPIModel> AAMTempList = new ObservableList <ApplicationAPIModel>(); ObservableList <ApplicationAPIModel> AAMCompletedList = new ObservableList <ApplicationAPIModel>(); try { AAMTempList = await Task.Run(() => SwaggerPar.ParseDocument(AddAPIModelWizard.URL)); AAMCompletedList = AAMTempList; } catch (Exception ex) { Reporter.ToUser(eUserMsgKeys.ParsingError, "Failed to Parse the Swagger File" + AddAPIModelWizard.URL); GingerCoreNET.ReporterLib.Reporter.ToLog(GingerCoreNET.ReporterLib.eLogLevel.ERROR, "Error Details: " + ex.Message + " Failed to Parse the Swagger file " + AddAPIModelWizard.URL); parseSuccess = false; } AddAPIModelWizard.AAMList = AAMCompletedList; xApisSelectionGrid.DataSourceList = AddAPIModelWizard.AAMList; // AddAPIModelWizard.FinishEnabled = false; AddAPIModelWizard.ProcessEnded(); return(parseSuccess); }
public void TestInputMapping() { var input = Path.Combine(Core.Utilities.Extensions.CodeBaseDirectory(typeof(MappingExtensionsTests)), "Resource", "swagger-payload-flatten.json"); var modeler = new SwaggerModeler(new Settings { PayloadFlatteningThreshold = 3 }); var clientModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); 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.Instance.FileSystemOutput.ReadAllText(Path.Combine("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; }")); } }
protected override async Task <bool> ProcessInternal() { var files = await ListInputs(); if (files.Length != 1) { return(false); } var content = await ReadFile(files[0]); var fs = new MemoryFileSystem(); fs.WriteAllText(files[0], content); var serviceDefinition = SwaggerParser.Load(files[0], fs); var validator = new RecursiveObjectValidator(PropertyNameResolver.JsonName); foreach (ValidationMessage validationEx in validator.GetValidationExceptions(new Uri(files[0], UriKind.RelativeOrAbsolute), serviceDefinition)) { LogValidationMessage(validationEx); } return(true); }
public async Task OnExecute(CommandLineApplication app) { var showDoc = (await _showDocStore.GetAll()).FirstOrDefault(x => x.Name == Name); if (showDoc == null) { Console.WriteLine($"Not Found Project {Name}"); return; } try { var docStr = await HttpClient.GetStringAsync(showDoc.SwaggerUrl); var document = SwaggerParser.ParseString(docStr); var request = document.ToShowDocRequest(); foreach (var item in request) { await ShowDocClient.UpdateByApi(showDoc, item); } Console.WriteLine("Sync Successfully!"); } catch (Exception e) { Console.WriteLine($"Sync failed: {e.StackTrace}"); } }
protected override async Task <bool> ProcessInternal() { new Settings { Namespace = await GetValue("namespace") }; var files = await ListInputs(); if (files.Length != 1) { return(false); } var content = await ReadFile(files[0]); var fs = new MemoryFileSystem(); fs.WriteAllText(files[0], content); var serviceDefinition = SwaggerParser.Load(files[0], fs); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(serviceDefinition); var genericSerializer = new ModelSerializer <CodeModel>(); var modelAsJson = genericSerializer.ToJson(codeModel); WriteFile("codeMode.yaml", modelAsJson, null); return(true); }
public ParseMultiFileSwaggerTests() { var resourceRoot = new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent; var filePath = Path.Combine(resourceRoot.FullName, Path.Combine("Resource", "arm-network", "2017-03-01", "swagger", "routeTable.json")); _serviceDefinition = SwaggerParser.Load(filePath, new FileSystem()); }
public void TestcodeModelWithStreamAndByteArray() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-streaming.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); var methods = codeModel.Methods.ToList(); Assert.Equal("GetWithStreamFormData", methods[0].Name); Assert.Equal("Stream", methods[0].Parameters[0].ModelType.Name); Assert.Equal("Stream", CreateCSharpResponseType(methods[0].ReturnType)); Assert.Equal("Stream", CreateCSharpResponseType(methods[0].Responses[HttpStatusCode.OK])); Assert.Equal("PostWithByteArrayFormData", methods[1].Name); Assert.Equal("ByteArray", methods[1].Parameters[0].ModelType.Name); Assert.Equal("ByteArray", CreateCSharpResponseType(methods[1].ReturnType)); Assert.Equal("ByteArray", CreateCSharpResponseType(methods[1].Responses[HttpStatusCode.OK])); Assert.Equal("GetWithStream", methods[2].Name); Assert.Equal("Stream", CreateCSharpResponseType(methods[2].ReturnType)); Assert.Equal("Stream", CreateCSharpResponseType(methods[2].Responses[HttpStatusCode.OK])); Assert.Equal("PostWithByteArray", methods[3].Name); Assert.Equal("ByteArray", CreateCSharpResponseType(methods[3].ReturnType)); Assert.Equal("ByteArray", CreateCSharpResponseType(methods[3].Responses[HttpStatusCode.OK])); }
public void APILearnSwaggerMetroTest() { //Arrange SwaggerParser wsdlParser = new SwaggerParser(); ObservableList <ApplicationAPIModel> AAMSList = new ObservableList <ApplicationAPIModel>(); //Act string path = TestResources.GetTestResourcesFile(@"AutoPilot\Swagger\swagger.json"); wsdlParser.ParseDocument(path, AAMSList); //Assert Assert.AreEqual(AAMSList.Count, 22, "Is API's equal to 6"); Assert.AreEqual(AAMSList[0].EndpointURL, "https://petstore.swagger.io/v2/pet", "Is EndpointURL equal"); Assert.AreEqual(String.IsNullOrEmpty(AAMSList[0].RequestBody), false, "Is body not empty equal"); Assert.AreEqual(AAMSList[0].AppModelParameters.Count, 8, "are parameters are equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[0].PlaceHolder, "<ID>", "are parameters are equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[1].PlaceHolder, "<ID1>", "are parameters are equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[2].PlaceHolder, "<NAME>", "are parameters are equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[3].PlaceHolder, "<NAME1>", "are parameters are equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[4].PlaceHolder, "<PHOTOURLS[0]>", "Is parameter name equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[5].PlaceHolder, "<ID2>", "Is parameter name equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[6].PlaceHolder, "<NAME2>", "Is parameter name equal"); Assert.AreEqual(AAMSList[0].AppModelParameters[7].PlaceHolder, "<STATUS>", "Is parameter name equal"); }
public void ParseSecurityDefinitionType() { var swaggerContent = File.ReadAllText(@"Resource\SerializationTests\SerializationTests.json"); var definition = SwaggerParser.Parse(swaggerContent); Assert.Equal(SecuritySchemeType.OAuth2, definition.SecurityDefinitions["petstore_auth"].SecuritySchemeType); Assert.Equal(SecuritySchemeType.ApiKey, definition.SecurityDefinitions["api_key"].SecuritySchemeType); }
public ParseSingleFileSwaggerTests() { var resourceRoot = new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent; var fileRelativePath = Path.Combine("Resource", "arm-storage", "2017-06-01", "swagger", "storage.json"); var filePath = Path.Combine(resourceRoot.FullName, fileRelativePath); _serviceDefinition = SwaggerParser.Load(filePath, new FileSystem()); }
public ParseSwaggerWithBlacklistedEndpointTests() { var resourceRoot = new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.Parent; var fileRelativePath = Path.Combine("Resource", "arm-web", "2016-03-01", "swagger", "DeletedWebApps.json"); var filePath = Path.Combine(resourceRoot.FullName, fileRelativePath); _serviceDefinition = SwaggerParser.Load(filePath, new FileSystem()); }
public void TestYamlParsing() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-simple-spec.yaml"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); }
public void GlobalResponsesReference() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-global-responses.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.Equal(1, codeModel.Methods[0].Responses.Count); Assert.NotNull(codeModel.Methods[0].Responses[HttpStatusCode.OK]); }
public void TestCompositeConstants() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-composite-constants.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.Equal(false, codeModel.ModelTypes.First(m => m.Name == "NetworkInterfaceIPConfigurationPropertiesFormat").ContainsConstantProperties); Assert.Equal(false, codeModel.ModelTypes.First(m => m.Name == "IPConfigurationPropertiesFormat").ContainsConstantProperties); }
public void TestCustomPaths() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-x-ms-paths.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); Assert.Equal(3, codeModel.Methods.Count()); Assert.True(codeModel.Methods.All(m => m.Url == "/values/foo")); }
public void DefaultReturnsCorrectType() { 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))); var retType = codeModel.Methods.First(m => m.Name == "PatchDefaultResponse"); Assert.Equal("Pet", CreateCSharpResponseType(retType.ReturnType)); }
public void GenerateCodeModel() { var input = Path.Combine(CodeBaseDirectory, "..", "..", "..", "Resource", "Swagger", "deprecated.yaml"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); var output = Path.Combine(CodeBaseDirectory, "..", "..", "..", "Expected", "deprecated", "deprecated.json"); Directory.CreateDirectory(Path.GetDirectoryName(output)); File.WriteAllText(output, JsonConvert.SerializeObject(codeModel, Formatting.Indented)); }
public void TestcodeModelWithMethodGroups() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-optional-params.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); Assert.Equal(0, codeModel.Methods.Count(m => m.Group == null)); Assert.Equal(2, codeModel.Methods.Count(m => m.Group == "Widgets")); Assert.Equal("List", codeModel.Methods[0].Name); }
public void TestRealPathRegular() { var input = Path.Combine("Resource", "Swagger", "swagger-xml.yaml"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); foreach (var property in codeModel.ModelTypes.SelectMany(m => m.Properties)) { Assert.Equal(property.Name, string.Join(".", property.RealPath)); Assert.Equal(property.XmlName, string.Join(".", property.RealXmlPath)); } }
public SwaggerParserV3_Tests() { _showdoc = new ShowDocEntity() { AppKey = "5b2451ec0a8b49f5323645e6d50d9b29557907599", AppToken = "170c09f45fe6e70642cc17c44ff9213f1222612682", ShowDocUrl = "https://www.showdoc.cc/server/api/item/updateByApi" }; var str = File.ReadAllText(AppContext.BaseDirectory + "swaggerDocsV3.json", Encoding.UTF8); _documentCoreV3 = SwaggerParser.ParseString(str) as SwaggerDocumentCoreV3; }
public void AllowVendorExtensionInPath() { var input = Path.Combine("Resource", "Swagger", "vendor-extension-in-path.json"); var modeler = new SwaggerModeler(); var clientModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); // should return a valid model. Assert.NotNull(clientModel); // there should be one method in this generated api. Assert.Equal(1, modeler.CodeModel.Methods.Count); }
private IEnumerable <ValidationMessage> ValidateSwagger(string input, ServiceDefinitionMetadata metadata) { // Most rules are to be applied for ARM documents // Also, most rules need to be run over the composite document (i.e. AFTER merge state) // hence the defaults using (NewContext) { var validator = new RecursiveObjectValidator(PropertyNameResolver.JsonName); var serviceDefinition = SwaggerParser.Parse(input, File.ReadAllText(input)); return(validator.GetValidationExceptions(new Uri(input, UriKind.RelativeOrAbsolute), serviceDefinition, metadata).OfType <ValidationMessage>()); } }
public SwaggerParserV2_Tests() { _showdoc = new ShowDocEntity() { AppKey = "a338fb0d83c6f4b660bc2706b92e89451844587564", AppToken = "e1511a84db06d25150377970f328e9f7572510835", ShowDocUrl = "https://www.showdoc.cc/server/api/item/updateByApi" }; var str = File.ReadAllText(AppContext.BaseDirectory + "swaggerDocsV2.json", Encoding.UTF8); _document = SwaggerParser.ParseString(str) as SwaggerDocumentCoreV2; }
public void TestcodeModelWithRecursiveTypes() { var input = Path.Combine(CodeBaseDirectory, "Resource", "Swagger", "swagger-recursive-type.json"); var modeler = new SwaggerModeler(); var codeModel = modeler.Build(SwaggerParser.Parse(File.ReadAllText(input))); Assert.NotNull(codeModel); Assert.Equal("Product", codeModel.ModelTypes.First(m => m.Name == "Product").Name); Assert.Equal("ProductId", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[0].Name); Assert.Equal("String", codeModel.ModelTypes.First(m => m.Name == "Product").Properties[0].ModelType.Name); }