public async Task CheckAncestorTraversal() { using (var fileSystem = GenerateCodeForTestFromSpec()) { var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); } }
public async Task UseCases() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // Expected Files Assert.True(fileSystem.FileExists(@"Models/Enum2CustomName.cs")); Assert.True(fileSystem.FileExists(@"Models/Enum3CustomName.cs")); Assert.True(fileSystem.FileExists(@"Models/Enum4CustomName.cs")); Assert.True(fileSystem.FileExists(@"Models/Enum5CustomName.cs")); // check that (supposedly) overridden stuff doesn't exist. foreach (var file in fileSystem.VirtualStore.Values) { Assert.False(file.ToString().Contains("OVERRIDDEN")); } // enum 3-5 must have descriptions Assert.True(fileSystem.ReadAllText(@"Models/Enum3CustomName.cs").Contains("is cool")); Assert.True(fileSystem.ReadAllText(@"Models/Enum4CustomName.cs").Contains("is cool")); Assert.True(fileSystem.ReadAllText(@"Models/Enum5CustomName.cs").Contains("is cool")); // enum 4-5 must have different name than value Assert.True(fileSystem.ReadAllText(@"Models/Enum4CustomName.cs").Contains("4aValue")); Assert.True(fileSystem.ReadAllText(@"Models/Enum4CustomName.cs").Contains("4aName")); Assert.True(fileSystem.ReadAllText(@"Models/Enum5CustomName.cs").Contains("5aValue")); Assert.True(fileSystem.ReadAllText(@"Models/Enum5CustomName.cs").Contains("5aName")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination //fileSystem.SaveFilesToTemp("name_collision"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); } }
public async Task EmptyPathObjectCodeGenerationTest() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // check for the expected class. Assert.True(fileSystem.FileExists(@"GeneratedCode\APIwithcollectionformat.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); } }
public async Task CompileAndVerifyServerCode() { using (NewContext) { MemoryFileSystem fileSystem = CreateMockFilesystem(); var settings = new Settings { Modeler = "Swagger", CodeGenerator = "CSharp", FileSystemInput = fileSystem, OutputDirectory = "", Namespace = "Test", CodeGenerationMode = "rest-server" }; using (fileSystem = $"{GetType().Name}".GenerateCodeInto(fileSystem, settings)) { var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp($"{GetType().Name}"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Load and reflect on the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // Verify the server controller var simpleApi = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.ValueController"); Assert.NotNull(simpleApi); Assert.NotNull(simpleApi.GetMethod("Get")); Assert.Equal(simpleApi.GetMethod("Get").ReturnType.Name, "SimpleModel"); Assert.NotEmpty(simpleApi.GetMethod("Get").CustomAttributes.Where(a => a.AttributeType.Name == "HttpGetAttribute")); // Verify the model var simpleModel = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.SimpleModel"); Assert.NotNull(simpleModel); } } }
public async Task PropertyNamesWithLeadingUnderscores() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // Expected Files Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\TestObject.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp("bug1125"); // Or just use this to see the generated code in VsCode :D // ShowGeneratedCode(fileSystem); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = Assembly.Load(result.Output.GetBuffer()); Assert.NotNull(asm); // verify that we have the class we expected var testObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.TestObject"); Assert.NotNull(testObject); // verify the property is generated var property1 = testObject.GetProperty("_name"); Assert.NotNull(property1); // verify the property is generated var property2 = testObject.GetProperty("Name"); Assert.NotNull(property2); // verify the property is generated var property3 = testObject.GetProperty("_namE"); Assert.NotNull(property3); } }
public async Task DoubleQuestionMarksWhenUsingEnumsInAnArray() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // check for the expected class. Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\RecurrenceSchedule.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); var recurrenceSchedule = fileSystem.ReadFileAsText(@"GeneratedCode\Models\RecurrenceSchedule.cs"); Assert.NotNull(recurrenceSchedule); } }
public async Task CompositeSwaggerWithPayloadFlattening() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec(modeler: "CompositeSwagger")) { // Expected Files Assert.True(fileSystem.FileExists(Path.Combine("CompositeModel.cs"))); Assert.True(fileSystem.FileExists(Path.Combine("Models", "Param1.cs"))); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp("bug1288"); // Or just use this to see the generated code in VsCode :D // ShowGeneratedCode(fileSystem); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that we have the composite class we expected var testCompositeObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.CompositeModel"); Assert.NotNull(testCompositeObject); // verify that we have the class we expected var testObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.Param1"); Assert.NotNull(testObject); // verify the property is generated var property1 = testObject.GetProperty("Prop1"); Assert.NotNull(property1); // verify the property is generated var property2 = testObject.GetProperty("Prop2"); Assert.NotNull(property2); } }
public async Task SupportModelsNameOverride() { using (NewContext) { string modelsName = "MyModels"; var settings = new Settings { Modeler = "Swagger", CodeGenerator = "CSharp", OutputDirectory = "", Namespace = "Test", ModelsName = modelsName }; using (var fileSystem = $"{GetType().Name}".GenerateCodeInto(new MemoryFileSystem(), settings)) { // Expected Files Assert.True(fileSystem.FileExists($@"{modelsName}\ResultObject.cs")); var result = await Compile(settings.FileSystemOutput); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp($"{GetType().Name}"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that we have the class we expected var resultObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == $"Test.{modelsName}.ResultObject"); Assert.NotNull(resultObject); } } }
public async Task SupportCharFormatForString() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // Expected Files Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ResultObject.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ResultObjectWithDefault.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ResultObjectWithMinMax.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ResultObjectWithExclusiveMinMax.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ParamObject.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ParamObjectWithDefault.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp("bug1125"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that we have the class we expected var resultObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.ResultObject"); Assert.NotNull(resultObject); // verify the property is generated var property = resultObject.GetProperty("SingleLetter"); Assert.NotNull(property); // verify the type is as expected. Assert.Equal(property.PropertyType, typeof(char?)); } }
public async Task BatchTest() { var path = new DirectoryInfo(@"C:\PathToSpecs"); Assert.True(path.Exists, $"{path} does not exist"); // get all of the json and yaml files from filesystem var files = path.GetFiles("*.json", SearchOption.AllDirectories).Concat(path.GetFiles("*.yaml", SearchOption.AllDirectories)); Assert.True(files.Count() > 0, $"{path} does not contain any json or yaml files"); foreach (var file in files) { // Comment this block out if not needed if (!File.ReadAllText(file.FullName).Contains(@"""swagger"": ""2.0""")) { //skip files that are not swagger files. continue; } using (var memoryFileSystem = GenerateCodeForTestFromSpec(dirName: file.FullName)) { // Expected Files Assert.True(memoryFileSystem.GetFiles("", "*.cs", SearchOption.TopDirectoryOnly).GetUpperBound(0) > 0); Assert.True(memoryFileSystem.GetFiles("Models", "*.cs", SearchOption.TopDirectoryOnly).GetUpperBound(0) > 0); var result = await Compile(memoryFileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // memoryFileSystem.SaveFilesToTemp(file.Name); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, memoryFileSystem); Write(errors, memoryFileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, memoryFileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); } } }
public async Task CheckForCorrectParameterType() { using (var fileSystem = GenerateCodeForTestFromSpec()) { // Expected Files Assert.True(fileSystem.FileExists(@"GeneratedCode\SimpleAPI.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\SimpleAPIExtensions.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = Assembly.Load(result.Output.GetBuffer()); Assert.NotNull(asm); // verify that parameter is of correct type var simpleApi = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.SimpleAPI"); Assert.NotNull(simpleApi); var simpleApiMethod = simpleApi.GetMethod("TestMethodWithHttpMessagesAsync"); Assert.NotNull(simpleApiMethod); var simpleApiMethodParam = simpleApiMethod.GetParameters().FirstOrDefault(param => param.Name == "query"); Assert.NotNull(simpleApiMethodParam); Assert.Equal("System.String", simpleApiMethodParam.ParameterType.FullName); var simpleApiExtensions = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.SimpleAPIExtensions"); Assert.NotNull(simpleApiExtensions); var simpleApiExtensionsMethod = simpleApiExtensions.GetMethod("TestMethod"); Assert.NotNull(simpleApiExtensionsMethod); var simpleApiExtensionsMethodParam = simpleApiExtensionsMethod.GetParameters().FirstOrDefault(param => param.Name == "query"); Assert.NotNull(simpleApiExtensionsMethodParam); Assert.Equal("System.String", simpleApiExtensionsMethodParam.ParameterType.FullName); } }
public async Task EnsureHttpMessageAsyncDispose() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // check for the expected class. Assert.True(fileSystem.FileExists(@"TestOperationsExtensions.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that parameter is of correct type var testApi = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.TestOperationsExtensions"); Assert.NotNull(testApi); var testApiMethod = testApi.GetMethod("PutAsync"); Assert.NotNull(testApiMethod); var codeText = fileSystem.ReadAllText(@"TestOperationsExtensions.cs"); // get hold of the async func var methodSignature = "public static async System.Threading.Tasks.Task PutAsync(this ITestOperations operations, Body body = default(Body), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken))"; var regex = new Regex(Regex.Escape(methodSignature) + @"[^}]+"); var match = regex.Match(codeText); Assert.NotNull(match); // verify the function calls dispose on HTTPResponse object Assert.True(match.Groups[0].Value.Contains(".Dispose()")); } }
public async Task SupportDeprecatedOperations() { using (var fileSystem = GenerateCodeForTestFromSpec()) { // Expected Files Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ResultObject.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\DeprecatedExtensions.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\ApprovedExtensions.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp("bug1285"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = Assembly.Load(result.Output.GetBuffer()); Assert.NotNull(asm); // verify that deprecated_operation is marked correctly var deprecatedExtensions = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.DeprecatedExtensions"); Assert.NotNull(deprecatedExtensions); Assert.NotNull(deprecatedExtensions.GetMethod("Operation").GetCustomAttribute(typeof(System.ObsoleteAttribute))); // verify the other operations are not marked as deprecated var approvedExtensions = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.ApprovedExtensions"); Assert.NotNull(approvedExtensions); Assert.Null(approvedExtensions.GetMethod("Operation2").GetCustomAttribute(typeof(System.ObsoleteAttribute))); Assert.Null(approvedExtensions.GetMethod("Operation3").GetCustomAttribute(typeof(System.ObsoleteAttribute))); } }
public async Task CheckGeneratesValidCSharp() { var settings = new Settings { Namespace = "ExtensibleEnums" }; using (var fileSystem = $"{GetType().Name}".GenerateCodeInto(new MemoryFileSystem(), settings)) { // if newlines and stuff aren't excaped properly, compilation will fail var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); var extensibleEnumsModel = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "ExtensibleEnums.Models.DaysOfWeekExtensibleEnum"); Assert.NotNull(extensibleEnumsModel); var enumVals = extensibleEnumsModel.GetFields().Where(f => f.IsPublic && f.IsStatic && f.DeclaringType.ToString() == "ExtensibleEnums.Models.DaysOfWeekExtensibleEnum"); Assert.Equal(enumVals.Count(), 7); Assert.True(Enumerable.SequenceEqual(enumVals.Select(val => val.GetValue(null).ToString()), new List <string>() { "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday" })); } }
public async Task SupportModelNameCollisions() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // Expected Files Assert.True(fileSystem.FileExists(@"Models\Action.cs")); Assert.True(fileSystem.FileExists(@"Models\HttpOperationResponse.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination //fileSystem.SaveFilesToTemp("name_collision"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that we have the class we expected var resultObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.Action"); Assert.NotNull(resultObject); var resultObject2 = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.HttpOperationResponse"); Assert.NotNull(resultObject2); } }
public async Task CheckLruCodegenBehavior() { using (var fileSystem = GenerateCodeForTestFromSpec(codeGenerator: "Azure.CSharp")) { // Expected Files Assert.True(fileSystem.FileExists(@"GeneratedCode\SimpleAPI.cs")); // compilation is key in this test, as `x-ms-long-running-operation: false` // creates method that contains call to non-existent method. var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = Assembly.Load(result.Output.GetBuffer()); Assert.NotNull(asm); // verify that correct methods exist. var simpleApi = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.SimpleAPI"); Assert.NotNull(simpleApi); Assert.NotNull(simpleApi.GetMethod("Lru0WithHttpMessagesAsync")); Assert.NotNull(simpleApi.GetMethod("Lru1WithHttpMessagesAsync")); Assert.NotNull(simpleApi.GetMethod("Lru2WithHttpMessagesAsync")); Assert.Null(simpleApi.GetMethod("BeginLru0WithHttpMessagesAsync")); Assert.NotNull(simpleApi.GetMethod("BeginLru1WithHttpMessagesAsync")); Assert.Null(simpleApi.GetMethod("BeginLru2WithHttpMessagesAsync")); } }
public async Task VerifyUnderscoredClassMembers() { using (var fileSystem = GenerateCodeForTestFromSpec()) { var result = await Compile(fileSystem); // Expected Files Assert.True(fileSystem.FileExists(Path.Combine("GeneratedCode", "Models", "Pet.cs"))); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); var petModel = asm.ExportedTypes.First(type => type.FullName == "Test.Models.Pet"); var idMember = petModel.GetMembers().First(member => member.Name == "_id"); Assert.NotNull(idMember); // now read from the file to ensure we use this. to access the members var codeText = fileSystem.ReadFileAsText(Path.Combine("GeneratedCode", "Models", "Pet.cs")); // get hold of the ctor var regex = new Regex(Regex.Escape("public Pet(int _id, string name = default(string))") + @"[^}]+"); var match = regex.Match(codeText); Assert.NotNull(match); // verify the ctor has proper assignments Assert.True(match.Groups[0].Value.Contains("this._id = _id")); Assert.True(match.Groups[0].Value.Contains("this.Name = name")); } }
public async Task CheckForCorrectParameterType() { using (var fileSystem = GenerateCodeForTestFromSpec(codeGenerator: "Azure.CSharp")) { // Expected Files Assert.True(fileSystem.FileExists(@"Models\Page.cs")); Assert.True(fileSystem.FileExists(@"IProductsOperations.cs")); Assert.True(fileSystem.FileExists(@"ProductsOperationsExtensions.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that parameter is of correct type var ops = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.ProductsOperationsExtensions"); Assert.NotNull(ops); var opsMethod = ops.GetMethod("List"); Assert.NotNull(opsMethod); var opsMethodReturnType = opsMethod.ReturnType?.GetGenericArguments()?.FirstOrDefault(); Assert.NotNull(opsMethodReturnType); Assert.Equal(typeof(int?), opsMethodReturnType); } }
public async Task PolymorphicTypesAreNotConstants() { using (var fileSystem = GenerateCodeForTestFromSpec(new AutoRest.CSharp.Azure.PluginCsa())) { // Expected Files Assert.True(fileSystem.FileExists(@"JobDefinitionsOperations.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that class with the expected name is present var ops = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.JobDefinitionsOperationsExtensions"); Assert.NotNull(ops); // verify the method is there. var method = ops.GetMethod("ListResults"); Assert.NotNull(method); // verify that the parameter is there. Assert.True(method.GetParameters().Any(each => each.Name.EqualsIgnoreCase("DataServiceResultQuery"))); } }
/// <summary> /// Xml Serialization tests /// </summary> /// [Fact] public async Task CheckXmlSerialization() { using (var fileSystem = GenerateCodeForTestFromSpec()) { Assert.True(fileSystem.FileExists(@"Models\StorageServiceProperties.cs")); Assert.True(fileSystem.FileExists(@"SimpleAPI.cs")); fileSystem.WriteAllText("Program.cs", new FileSystem().ReadAllText(Path.Combine("Resource", "XmlSerialization", "GeneratedCode", "Program._cs"))); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); using (var service = new ServiceController()) { var program = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "XmlSerialization.Program"); dynamic test = program.GetConstructor(new Type[0]).Invoke(new object[0]); // var testResult = (int)program.GetMethod("Main").Invoke(null, new object[] {$"{service.Uri.AbsolutePath}/xml"}); int testResult = test.Main($"{service.Uri.AbsoluteUri}xml"); Assert.Equal(0, testResult); // Should also succeed. Assert.True(result.Succeeded); } } }
public async Task DoubleQuestionMarksWhenUsingEnumsInAnArray() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // check for the expected class. Assert.True(fileSystem.FileExists(@"Models\RecurrenceSchedule.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that we have the class we expected var recurrenceScheduleObject = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.RecurrenceSchedule"); Assert.NotNull(recurrenceScheduleObject); // verify the property is generated var prop = recurrenceScheduleObject.GetProperty("WeekDays"); Assert.NotNull(prop); var propGenericType = prop.PropertyType.GenericTypeArguments[0].GenericTypeArguments[0]; Assert.Equal(propGenericType.Name, "DayOfWeek"); Assert.True(propGenericType.GetTypeInfo().IsEnum); } }
public async Task EnsureCustomInitMethodInConstructors() { using (var fileSystem = GenerateCodeForTestFromSpec(codeGenerator: "Azure.CSharp")) { // Expected Files Assert.True(fileSystem.FileExists(@"Models\Product.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that parameter is of correct type var prod = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.Models.Product"); Assert.NotNull(prod); // find all ctors in the model and ensure they call CustomInit() var codeText = fileSystem.ReadAllText(@"Models\Product.cs"); Assert.True(reg.IsMatch(codeText)); var matches = reg.Matches(codeText); Assert.True(matches[0].Value.Contains("CustomInit()")); Assert.True(matches[1].Value.Contains("CustomInit()")); } }
public async Task CompileAndVerifyServerCode() { using (NewContext) { MemoryFileSystem fileSystem = CreateMockFilesystem(); var settings = new Settings { FileSystemInput = fileSystem, Namespace = "Test" , PayloadFlatteningThreshold = 3 }; using (fileSystem = $"{GetType().Name}".GenerateCodeInto(fileSystem, settings)) { var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination // fileSystem.SaveFilesToTemp($"{GetType().Name}"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Load and reflect on the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); } } }
public async Task EmptyDefaultResponseExceptionHandling() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec(new AutoRest.CSharp.Azure.PluginCsa())) { // check for the expected class. Assert.True(fileSystem.FileExists(@"ContainerServicesOperations.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // now read from the file to ensure we have the try catch block as expected var codeText = fileSystem.ReadAllText(@"ContainerServicesOperations.cs"); Assert.NotEmpty(codeText); // is a CloudException object created? Assert.True(codeText.Contains("new Microsoft.Rest.Azure.CloudException")); // are we deserializing response into CloudError object? Assert.True(codeText.Contains("Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>")); // are we setting the errorbody in exception? Assert.True(codeText.Contains("ex.Body = _errorBody;")); } }
public async Task VerifyNonNullableReturnTypes() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec()) { // check for the expected class. Assert.True(fileSystem.FileExists(@"ISimpleAPI.cs")); Assert.True(fileSystem.FileExists(@"SimpleAPIExtensions.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); var testApiExtensions = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.SimpleAPIExtensions"); Assert.NotNull(testApiExtensions); var testExtensionMethod = testApiExtensions.GetMethod("GetInt"); Assert.False(testExtensionMethod.ReturnType.IsNullableValueType()); } }
public async Task CheckForProperDescriptionEscaping() { using (var fileSystem = GenerateCodeForTestFromSpec()) { // if newlines and stuff aren't excaped properly, compilation will fail var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = Assembly.Load(result.Output.GetBuffer()); Assert.NotNull(asm); // verify that "Func<int>" doesn't exist in the sources (otherwise escaping is still insufficient, even if newlines were handled) var unescapedFiles = fileSystem .VirtualStore .Where(file => file.Key.EndsWith(".cs")) .Where(file => file.Value.ToString().Contains("Func<int>")); Assert.Empty(unescapedFiles); } }
private async Task <System.Type> GenerateModelType(string modelName) { using (var fileSystem = GenerateCodeForTestFromSpec()) { // Expected Files Assert.True(fileSystem.FileExists($@"GeneratedCode\Models\{modelName}.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that deprecated_operations are marked correctly var resultType = asm.ExportedTypes.FirstOrDefault(each => each.FullName == $"Test.Models.{modelName}"); Assert.NotNull(resultType); return(resultType); } }
public async Task EnsureClientNameEndsWithClient() { // simplified test pattern for unit testing aspects of code generation using (var fileSystem = GenerateCodeForTestFromSpec(codeGenerator: "Azure.CSharp")) { // Expected Files Assert.True(fileSystem.FileExists(@"GeneratedCode\SimpleAPIClient.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); // verify that class with the expected name is present var ops = asm.ExportedTypes.FirstOrDefault(each => each.FullName == "Test.SimpleAPIClient"); Assert.NotNull(ops); } }
public async Task CheckGeneratesValidCSharp() { using (var fileSystem = GenerateCodeForTestFromSpec(new AutoRest.CSharp.Azure.PluginCsa())) { Assert.True(fileSystem.FileExists("Models/RetryHeader.cs")); Assert.False(fileSystem.FileExists("Models/BatchAccountCreateHeaders.cs")); Assert.False(fileSystem.FileExists("Models/BatchAccountDeleteHeaders.cs")); // if newlines and stuff aren't excaped properly, compilation will fail var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); // try to load the assembly var asm = LoadAssembly(result.Output); Assert.NotNull(asm); } }
public async Task VerifySignature() { using (var fileSystem = $"{GetType().Name}".GenerateCodeInto(fileSystem: CreateMockFilesystem(), modeler: "Swagger")) { // Expected Files Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\ResultObject.cs")); Assert.True(fileSystem.FileExists(@"GeneratedCode\Models\TestAllOfObject.cs")); var result = await Compile(fileSystem); // filter the warnings var warnings = result.Messages.Where( each => each.Severity == DiagnosticSeverity.Warning && !SuppressWarnings.Contains(each.Id)).ToArray(); // use this to dump the files to disk for examination fileSystem.SaveFilesToTemp($"{GetType().Name}"); // filter the errors var errors = result.Messages.Where(each => each.Severity == DiagnosticSeverity.Error).ToArray(); Write(warnings, fileSystem); Write(errors, fileSystem); // use this to write out all the messages, even hidden ones. // Write(result.Messages, fileSystem); // Don't proceed unless we have zero Warnings. Assert.Empty(warnings); // Don't proceed unless we have zero Errors. Assert.Empty(errors); // Should also succeed. Assert.True(result.Succeeded); } }