public void CodeGen_CustomAttrGen_AttributeType_NotShared() { ConsoleLogger logger = new ConsoleLogger(); // Create a shared type service that says the entity's attribute is "unshared" when asked whether it is shared MockSharedCodeService mockSts = new MockSharedCodeService( new Type[] { typeof(Mock_CG_Attr_Gen_Type) }, new MethodBase[0], new string[0]); mockSts.AddUnsharedType(typeof(Mock_CG_Attr_Gen_TestAttribute)); string generatedCode = TestHelper.GenerateCode("C#", new Type[] { typeof(Mock_CG_Attr_Gen_Entity) }, logger, mockSts); string expectedWarning = string.Format( CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_RequiresDataAnnotations, typeof(Mock_CG_Attr_Gen_TestAttribute), "MockProject"); TestHelper.AssertContainsWarnings(logger, expectedWarning); string warningComment = string.Format( CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_RequiresShared, typeof(Mock_CG_Attr_Gen_TestAttribute), "MockProject"); TestHelper.AssertGeneratedCodeContains(generatedCode, warningComment); }
public void ProjectFileReader_Bad_Project_File_Warns() { ConsoleLogger logger = new ConsoleLogger(); using (ProjectFileReader projectFileReader = new ProjectFileReader(logger)) { string badProjectPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".csproj"); File.WriteAllText(badProjectPath, "neener neener"); try { projectFileReader.LoadProject(badProjectPath); // Simulate the exception so we get the exact text string warningMessage = null; try { Engine engine = new Engine(); Project project = new Project(engine); project.Load(badProjectPath); } catch (InvalidProjectFileException ipfe) { warningMessage = string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Open_Project, badProjectPath, ipfe.Message); } TestHelper.AssertContainsWarnings(logger, new string[] { warningMessage }); } finally { File.Delete(badProjectPath); } } }
public void CodeGen_Attribute_UIHint_ControlParameters_Fail_Odd_Count() { UnitTestHelper.EnsureEnglish(); var logger = new ConsoleLogger(); string generatedCode = TestHelper.GenerateCode("C#", typeof(Mock_CG_Attr_Entity_UIHint_ControlParameters_Odd), logger); TestHelper.AssertContainsWarnings(logger, string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeTypeMember, string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException, typeof(UIHintAttribute), "ControlParameters"), "StringProperty", typeof(Mock_CG_Attr_Entity_UIHint_ControlParameters_Odd).Name, "The number of control parameters must be even.")); TestHelper.AssertGeneratedCodeContains(generatedCode, "// - An exception occurred generating the 'ControlParameters' property on attribute of type 'System.ComponentModel.DataAnnotations.UIHintAttribute'."); }
public void ClientFilesTask_Safe_File_Move() { CleanClientFilesTask task = new CleanClientFilesTask(); MockBuildEngine mockBuildEngine = new MockBuildEngine(); task.BuildEngine = mockBuildEngine; string tempFolder = CodeGenHelper.GenerateTempFolder(); try { // Do a simple move string file1 = Path.Combine(tempFolder, "File1.txt"); string file2 = Path.Combine(tempFolder, "File2.txt"); File.AppendAllText(file1, "stuff"); bool success = task.SafeFileMove(file1, file2); Assert.IsTrue(success, "SafeFileMove reported failure"); Assert.IsTrue(File.Exists(file2), "File2 did not get created"); Assert.IsFalse(File.Exists(file1), "File1 still exists after move"); string content = File.ReadAllText(file2); Assert.AreEqual("stuff", content, "File2 did not get right content"); string errorMessage = String.Empty; // Finally, try a clearly illegal move and catch the error using (FileStream fs = new FileStream(file2, FileMode.Open, FileAccess.Read, FileShare.None)) { try { File.Move(file2, file1); } catch (IOException iox) { errorMessage = iox.Message; } success = task.SafeFileMove(file2, file1); } Assert.IsFalse(success, "Expected illegal move to report failure"); string expectedWarning = string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Rename_File, file2, file1, errorMessage); TestHelper.AssertContainsWarnings(mockBuildEngine.ConsoleLogger, expectedWarning); } finally { CodeGenHelper.DeleteTempFolder(tempFolder); } }
public void ProjectSourceFileCache_Failed_BreadCrumb_Save_Warns() { ConsoleLogger logger = new ConsoleLogger(); using (ProjectFileReader projectFileReader = new ProjectFileReader(logger)) { string projectPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".csproj"); string breadCrumbPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".txt"); string csFile = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".cs"); // Need file on disk only for timestamp File.WriteAllText(projectPath, "neener neener"); File.WriteAllText(breadCrumbPath, "bread crumbs"); File.WriteAllText(csFile, "//"); try { ProjectSourceFileCache cache = new ProjectSourceFileCache(projectPath, breadCrumbPath, logger, projectFileReader); cache.SourceFilesByProject[projectPath] = new string[] { csFile }; // Setup for failure File.SetAttributes(breadCrumbPath, FileAttributes.ReadOnly); // Ask to write to readonly file -- should fail cache.SaveCacheToFile(); // Simulate the exception so we get the exact text string warningMessage = null; try { // this should fail File.WriteAllText(breadCrumbPath, "stuff"); } catch (UnauthorizedAccessException uae) { warningMessage = string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Write_File, breadCrumbPath, uae.Message); } TestHelper.AssertContainsWarnings(logger, new string[] { warningMessage }); } finally { File.Delete(projectPath); File.SetAttributes(breadCrumbPath, File.GetAttributes(breadCrumbPath) & ~FileAttributes.ReadOnly); File.Delete(breadCrumbPath); File.Delete(csFile); } } }
public void Enum_Gen_Warn_Nested_Property() { foreach (bool isCSharp in new bool[] { true, false }) { using (AssemblyGenerator asmGen = new AssemblyGenerator( "CG_ENUM", isCSharp, new Type[] { typeof(Enum_Nested_Prop_Entity) })) { string generatedCode = asmGen.GeneratedCode; Assert.IsFalse(string.IsNullOrEmpty(generatedCode), "Failed to generate code:\r\n" + asmGen.ConsoleLogger.Errors); string message = String.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Property_Enum_Error, "EnumGen.Tests.Enum_Nested_Prop_Entity", "NestedEnumProp", "EnumGen.Tests.Enum_Nested_Prop_Entity+NestedEnum", Resource.Enum_Type_Must_Be_Public); TestHelper.AssertContainsWarnings(asmGen.ConsoleLogger, message); } } }
public void ClientCodeGenerationDispatcher_Error_TypeLoadException() { var logger = new ConsoleLogger(); var options = new ClientCodeGenerationOptions { Language = "C#" }; var host = TestHelper.CreateMockCodeGenerationHost(logger, /*sharedTypeService*/ null); // Create a new dispatcher and call an internal extensibility point to add ourselves // into the MEF composition container using (var dispatcher = new ClientCodeGenerationDispatcher()) { // We want to include into the MEF container an assembly that will throw TypeLoadException // when MEF tries to analyze it. This is to test our own recovery, which should consist // of logging an error making a default container containing only Tools. var unitTestAssemblyLocation = Assembly.GetExecutingAssembly().Location; var typeLoadExceptionProjectLocation = Path.Combine(Path.GetDirectoryName(unitTestAssemblyLocation), "TypeLoadExceptionProject.dll"); Assert.IsTrue(File.Exists(typeLoadExceptionProjectLocation), "Expected TypeLoadExceptionProject.dll to coreside with this assembly in test folder"); // Do what MEF does to load the types so we can capture the exception Exception expectedException = null; try { Assembly assembly = Assembly.LoadFrom(typeLoadExceptionProjectLocation); assembly.GetTypes(); } catch (Exception ex) { expectedException = ex; } Assert.IsNotNull(expectedException, "We did not generate the type load exception we expected"); var compositionAssemblies = new[] { unitTestAssemblyLocation, typeLoadExceptionProjectLocation }; IClientCodeGenerator generator = dispatcher.FindCodeGenerator(host, options, compositionAssemblies, /*generatorName*/ null); Assert.IsNotNull(generator, "the dispatcher did not pick default generator"); Assert.IsTrue(generator is CodeDomClientCodeGenerator, "the dispatcher did not pick the default code generator"); string error = (string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Create_Composition_Container, expectedException.Message)); TestHelper.AssertContainsWarnings(logger, error); } }
public void Enum_Gen_Warn_System_Property() { foreach (bool isCSharp in new bool[] { true, false }) { using (AssemblyGenerator asmGen = new AssemblyGenerator( "CG_ENUM", isCSharp, new Type[] { typeof(Enum_System_Prop_Entity) })) { // Force this type to be unshared to force failure asmGen.MockSharedCodeService.AddUnsharedType(typeof(System.IO.FileAttributes)); string generatedCode = asmGen.GeneratedCode; Assert.IsFalse(string.IsNullOrEmpty(generatedCode), "Failed to generate code:\r\n" + asmGen.ConsoleLogger.Errors); string message = String.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Property_Enum_Error, "EnumGen.Tests.Enum_System_Prop_Entity", "FileAttrProp", "System.IO.FileAttributes", Resource.Enum_Type_Cannot_Gen_System); TestHelper.AssertContainsWarnings(asmGen.ConsoleLogger, message); } } }
public void ProjectFileReader_Nonexistent_Project_File_Warns() { ConsoleLogger logger = new ConsoleLogger(); string badProjectPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".csproj"); using (ProjectFileReader projectFileReader = new ProjectFileReader(logger)) { try { projectFileReader.LoadProject(badProjectPath); string warningMessage = string.Format(CultureInfo.CurrentCulture, Resource.Project_Does_Not_Exist, badProjectPath); TestHelper.AssertContainsWarnings(logger, new string[] { warningMessage }); } finally { File.Delete(badProjectPath); } } }
public void CodeGen_CustomAttrGen_EntityAttributeThrows() { ConsoleLogger logger = new ConsoleLogger(); string generatedCode = TestHelper.GenerateCode("C#", typeof(AttributeThrowingEntity), logger); Assert.IsFalse(string.IsNullOrEmpty(generatedCode), "Code should have been generated"); AttributeBuilderException expectedException = new AttributeBuilderException( new ThrowingEntityAttributeException(ThrowingEntityAttribute.ExceptionMessage), typeof(ThrowingEntityAttribute), ThrowingEntityAttribute.ThrowingPropertyName); string expectedBuildWarning = string.Format( CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeType, expectedException.Message, typeof(AttributeThrowingEntity).Name, expectedException.InnerException.Message); TestHelper.AssertGeneratedCodeContains(generatedCode, expectedException.Message); TestHelper.AssertContainsWarnings(logger, expectedBuildWarning); }
public void ProjectSourceFileCache_Nonexistent_Project_File_Warns() { ConsoleLogger logger = new ConsoleLogger(); string badProjectPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".csproj"); using (ProjectFileReader projectFileReader = new ProjectFileReader(logger)) { try { ProjectSourceFileCache cache = new ProjectSourceFileCache(badProjectPath, "breadCrumb", logger, projectFileReader); IEnumerable <string> projects = cache.GetAllKnownProjects(); string warningMessage = string.Format(CultureInfo.CurrentCulture, Resource.Project_Does_Not_Exist, badProjectPath); TestHelper.AssertContainsWarnings(logger, new string[] { warningMessage }); } finally { File.Delete(badProjectPath); } } }
public void CodeGen_Attribute_DisplayAttribute_Fail_Private_ResourceType() { UnitTestHelper.EnsureEnglish(); var logger = new ConsoleLogger(); var generatedCode = TestHelper.GenerateCode("C#", typeof(Mock_CG_DisplayAttr_Entity_Private_ResourceType), logger); var expectedExceptionMessage = "Cannot retrieve property 'Name' because localization failed. Type 'Luma.SimpleEntity.Tests.Mock_CG_DisplayAttr_Private_ResourceType' is not public or does not contain a public static string property with the name 'Resource2'."; var expectedException = new AttributeBuilderException( new InvalidOperationException(expectedExceptionMessage), typeof(DisplayAttribute), "Name"); string expectedBuildWarning = string.Format( CultureInfo.CurrentCulture, Resource.ClientCodeGen_Attribute_ThrewException_CodeTypeMember, expectedException.Message, "TheResourcedProperty", typeof(Mock_CG_DisplayAttr_Entity_Private_ResourceType).Name, expectedException.InnerException.Message); TestHelper.AssertGeneratedCodeContains(generatedCode, expectedException.Message); TestHelper.AssertContainsWarnings(logger, expectedBuildWarning); }
public void ClientCodeGenerationDispatcher_Custom_By_AssemblyQualifiedName_Wrong_Type() { ConsoleLogger logger = new ConsoleLogger(); ClientCodeGenerationOptions options = new ClientCodeGenerationOptions() { Language = "C#" }; ICodeGenerationHost host = TestHelper.CreateMockCodeGenerationHost(logger, /*sharedTypeService*/ null); string codeGeneratorName = typeof(string).AssemblyQualifiedName; // Create a new dispatcher and call an internal extensibility point to add ourselves // into the MEF composition container using (ClientCodeGenerationDispatcher dispatcher = new ClientCodeGenerationDispatcher()) { string[] compositionAssemblies = new string[0]; IClientCodeGenerator generator = dispatcher.FindCodeGenerator(host, options, compositionAssemblies, codeGeneratorName); Assert.IsNull(generator, "the dispatcher should not find the code generator"); string error = string.Format(CultureInfo.CurrentCulture, Resource.Code_Generator_Incorrect_Type, codeGeneratorName); TestHelper.AssertContainsWarnings(logger, error); } }
public void ClientFilesTask_Safe_File_Copy() { CleanClientFilesTask task = new CleanClientFilesTask(); MockBuildEngine mockBuildEngine = new MockBuildEngine(); task.BuildEngine = mockBuildEngine; string tempFolder = CodeGenHelper.GenerateTempFolder(); try { // Do a simple copy with no special handling for attributes string file1 = Path.Combine(tempFolder, "File1.txt"); string file2 = Path.Combine(tempFolder, "File2.txt"); File.AppendAllText(file1, "stuff"); bool success = task.SafeFileCopy(file1, file2, /*isProjectFile*/ false); Assert.IsTrue(success, "SafeFileCopy reported failure"); Assert.IsTrue(File.Exists(file2), "File2 did not get created"); string content = File.ReadAllText(file2); Assert.AreEqual("stuff", content, "File2 did not get right content"); FileAttributes fa = File.GetAttributes(file2); Assert.AreEqual(0, (int)(fa & FileAttributes.ReadOnly), "Expected RO bit not to be set"); Assert.IsFalse(task.FilesWereWritten, "Should not have marked files as written"); File.Delete(file2); // Repeat, but ask for it to be treated as a project file success = task.SafeFileCopy(file1, file2, /*isProjectFile*/ true); Assert.IsTrue(success, "SafeFileCopy reported failure"); Assert.IsTrue(File.Exists(file2), "File2 did not get created"); content = File.ReadAllText(file2); Assert.AreEqual("stuff", content, "File2 did not get right content"); fa = File.GetAttributes(file2); Assert.AreEqual((int)FileAttributes.ReadOnly, (int)(fa & FileAttributes.ReadOnly), "Expected RO bit to be set"); Assert.IsTrue(task.FilesWereWritten, "Should have marked files as written"); task.SafeFileDelete(file2); string errorMessage = String.Empty; // Finally, try a clearly illegal copy and catch the error using (FileStream fs = new FileStream(file1, FileMode.Open, FileAccess.Read, FileShare.None)) { try { File.Copy(file1, file2, true); } catch (IOException iox) { errorMessage = iox.Message; } success = task.SafeFileCopy(file1, file2, /*isProjectFile*/ false); } Assert.IsFalse(success, "Expected illegal copy to report failure"); string expectedWarning = string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Copy_File, file1, file2, errorMessage); TestHelper.AssertContainsWarnings(mockBuildEngine.ConsoleLogger, expectedWarning); } finally { CodeGenHelper.DeleteTempFolder(tempFolder); } }
public void CleanClientFiles_Safe_File_Delete() { CleanClientFilesTask task = new CleanClientFilesTask(); MockBuildEngine mockBuildEngine = new MockBuildEngine(); task.BuildEngine = mockBuildEngine; // Test 1 -- null and empty deletes do nothing task.SafeFileDelete(null); TestHelper.AssertNoErrorsOrWarnings(mockBuildEngine.ConsoleLogger); task.SafeFileDelete(string.Empty); TestHelper.AssertNoErrorsOrWarnings(mockBuildEngine.ConsoleLogger); // Test 2 -- nonexistant file does nothing string fileName = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); Assert.IsFalse(File.Exists(fileName)); task.SafeFileDelete(fileName); TestHelper.AssertNoErrorsOrWarnings(mockBuildEngine.ConsoleLogger); // Test 3 -- verify delete on actual file succeeds without error File.WriteAllText(fileName, "stuff"); Assert.IsTrue(File.Exists(fileName)); task.SafeFileDelete(fileName); Assert.IsFalse(File.Exists(fileName)); TestHelper.AssertNoErrorsOrWarnings(mockBuildEngine.ConsoleLogger); // Test 4 -- verify delete on actual file with READONLY attribute set succeeds without error File.WriteAllText(fileName, "stuff"); File.SetAttributes(fileName, FileAttributes.ReadOnly); Assert.IsTrue(File.Exists(fileName)); task.SafeFileDelete(fileName); Assert.IsFalse(File.Exists(fileName)); TestHelper.AssertNoErrorsOrWarnings(mockBuildEngine.ConsoleLogger); // Test 5 -- attempt to delete while file is open. // Verify we log a warning containing the exception's message File.WriteAllText(fileName, "stuff"); Assert.IsTrue(File.Exists(fileName)); string errorMessage = null; using (StreamReader t1 = new StreamReader(fileName)) { // We do a delete here to capture the exception we expect the SafeFileDelete to encounter try { File.Delete(fileName); } catch (IOException ioe) { errorMessage = ioe.Message; } Assert.IsNotNull(errorMessage, "Expected File.Delete to throw IOException"); task.SafeFileDelete(fileName); } Assert.IsTrue(File.Exists(fileName)); File.Delete(fileName); string expectedWarning = string.Format(CultureInfo.CurrentCulture, Resource.Failed_To_Delete_File_Error, fileName, errorMessage); TestHelper.AssertContainsWarnings(mockBuildEngine.ConsoleLogger, expectedWarning); }