public void NoLanguage() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.OutputFile = new TaskItem("foo"); bool result = task.Execute(); Assert.AreEqual(false, result); engine.AssertLogContains("MSB3098"); }
public void NoFileOrDirectory() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; bool result = task.Execute(); Assert.AreEqual(false, result); engine.AssertLogContains("MSB3711"); }
public void VerifyFindInvalidProjectReferences() { // Create the engine. MockEngine engine = new MockEngine(); FindInvalidProjectReferences t = new FindInvalidProjectReferences(); t.TargetPlatformVersion = "8.0"; t.TargetPlatformIdentifier = "Windows"; Dictionary<string, string> proj1 = new Dictionary<string, string>(); proj1["TargetPlatformMoniker"] = "Windows, Version=7.0"; Dictionary<string, string> proj2 = new Dictionary<string, string>(); proj2["TargetPlatformMoniker"] = "Windows, Version=8.0"; Dictionary<string, string> proj3 = new Dictionary<string, string>(); proj3["TargetPlatformMoniker"] = "Windows, Version=8.1"; Dictionary<string, string> proj4 = new Dictionary<string, string>(); proj4["TargetPlatformMoniker"] = "Windows, Version=8.2"; t.ProjectReferences = new TaskItem[] { new TaskItem("proj1.proj", proj1), new TaskItem("proj2.proj", proj2), new TaskItem("proj3.proj", proj3), new TaskItem("proj4.proj", proj4) }; t.BuildEngine = engine; bool succeeded = t.Execute(); Assert.True(succeeded); string warning1 = ResourceUtilities.FormatResourceString("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj1.proj", "Windows, Version=7.0"); engine.AssertLogDoesntContain(warning1); string warning2 = ResourceUtilities.FormatResourceString("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj2.proj", "Windows, Version=8.0"); engine.AssertLogDoesntContain(warning2); string warning3 = ResourceUtilities.FormatResourceString("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj3.proj", "Windows, Version=8.1"); engine.AssertLogContains(warning3); string warning4 = ResourceUtilities.FormatResourceString("FindInvalidProjectReferences.WarnWhenVersionIsIncompatible", "Windows", "8.0", "proj4.proj", "Windows, Version=8.2"); engine.AssertLogContains(warning4); Assert.Equal(t.InvalidReferences.Length, 2); Assert.Equal(t.InvalidReferences[0].ItemSpec, "proj3.proj"); Assert.Equal(t.InvalidReferences[1].ItemSpec, "proj4.proj"); }
public void HandleExecutionErrorsWhenToolDoesntLogError() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.MockCommandLineCommands = NativeMethodsShared.IsWindows ? "/C garbagegarbagegarbagegarbage.exe" : "-c garbagegarbagegarbagegarbage.exe"; Assert.False(t.Execute()); Assert.Equal(NativeMethodsShared.IsWindows ? 1 : 127, t.ExitCode); // cmd.exe error code is 1, sh error code is 127 // We just tried to run "cmd.exe /C garbagegarbagegarbagegarbage.exe". This should fail, // but since "cmd.exe" doesn't log its errors in canonical format, no errors got // logged by the tool itself. Therefore, ToolTask's default implementation of // HandleTaskExecutionErrors should have logged error MSB6006. engine.AssertLogContains("MSB6006"); } }
public void DoNotErrorWhenTextSentToStandardError() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.MockCommandLineCommands = NativeMethodsShared.IsWindows ? "/C Echo 'Who made you king anyways' 1>&2" : @"-c """"""echo Who made you king anyways 1>&2"""""""; Assert.True(t.Execute()); engine.AssertLogDoesntContain("MSB"); engine.AssertLogContains("Who made you king anyways"); Assert.Equal(0, t.ExitCode); Assert.Equal(0, engine.Errors); } }
public void NoNumber() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_Parameter", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.False(result); engine.AssertLogContains("MSB3098"); }
public void TestGeneralFrameworkMonikerNonExistent() { MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; // Make a framework which does not exist, intentional mispelling of framework getReferencePaths.TargetFrameworkMoniker = ".NetFramewok, Version=v99.0"; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Equal(0, returnedPaths.Length); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); FrameworkNameVersioning frameworkMoniker = new FrameworkNameVersioning(getReferencePaths.TargetFrameworkMoniker); string message = ResourceUtilities.FormatResourceString("GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", frameworkMoniker.ToString()); engine.AssertLogContains(message); }
public void GetResolvedRuleSetPath_FullPath_NonExistent() { MockEngine mockEngine = new MockEngine(); ResolveCodeAnalysisRuleSet task = new ResolveCodeAnalysisRuleSet(); task.BuildEngine = mockEngine; string codeAnalysisRuleSet = @"C:\foo\bar\CodeAnalysis.ruleset"; task.CodeAnalysisRuleSet = codeAnalysisRuleSet; task.MSBuildProjectDirectory = null; task.CodeAnalysisRuleSetDirectories = null; bool result = task.Execute(); string resolvedRuleSet = task.ResolvedCodeAnalysisRuleSet; Assert.AreEqual(expected: true, actual: result); Assert.AreEqual(expected: null, actual: resolvedRuleSet); mockEngine.AssertLogContains("MSB3884"); }
public void TestGeneralFrameworkMonikerGoodWithInvalidIncludePath() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithInvalidIncludePath"); string framework41Directory = Path.Combine(tempDirectory, "MyFramework\\v4.1\\"); string redistListDirectory = Path.Combine(framework41Directory, "RedistList"); string redistListFile = Path.Combine(redistListDirectory, "FrameworkList.xml"); try { Directory.CreateDirectory(framework41Directory); Directory.CreateDirectory(redistListDirectory); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' IncludeFramework='..\\Mooses' Name='Chained oh noes'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; File.WriteAllText(redistListFile, redistListContents); string targetFrameworkMoniker = "MyFramework, Version=v4.1"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = tempDirectory; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Equal(0, returnedPaths.Length); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); FrameworkNameVersioning frameworkMoniker = new FrameworkNameVersioning(getReferencePaths.TargetFrameworkMoniker); string message = ResourceUtilities.FormatResourceString("GetReferenceAssemblyPaths.NoReferenceAssemblyDirectoryFound", frameworkMoniker.ToString()); engine.AssertLogContains(message); } finally { if (Directory.Exists(framework41Directory)) { Directory.Delete(framework41Directory, true); } } }
public void ErrorInNamespaceDecl() { MockEngine engine = new MockEngine(true); string xmlInputPath; Prepare(_xmlFileWithNs, out xmlInputPath); XmlPoke p = new XmlPoke(); p.BuildEngine = engine; p.XmlInputPath = new TaskItem(xmlInputPath); p.Query = "//s:variable/@Name"; p.Namespaces = "<!THIS IS ERROR Namespace Prefix=\"s\" Uri=\"http://nsurl\" />"; p.Namespaces.ShouldBe("<!THIS IS ERROR Namespace Prefix=\"s\" Uri=\"http://nsurl\" />"); p.Value = new TaskItem("Nur"); p.Execute().ShouldBeFalse(); // "Execution should've failed" engine.AssertLogContains("MSB3731"); }
public void ErrorWhenTextSentToStandardError() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.LogStandardErrorAsError = true; t.MockCommandLineCommands = NativeMethodsShared.IsWindows ? "/C Echo 'Who made you king anyways' 1>&2" : @"-c """"""echo 'Who made you king anyways' 1>&2"""""""; t.Execute().ShouldBeFalse(); engine.AssertLogDoesntContain("MSB3073"); engine.AssertLogContains("Who made you king anyways"); t.ExitCode.ShouldBe(-1); engine.Errors.ShouldBe(1); } }
public void GetResolvedRuleSetPath_SimpleNameAndDirectories_NonExistent() { MockEngine mockEngine = new MockEngine(); ResolveCodeAnalysisRuleSet task = new ResolveCodeAnalysisRuleSet(); task.BuildEngine = mockEngine; string directory = Path.GetTempPath(); task.CodeAnalysisRuleSet = Path.GetRandomFileName() + ".ruleset"; task.MSBuildProjectDirectory = null; task.CodeAnalysisRuleSetDirectories = new[] { directory }; bool result = task.Execute(); string resolvedRuleSet = task.ResolvedCodeAnalysisRuleSet; Assert.True(result); Assert.Null(resolvedRuleSet); mockEngine.AssertLogContains("MSB3884"); }
public void Error() { MockEngine e = new MockEngine(true); Error err = new Error(); err.BuildEngine = e; err.Text = "errortext"; err.File = "c:\\file"; bool retval = err.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.False(retval); e.AssertLogContains("c:\\file(0,0): ERROR : errortext"); Assert.Equal(1, e.Errors); }
public void Regress_Mutation_WarnIfCommandLineTooLong() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; // "cmd.exe" croaks big-time when given a very long command-line. It pops up a message box on // Windows XP. We can't have that! So use "attrib.exe" for this exercise instead. t.FullToolName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "attrib.exe"); t.MockCommandLineCommands = new String('x', 32001); // It's only a warning, we still succeed Assert.True(t.Execute()); Assert.Equal(0, t.ExitCode); // There should be a warning about the command-line being too long. engine.AssertLogContains("MSB6002"); } }
public void Warning() { MockEngine e = new MockEngine(true); Warning w = new Warning(); w.BuildEngine = e; w.Text = "warningtext"; w.File = "c:\\file"; bool retval = w.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.True(retval); e.AssertLogContains("c:\\file(0,0): WARNING : warningtext"); Assert.Equal(1, e.Warnings); }
public void GetResolvedRuleSetPath_FullPath_NonExistent() { MockEngine mockEngine = new MockEngine(); ResolveCodeAnalysisRuleSet task = new ResolveCodeAnalysisRuleSet(); task.BuildEngine = mockEngine; string codeAnalysisRuleSet = @"C:\foo\bar\CodeAnalysis.ruleset"; task.CodeAnalysisRuleSet = codeAnalysisRuleSet; task.MSBuildProjectDirectory = null; task.CodeAnalysisRuleSetDirectories = null; bool result = task.Execute(); string resolvedRuleSet = task.ResolvedCodeAnalysisRuleSet; Assert.True(result); Assert.Null(resolvedRuleSet); mockEngine.AssertLogContains("MSB3884"); }
public void GetResolvedRuleSetPath_RelativePath_NoProject() { MockEngine mockEngine = new MockEngine(); ResolveCodeAnalysisRuleSet task = new ResolveCodeAnalysisRuleSet(); task.BuildEngine = mockEngine; string subdirectoryName = Path.GetRandomFileName(); task.CodeAnalysisRuleSet = Path.Combine(subdirectoryName, "CodeAnalysis.ruleset"); task.MSBuildProjectDirectory = null; task.CodeAnalysisRuleSetDirectories = null; bool result = task.Execute(); string resolvedRuleSet = task.ResolvedCodeAnalysisRuleSet; Assert.True(result); Assert.Null(resolvedRuleSet); mockEngine.AssertLogContains("MSB3884"); }
public void TaskFoundOnPath() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; string toolName = NativeMethodsShared.IsWindows ? "cmd.exe" : "sh"; t.FullToolName = toolName; Assert.True(t.Execute()); Assert.Equal(0, t.ExitCode); Assert.Equal(0, engine.Errors); engine.AssertLogContains( #if FEATURE_SPECIAL_FOLDERS Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), toolName)); #else Path.Combine(FileUtilities.GetFolderPath(FileUtilities.SpecialFolder.System), toolName)); #endif } }
public void GetResolvedRuleSetPath_RelativePath_WithProject_NonExistent() { MockEngine mockEngine = new MockEngine(); ResolveCodeAnalysisRuleSet task = new ResolveCodeAnalysisRuleSet(); task.BuildEngine = mockEngine; string subdirectoryName = Path.GetRandomFileName(); string projectDirectory = Path.GetTempPath(); task.CodeAnalysisRuleSet = Path.Combine(subdirectoryName, "CodeAnalysis.ruleset"); task.MSBuildProjectDirectory = projectDirectory; task.CodeAnalysisRuleSetDirectories = null; bool result = task.Execute(); string resolvedRuleSet = task.ResolvedCodeAnalysisRuleSet; Assert.AreEqual(expected: true, actual: result); Assert.AreEqual(expected: null, actual: resolvedRuleSet); mockEngine.AssertLogContains("MSB3884"); }
public void GetResolvedRuleSetPath_SimpleNameAndProjectDirectory_NonExistent() { MockEngine mockEngine = new MockEngine(); ResolveCodeAnalysisRuleSet task = new ResolveCodeAnalysisRuleSet(); task.BuildEngine = mockEngine; string projectDirectory = Path.GetTempPath(); string codeAnalysisRuleSet = Path.GetRandomFileName() + ".ruleset"; task.CodeAnalysisRuleSet = codeAnalysisRuleSet; task.MSBuildProjectDirectory = projectDirectory; task.CodeAnalysisRuleSetDirectories = null; bool result = task.Execute(); string resolvedRuleSet = task.ResolvedCodeAnalysisRuleSet; Assert.Equal(expected: true, actual: result); Assert.Equal(expected: null, actual: resolvedRuleSet); mockEngine.AssertLogContains("MSB3884"); }
public void ErrorFromResources() { MockEngine e = new MockEngine(true); ErrorFromResources err = new ErrorFromResources(); err.BuildEngine = e; err.Resource = "Exec.MissingCommandError"; bool retval = err.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.False(retval); string message = AssemblyResources.GetString(err.Resource); e.AssertLogContains(message); Assert.Equal(1, e.Errors); }
public void ErrorFromResourcesWithInvalidArguments() { MockEngine e = new MockEngine(true); ErrorFromResources err = new ErrorFromResources(); err.BuildEngine = e; err.Resource = "Copy.Error"; err.Arguments = new string[] { "a.txt", "b.txt" }; bool retval = err.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.False(retval); e.AssertLogDoesntContain("a.txt"); e.AssertLogContains("MSB3861"); Assert.Equal(1, e.Errors); }
public void ErrorFromResourcesWithArguments() { MockEngine e = new MockEngine(true); ErrorFromResources err = new ErrorFromResources(); err.BuildEngine = e; err.Resource = "Copy.Error"; err.Arguments = new string[] { "a.txt", "b.txt", "xyz" }; bool retval = err.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.False(retval); string message = String.Format(AssemblyResources.GetString(err.Resource), err.Arguments); e.AssertLogContains(message); Assert.Equal(1, e.Errors); }
public void BogusCustomRegexesCauseOneErrorEach() { Exec exec; if (NativeMethodsShared.IsWindows) { exec = PrepareExec("echo Some output & echo Some output & echo Some output & echo Some output "); } else { exec = PrepareExec("echo Some output ; echo Some output ; echo Some output ; echo Some output "); } exec.CustomErrorRegularExpression = "~!@#$%^_)(*&^%$#@@#XF &%^%T$REd((((([[[["; exec.CustomWarningRegularExpression = "*"; exec.Execute(); MockEngine e = (MockEngine)exec.BuildEngine; Console.WriteLine(e.Log); Assert.Equal(3, e.Errors); e.AssertLogContains("MSB3076"); }
public void OverrideStdOutImportanceToHigh() { string tempFile = FileUtilities.GetTemporaryFile(); File.WriteAllText(tempFile, @"hello world"); using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); engine.MinimumMessageImportance = MessageImportance.High; t.BuildEngine = engine; t.FullToolName = "find.exe"; t.MockCommandLineCommands = "\"hello\" \"" + tempFile + "\""; t.StandardOutputImportance = "High"; Assert.True(t.Execute()); Assert.Equal(0, t.ExitCode); Assert.Equal(0, engine.Errors); engine.AssertLogContains("hello world"); } File.Delete(tempFile); }
public void OverrideStdOutImportanceToHigh() { string tempFile = FileUtilities.GetTemporaryFile(); File.WriteAllText(tempFile, @"hello world"); using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); engine.MinimumMessageImportance = MessageImportance.High; t.BuildEngine = engine; t.FullToolName = NativeMethodsShared.IsWindows ? "findstr.exe" : "grep"; t.MockCommandLineCommands = "\"hello\" \"" + tempFile + "\""; t.StandardOutputImportance = "High"; t.Execute().ShouldBeTrue(); t.ExitCode.ShouldBe(0); engine.Errors.ShouldBe(0); engine.AssertLogContains("hello world"); } File.Delete(tempFile); }
public void Regress_Mutation_WarnIfCommandLineTooLong() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; // "cmd.exe" croaks big-time when given a very long command-line. It pops up a message box on // Windows XP. We can't have that! So use "attrib.exe" for this exercise instead. #if FEATURE_SPECIAL_FOLDERS t.FullToolName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), NativeMethodsShared.IsWindows ? "attrib.exe" : "ps"); #else t.FullToolName = Path.Combine(FileUtilities.GetFolderPath(FileUtilities.SpecialFolder.System), NativeMethodsShared.IsWindows ? "attrib.exe" : "ps"); #endif t.MockCommandLineCommands = new String('x', 32001); // It's only a warning, we still succeed t.Execute().ShouldBeTrue(); t.ExitCode.ShouldBe(0); // There should be a warning about the command-line being too long. engine.AssertLogContains("MSB6002"); } }
public void TestVerifyProjectReferenceItem() { ResolveNonMSBuildProjectOutput rvpo = new ResolveNonMSBuildProjectOutput(); ITaskItem[] taskItems = new ITaskItem[1]; // bad GUID - this reference is invalid taskItems[0] = new TaskItem("projectReference"); taskItems[0].SetMetadata(attributeProject, "{invalid guid}"); MockEngine engine = new MockEngine(); rvpo.BuildEngine = engine; Assert.AreEqual(true, rvpo.VerifyProjectReferenceItems(taskItems, false /* treat problems as warnings */)); Assert.AreEqual(1, engine.Warnings); Assert.AreEqual(0, engine.Errors); engine.AssertLogContains("MSB3107"); engine = new MockEngine(); rvpo.BuildEngine = engine; Assert.AreEqual(false, rvpo.VerifyProjectReferenceItems(taskItems, true /* treat problems as errors */)); Assert.AreEqual(0, engine.Warnings); Assert.AreEqual(1, engine.Errors); engine.AssertLogContains("MSB3107"); }
public void ErrorFromResourcesWithOverriddenCode() { MockEngine e = new MockEngine(true); ErrorFromResources err = new ErrorFromResources(); err.BuildEngine = e; err.Resource = "Exec.MissingCommandError"; err.Code = "ABC1234"; bool retval = err.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.False(retval); string message = AssemblyResources.GetString(err.Resource); string updatedMessage = message.Replace("MSB3072", "ABC1234"); e.AssertLogContains(updatedMessage); Assert.Equal(1, e.Errors); }
// Ignore: Flaky test public void CopyToDestinationFolderWithHardLinkFallbackNetwork() { string sourceFile = FileUtilities.GetTemporaryFile(); string temp = @"\\localhost\c$\temp"; string destFolder = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A398"); string destFile = Path.Combine(destFolder, Path.GetFileName(sourceFile)); try { if (!Directory.Exists(destFolder)) { Directory.CreateDirectory(destFolder); } string nothingFile = Path.Combine(destFolder, "nothing.txt"); File.WriteAllText(nothingFile, "nothing"); File.Delete(nothingFile); } catch (Exception) { Console.WriteLine("CopyToDestinationFolderWithHardLinkFallbackNetwork test could not access the network."); // Something caused us to not be able to access our "network" share, don't fail. return; } try { using (StreamWriter sw = new StreamWriter(sourceFile, true)) // HIGHCHAR: Test writes in UTF8 without preamble. sw.Write("This is a source temp file."); ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! t.UseHardlinksIfPossible = true; MockEngine me = new MockEngine(true); t.BuildEngine = me; t.SourceFiles = sourceFiles; t.DestinationFolder = new TaskItem(destFolder); t.SkipUnchangedFiles = true; bool success = t.Execute(); Assert.IsTrue(success, "success"); Assert.IsTrue(File.Exists(destFile), "destination exists"); Microsoft.Build.UnitTests.MockEngine.GetStringDelegate resourceDelegate = new Microsoft.Build.UnitTests.MockEngine.GetStringDelegate(AssemblyResources.GetString); me.AssertLogContainsMessageFromResource(resourceDelegate, "Copy.HardLinkComment", sourceFile, destFile); // Can't do this below, because the real message doesn't end with String.Empty, it ends with a CLR exception string, and so matching breaks in PLOC. // Instead look for the HRESULT that CLR unfortunately puts inside its exception string. Something like this // The system cannot move the file to a different disk drive. (Exception from HRESULT: 0x80070011) // me.AssertLogContainsMessageFromResource(resourceDelegate, "Copy.RetryingAsFileCopy", sourceFile, destFile, String.Empty); me.AssertLogContains("0x80070011"); string destinationFileContents; using (StreamReader sr = new StreamReader(destFile)) destinationFileContents = sr.ReadToEnd(); Assert.IsTrue ( destinationFileContents == "This is a source temp file.", "Expected the destination file to contain the contents of source file." ); Assert.AreEqual(1, t.DestinationFiles.Length); Assert.AreEqual(1, t.CopiedFiles.Length); Assert.AreEqual(destFile, t.DestinationFiles[0].ItemSpec); Assert.AreEqual(destFile, t.CopiedFiles[0].ItemSpec); // Now we will write new content to the source file // we'll then check that the destination file automatically // has the same content (i.e. it's been hard linked) using (StreamWriter sw = new StreamWriter(sourceFile, false)) // HIGHCHAR: Test writes in UTF8 without preamble. sw.Write("This is another source temp file."); // Read the destination file (it should have the same modified content as the source) using (StreamReader sr = new StreamReader(destFile)) destinationFileContents = sr.ReadToEnd(); Assert.IsTrue ( destinationFileContents == "This is a source temp file.", "Expected the destination copied file to contain the contents of original source file only." ); ((MockEngine)t.BuildEngine).AssertLogDoesntContain("MSB3026"); // Didn't do retries } finally { File.Delete(sourceFile); File.Delete(destFile); Directory.Delete(destFolder, true); } }
public void TooFewRetriesThrows() { Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! // Allow the task's default (false) to have a chance if (useHardLinks) { t.UseHardlinksIfPossible = useHardLinks; } MockEngine engine = new MockEngine(true /* log to console */); t.BuildEngine = engine; t.SourceFiles = new ITaskItem[] { new TaskItem("c:\\source") }; t.DestinationFiles = new ITaskItem[] { new TaskItem("c:\\destination") }; t.Retries = 1; CopyFunctor copyFunctor = new CopyFunctor(3, true /* throw */); bool result = t.Execute(copyFunctor.Copy); Assert.AreEqual(false, result); engine.AssertLogContains("MSB3026"); engine.AssertLogContains("MSB3027"); }
public void TestLogFromException() { string message = "exception message"; string stackTrace = "TaskLoggingHelperTests.TestLogFromException"; MockEngine engine = new MockEngine(); MockTask task = new MockTask(); task.BuildEngine = engine; // need to throw and catch an exception so that its stack trace is initialized to something try { Exception inner = new InvalidOperationException(); throw new Exception(message, inner); } catch (Exception e) { // log error without stack trace task.Log.LogErrorFromException(e); engine.AssertLogContains(message); engine.AssertLogDoesntContain(stackTrace); engine.AssertLogDoesntContain("InvalidOperationException"); engine.Log = string.Empty; // log warning with stack trace task.Log.LogWarningFromException(e); engine.AssertLogContains(message); engine.AssertLogDoesntContain(stackTrace); engine.Log = string.Empty; // log error with stack trace task.Log.LogErrorFromException(e, true); engine.AssertLogContains(message); engine.AssertLogContains(stackTrace); engine.AssertLogDoesntContain("InvalidOperationException"); engine.Log = string.Empty; // log warning with stack trace task.Log.LogWarningFromException(e, true); engine.AssertLogContains(message); engine.AssertLogContains(stackTrace); engine.Log = string.Empty; // log error with stack trace and inner exceptions task.Log.LogErrorFromException(e, true, true, "foo.cs"); engine.AssertLogContains(message); engine.AssertLogContains(stackTrace); engine.AssertLogContains("InvalidOperationException"); } }
/// <summary> /// Given a log and a resource string, acquires the text of that resource string and /// compares it to the log. Asserts if the log does not contain the desired string. /// </summary> /// <param name="e">The MockEngine that contains the log we're checking</param> /// <param name="log">The TaskLoggingHelper that we use to load the string resource</param> /// <param name="errorResource">The name of the resource string to check the log for</param> /// <param name="args">Arguments needed to format the resource string properly</param> private void VerifyLogContainsResource(MockEngine e, TaskLoggingHelper log, string messageResource, params object[] args) { string message = log.FormatResourceString(messageResource, args); e.AssertLogContains(message); }
public void DoRetryWhenDestinationLocked() { string destinationFile = Path.GetTempFileName(); string sourceFile = Path.GetTempFileName(); try { using (StreamWriter sw = new StreamWriter(destinationFile, true)) // Keep it locked { ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! // Allow the task's default (false) to have a chance if (useHardLinks) { t.UseHardlinksIfPossible = useHardLinks; } MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.SourceFiles = sourceFiles; t.DestinationFiles = new TaskItem[] { new TaskItem(destinationFile) }; bool result = t.Execute(); Assert.IsFalse(result); engine.AssertLogContains("MSB3021"); // copy failed engine.AssertLogContains("MSB3026"); // DID retry Assert.IsTrue(engine.Errors == 2); // retries failed, and actual failure Assert.IsTrue(engine.Warnings == 10); } } finally { File.Delete(sourceFile); File.Delete(destinationFile); } }
public void DoNotRetryCopyWhenDestinationFileIsFolder() { string destinationFile = Path.GetTempPath(); string sourceFile = FileUtilities.GetTemporaryFile(); try { using (StreamWriter sw = new StreamWriter(sourceFile, true)) // HIGHCHAR: Test writes in UTF8 without preamble. sw.Write("This is a destination temp file."); ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! // Allow the task's default (false) to have a chance if (useHardLinks) { t.UseHardlinksIfPossible = useHardLinks; } MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.SourceFiles = sourceFiles; t.DestinationFiles = destinationFiles; t.SkipUnchangedFiles = true; bool result = t.Execute(); Assert.IsFalse(result); Assert.IsTrue(engine.Errors == 1); Assert.IsTrue(engine.Warnings == 0); engine.AssertLogContains("MSB3024"); engine.AssertLogDoesntContain("MSB3026"); } finally { File.Delete(sourceFile); } }
public void TestGeneralFrameworkMonikerGoodWithInvalidCharInIncludePath() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithInvalidCharInIncludePath"); string framework41Directory = Path.Combine(tempDirectory, "MyFramework\\v4.1\\"); string redistListDirectory = Path.Combine(framework41Directory, "RedistList"); string redistListFile = Path.Combine(redistListDirectory, "FrameworkList.xml"); try { Directory.CreateDirectory(framework41Directory); Directory.CreateDirectory(redistListDirectory); string redistListContents = "<FileList Redist='Microsoft-Windows-CLRCoreComp' IncludeFramework='v4.*' Name='Chained oh noes'>" + "<File AssemblyName='System.Xml' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "<File AssemblyName='Microsoft.Build.Engine' Version='2.0.0.0' PublicKeyToken='b03f5f7f11d50a3a' Culture='Neutral' FileVersion='2.0.50727.208' InGAC='true' />" + "</FileList >"; File.WriteAllText(redistListFile, redistListContents); string targetFrameworkMoniker = "MyFramework, Version=v4.1"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.RootPath = tempDirectory; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Equal(0, returnedPaths.Length); string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Null(displayName); FrameworkNameVersioning frameworkMoniker = new FrameworkNameVersioning(getReferencePaths.TargetFrameworkMoniker); engine.AssertLogContains("MSB3643"); } finally { if (Directory.Exists(framework41Directory)) { Directory.Delete(framework41Directory, true); } } }
public void AssemblyFoldersFromConfigFileMalformed() { var assemblyConfig = Path.GetTempFileName(); File.WriteAllText(assemblyConfig, "<<<>><>!" + TestFile); var moniker = "{AssemblyFoldersFromConfig:" + assemblyConfig + ",v4.5}"; try { MockEngine engine = new MockEngine(); ResolveAssemblyReference t = new ResolveAssemblyReference { BuildEngine = engine, Assemblies = new ITaskItem[] { new TaskItem("assemblyfromconfig2") }, SearchPaths = new[] { moniker } }; var success = Execute(t); Assert.False(success); Assert.Equal(0, t.ResolvedFiles.Length); engine.AssertLogContains(") specified in Microsoft.Common.CurrentVersion.targets was invalid. The error was: "); } finally { FileUtilities.DeleteNoThrow(assemblyConfig); } }
public void StopOnFirstFailureandBuildInParallelMultipleNode() { string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Error Text='Error'/> </Target> </Project> "); string project2 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='msbuild'> <Message Text='SecondProject'/> </Target> </Project> "); try { ITaskItem[] projects = new ITaskItem[] { new TaskItem(project1), new TaskItem(project2) }; // Test the various combinations of BuildInParallel and StopOnFirstFailure when the msbuild task is told there are multiple nodes // running in the system for (int i = 0; i < 4; i++) { MSBuild msbuildTask = new MSBuild(); MockEngine mockEngine = new MockEngine(); mockEngine.IsRunningMultipleNodes = true; msbuildTask.BuildEngine = mockEngine; msbuildTask.Projects = projects; msbuildTask.Targets = new string[] { "msbuild" }; // Make success true as the expected resultis false bool success = true; switch (i) { case 0: // Verify setting BuildInParallel and StopOnFirstFailure to // true will not cause the msbuild task to set BuildInParallel to false during the execute msbuildTask.BuildInParallel = true; msbuildTask.StopOnFirstFailure = true; success = msbuildTask.Execute(); // Verify build did build second project which has the message SecondProject mockEngine.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log Assert.IsTrue(msbuildTask.BuildInParallel, "Iteration of 0 Expected BuildInParallel to be true"); break; case 1: // Verify setting BuildInParallel to true and StopOnFirstFailure to // false will cause no change in BuildInParallel msbuildTask.BuildInParallel = true; msbuildTask.StopOnFirstFailure = false; success = msbuildTask.Execute(); // Verify build did build second project which has the message SecondProject mockEngine.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log Assert.IsTrue(msbuildTask.BuildInParallel, "Iteration of 1 Expected BuildInParallel to be true"); break; case 2: // Verify setting BuildInParallel to false and StopOnFirstFailure to // true will cause no change in BuildInParallel msbuildTask.BuildInParallel = false; msbuildTask.StopOnFirstFailure = true; success = msbuildTask.Execute(); // Verify build did not build second project which has the message SecondProject mockEngine.AssertLogDoesntContain("SecondProject"); // Verify the correct msbuild task messages are in the log Assert.IsFalse(msbuildTask.BuildInParallel, "Iteration of 2 Expected BuildInParallel to be false"); break; case 3: // Verify setting BuildInParallel to false and StopOnFirstFailure to // false will cause no change in BuildInParallel msbuildTask.BuildInParallel = false; msbuildTask.StopOnFirstFailure = false; success = msbuildTask.Execute(); // Verify build did build second project which has the message SecondProject mockEngine.AssertLogContains("SecondProject"); // Verify the correct msbuild task messages are in the log Assert.IsFalse(msbuildTask.BuildInParallel, "Iteration of 3 Expected BuildInParallel to be false"); break; } // The build should fail as the first project has an error Assert.IsFalse(success, "Iteration of i " + i + " Build Succeeded. See 'Standard Out' tab for details."); } } finally { File.Delete(project1); File.Delete(project2); } }
public void OneAttributePositionalParamInvalidSuffix() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_ParameterXXXXXXXXXX", "Microsoft"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.Equal(false, result); engine.AssertLogContains("MSB3098"); }
// Ignore: Flaky test public void CopyToDestinationFolderWithHardLinkFallbackTooManyLinks() { string sourceFile = FileUtilities.GetTemporaryFile(); string temp = Path.GetTempPath(); string destFolder = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A398"); string destFile = Path.Combine(destFolder, Path.GetFileName(sourceFile)); try { using (StreamWriter sw = new StreamWriter(sourceFile, true)) // HIGHCHAR: Test writes in UTF8 without preamble. sw.Write("This is a source temp file."); if (!Directory.Exists(destFolder)) { Directory.CreateDirectory(destFolder); } // Exhaust the number (1024) of directory entries that can be created for a file // This is 1 + (1 x hard links) // We need to test the fallback code path when we're out of directory entries for a file.. for (int n = 0; n < 1025 /* make sure */; n++) { string destLink = Path.Combine(destFolder, Path.GetFileNameWithoutExtension(sourceFile) + "." + n.ToString()); NativeMethods.CreateHardLink(destLink, sourceFile, IntPtr.Zero); } ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! t.UseHardlinksIfPossible = true; MockEngine me = new MockEngine(true); t.BuildEngine = me; t.SourceFiles = sourceFiles; t.DestinationFolder = new TaskItem(destFolder); t.SkipUnchangedFiles = true; bool success = t.Execute(); Assert.IsTrue(success, "success"); Assert.IsTrue(File.Exists(destFile), "destination exists"); Microsoft.Build.UnitTests.MockEngine.GetStringDelegate resourceDelegate = new Microsoft.Build.UnitTests.MockEngine.GetStringDelegate(AssemblyResources.GetString); me.AssertLogContainsMessageFromResource(resourceDelegate, "Copy.HardLinkComment", sourceFile, destFile); // Can't do this below, because the real message doesn't end with String.Empty, it ends with a CLR exception string, and so matching breaks in PLOC. // Instead look for the HRESULT that CLR unfortunately puts inside its exception string. Something like this // Tried to create more than a few links to a file that is supported by the file system. (! yhMcE! Exception from HRESULT: Table c?! 0x80070476) // me.AssertLogContainsMessageFromResource(resourceDelegate, "Copy.RetryingAsFileCopy", sourceFile, destFile, String.Empty); me.AssertLogContains("0x80070476"); string destinationFileContents; using (StreamReader sr = new StreamReader(destFile)) destinationFileContents = sr.ReadToEnd(); Assert.IsTrue ( destinationFileContents == "This is a source temp file.", "Expected the destination file to contain the contents of source file." ); Assert.AreEqual(1, t.DestinationFiles.Length); Assert.AreEqual(1, t.CopiedFiles.Length); Assert.AreEqual(destFile, t.DestinationFiles[0].ItemSpec); Assert.AreEqual(destFile, t.CopiedFiles[0].ItemSpec); // Now we will write new content to the source file // we'll then check that the destination file automatically // has the same content (i.e. it's been hard linked) using (StreamWriter sw = new StreamWriter(sourceFile, false)) // HIGHCHAR: Test writes in UTF8 without preamble. sw.Write("This is another source temp file."); // Read the destination file (it should have the same modified content as the source) using (StreamReader sr = new StreamReader(destFile)) destinationFileContents = sr.ReadToEnd(); Assert.IsTrue ( destinationFileContents == "This is a source temp file.", "Expected the destination copied file to contain the contents of original source file only." ); ((MockEngine)t.BuildEngine).AssertLogDoesntContain("MSB3026"); // Didn't do retries } finally { File.Delete(sourceFile); File.Delete(destFile); Directory.Delete(destFolder, true); } }
public void InvalidDirectoryPath() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") }; task.OutputDirectory = new TaskItem("||invalid||"); bool result = task.Execute(); Assert.AreEqual(false, result); engine.AssertLogContains("MSB3713"); }
public void DoNotRetryCopyNotSupportedException() { string sourceFile = FileUtilities.GetTemporaryFile(); string destinationFile = "foo:bar"; try { ITaskItem[] sourceFiles = new ITaskItem[] { new TaskItem(sourceFile) }; ITaskItem[] destinationFiles = new ITaskItem[] { new TaskItem(destinationFile) }; Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! // Allow the task's default (false) to have a chance if (useHardLinks) { t.UseHardlinksIfPossible = useHardLinks; } MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.SourceFiles = sourceFiles; t.DestinationFiles = destinationFiles; t.SkipUnchangedFiles = true; bool result = t.Execute(); Assert.IsFalse(result); Assert.IsTrue(engine.Errors == 1); Assert.IsTrue(engine.Warnings == 0); engine.AssertLogContains("MSB3021"); ((MockEngine)t.BuildEngine).AssertLogDoesntContain("MSB3026"); // Didn't do retries } finally { File.Delete(sourceFile); } }
public void ToolExeIsFoundOnToolPath() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.FullToolName = "cmd.exe"; string systemPath = Environment.GetFolderPath(Environment.SpecialFolder.System); t.ToolPath = systemPath; t.Execute(); Assert.AreEqual(Path.Combine(systemPath, "cmd.exe"), t.PathToToolUsed); engine.AssertLogContains("cmd.exe"); engine.Log = String.Empty; t.ToolExe = "xcopy.exe"; t.Execute(); Assert.AreEqual(Path.Combine(systemPath, "xcopy.exe"), t.PathToToolUsed); engine.AssertLogContains("xcopy.exe"); engine.AssertLogDoesntContain("cmd.exe"); } }
public void DoNotRetryWhenDestinationLockedDueToAcl() { string tempDirectory = Path.Combine(Path.GetTempPath(), "DoNotRetryWhenDestinationLockedDueToAcl"); string destinationFile = Path.Combine(tempDirectory, "DestinationFile.txt"); string sourceFile = Path.Combine(tempDirectory, "SourceFile.txt"); if (Directory.Exists(tempDirectory)) { FileUtilities.DeleteDirectoryNoThrow(tempDirectory, true); } Directory.CreateDirectory(tempDirectory); File.WriteAllText(destinationFile, "Destination"); File.WriteAllText(sourceFile, "SourceFile"); string userAccount = string.Format(@"{0}\{1}", System.Environment.UserDomainName, System.Environment.UserName); FileSystemAccessRule denyFile = new FileSystemAccessRule(userAccount, FileSystemRights.Write | FileSystemRights.Delete | FileSystemRights.DeleteSubdirectoriesAndFiles | FileSystemRights.WriteData, AccessControlType.Deny); FileSystemAccessRule denyDirectory = new FileSystemAccessRule(userAccount, FileSystemRights.DeleteSubdirectoriesAndFiles, AccessControlType.Deny); FileSecurity fSecurity = File.GetAccessControl(destinationFile); DirectorySecurity dSecurity = Directory.GetAccessControl(tempDirectory); try { fSecurity.AddAccessRule(denyFile); File.SetAccessControl(destinationFile, fSecurity); dSecurity.AddAccessRule(denyDirectory); Directory.SetAccessControl(tempDirectory, dSecurity); Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! // Allow the task's default (false) to have a chance if (useHardLinks) { t.UseHardlinksIfPossible = useHardLinks; } MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.SourceFiles = new TaskItem[] { new TaskItem(sourceFile) }; t.DestinationFiles = new TaskItem[] { new TaskItem(destinationFile) }; bool result = t.Execute(); Assert.IsFalse(result); engine.AssertLogContains("MSB3021"); // copy failed engine.AssertLogDoesntContain("MSB3026"); // Didn't retry Assert.IsTrue(engine.Errors == 1); Assert.IsTrue(engine.Warnings == 0); } finally { fSecurity.RemoveAccessRule(denyFile); File.SetAccessControl(destinationFile, fSecurity); dSecurity.RemoveAccessRule(denyDirectory); Directory.SetAccessControl(tempDirectory, dSecurity); if (Directory.Exists(tempDirectory)) { FileUtilities.DeleteDirectoryNoThrow(tempDirectory, true); } } }
public void TargetStopOnFirstFailureBuildInParallel() { string project1 = ObjectModelHelpers.CreateTempFileOnDisk(@" <Project xmlns='msbuildnamespace' ToolsVersion='msbuilddefaulttoolsversion'> <Target Name='T1'> <Message Text='Proj2 T1 message'/> </Target> <Target Name='T2'> <Message Text='Proj2 T2 message'/> </Target> <Target Name='T3'> <Error Text='Error'/> </Target> </Project> "); try { ITaskItem[] projects = new ITaskItem[] { new TaskItem(project1) }; for (int i = 0; i < 6; i++) { // Test the case where the error is in the last target MSBuild msbuildTask = new MSBuild(); MockEngine mockEngine = new MockEngine(); msbuildTask.BuildEngine = mockEngine; msbuildTask.Projects = projects; // Set to true as the expected result is false bool success = true; switch (i) { case 0: // Test the case where the error is in the last project and RunEachTargetSeparately = true msbuildTask.StopOnFirstFailure = true; msbuildTask.RunEachTargetSeparately = true; msbuildTask.Targets = new string[] { "T1", "T2", "T3" }; success = msbuildTask.Execute(); mockEngine.AssertLogContains("Proj2 T1 message"); mockEngine.AssertLogContains("Proj2 T2 message"); break; case 1: // Test the case where the error is in the second target out of 3. msbuildTask.StopOnFirstFailure = true; msbuildTask.RunEachTargetSeparately = true; msbuildTask.Targets = new string[] { "T1", "T3", "T2" }; success = msbuildTask.Execute(); mockEngine.AssertLogContains("Proj2 T1 message"); mockEngine.AssertLogDoesntContain("Proj2 T2 message"); // The build should fail as the first project has an error break; case 2: // Test case where error is in second last target but stopOnFirstFailure is false msbuildTask.RunEachTargetSeparately = true; msbuildTask.StopOnFirstFailure = false; msbuildTask.Targets = new string[] { "T1", "T3", "T2" }; success = msbuildTask.Execute(); mockEngine.AssertLogContains("Proj2 T1 message"); mockEngine.AssertLogContains("Proj2 T2 message"); break; // Test the cases where RunEachTargetSeparately is false. In these cases all of the targets should be submitted at once case 3: // Test the case where the error is in the last project and RunEachTargetSeparately = true msbuildTask.StopOnFirstFailure = true; msbuildTask.Targets = new string[] { "T1", "T2", "T3" }; success = msbuildTask.Execute(); mockEngine.AssertLogContains("Proj2 T1 message"); mockEngine.AssertLogContains("Proj2 T2 message"); // The build should fail as the first project has an error break; case 4: // Test the case where the error is in the second target out of 3. msbuildTask.StopOnFirstFailure = true; msbuildTask.Targets = new string[] { "T1", "T3", "T2" }; success = msbuildTask.Execute(); mockEngine.AssertLogContains("Proj2 T1 message"); mockEngine.AssertLogDoesntContain("Proj2 T2 message"); // The build should fail as the first project has an error break; case 5: // Test case where error is in second last target but stopOnFirstFailure is false msbuildTask.StopOnFirstFailure = false; msbuildTask.Targets = new string[] { "T1", "T3", "T2" }; success = msbuildTask.Execute(); mockEngine.AssertLogContains("Proj2 T1 message"); mockEngine.AssertLogDoesntContain("Proj2 T2 message"); break; } // The build should fail as the first project has an error Assert.IsFalse(success, "Iteration of i:" + i + "Build Succeeded. See 'Standard Out' tab for details."); } } finally { File.Delete(project1); } }
public void TaskFoundOnPath() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.FullToolName = "cmd.exe"; Assert.IsTrue(t.Execute()); Assert.AreEqual(0, t.ExitCode); Assert.AreEqual(0, engine.Errors); engine.AssertLogContains(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.System), "cmd.exe")); } }
public void LogMessageWithUnmatchedCurly() { MockEngine mockEngine = new MockEngine(); Task t = new MockTask(); t.BuildEngine = mockEngine; t.Log.LogMessage("echo {"); t.Log.LogMessageFromText("{1", MessageImportance.High); t.Log.LogCommandLine("{2"); t.Log.LogWarning("{3"); t.Log.LogError("{4"); mockEngine.AssertLogContains("echo {"); mockEngine.AssertLogContains("{1"); mockEngine.AssertLogContains("{2"); mockEngine.AssertLogContains("{3"); mockEngine.AssertLogContains("{4"); }
public void ErrorWhenTextSentToStandardError() { using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.LogStandardErrorAsError = true; t.MockCommandLineCommands = "/C Echo 'Who made you king anyways' 1>&2"; Assert.IsFalse(t.Execute()); engine.AssertLogDoesntContain("MSB3073"); engine.AssertLogContains("Who made you king anyways"); Assert.AreEqual(-1, t.ExitCode); Assert.AreEqual(1, engine.Errors); } }
public void NoNumber() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; TaskItem attribute = new TaskItem("AssemblyTrademarkAttribute"); attribute.SetMetadata("_Parameter", "2009"); task.AssemblyAttributes = new TaskItem[] { attribute }; task.Language = "c#"; task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.AreEqual(false, result); engine.AssertLogContains("MSB3098"); }
public void OverrideStdOutImportanceToHigh() { string tempFile = FileUtilities.GetTemporaryFile(); File.WriteAllText(tempFile, @"hello world"); using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); engine.MinimumMessageImportance = MessageImportance.High; t.BuildEngine = engine; t.FullToolName = "find.exe"; t.MockCommandLineCommands = "\"hello\" \"" + tempFile + "\""; t.StandardOutputImportance = "High"; Assert.IsTrue(t.Execute()); Assert.AreEqual(0, t.ExitCode); Assert.AreEqual(0, engine.Errors); engine.AssertLogContains("hello world"); } File.Delete(tempFile); }
public void SuccessAfterOneRetryContinueToNextFile() { Copy t = new Copy(); t.RetryDelayMilliseconds = 1; // speed up tests! // Allow the task's default (false) to have a chance if (useHardLinks) { t.UseHardlinksIfPossible = useHardLinks; } MockEngine engine = new MockEngine(true /* log to console */); t.BuildEngine = engine; t.SourceFiles = new ITaskItem[] { new TaskItem("c:\\source"), new TaskItem("c:\\source2") }; t.DestinationFiles = new ITaskItem[] { new TaskItem("c:\\destination"), new TaskItem("c:\\destination2") }; t.Retries = 1; t.RetryDelayMilliseconds = 1; // Can't really test the delay, but at least try passing in a value CopyFunctor copyFunctor = new CopyFunctor(2, false /* do not throw on failure */); bool result = t.Execute(copyFunctor.Copy); Assert.AreEqual(true, result); engine.AssertLogContains("MSB3026"); engine.AssertLogDoesntContain("MSB3027"); Assert.AreEqual(copyFunctor.FilesCopiedSuccessfully[0].Name, "c:\\source"); Assert.AreEqual(copyFunctor.FilesCopiedSuccessfully[1].Name, "c:\\source2"); }
public void ToolTaskCanChangeCanonicalErrorFormat() { string tempFile = FileUtilities.GetTemporaryFile(); File.WriteAllText(tempFile, @" Main.cs(17,20): warning CS0168: The variable 'foo' is declared but never used. BADTHINGHAPPENED: This is my custom error format that's not in canonical error format. "); using (MyTool t = new MyTool()) { MockEngine engine = new MockEngine(); t.BuildEngine = engine; // The command we're giving is the command to spew the contents of the temp // file we created above. t.MockCommandLineCommands = "/C type \"" + tempFile + "\""; t.Execute(); // The above command logged a canonical warning, as well as a custom error. engine.AssertLogContains("CS0168"); engine.AssertLogContains("The variable 'foo' is declared but never used"); engine.AssertLogContains("BADTHINGHAPPENED"); engine.AssertLogContains("This is my custom error format"); Assert.AreEqual(1, engine.Warnings, "Expected one warning in log."); Assert.AreEqual(1, engine.Errors, "Expected one error in log."); } File.Delete(tempFile); }
public void BuildProjectFileWithGlobalPropertiesSetInEngineObjectWithProjectFileAndTargetListSpecified ( ) { string[] targets; MockEngine myEngine = new MockEngine(); string projectFile = CreateGlobalPropertyProjectFile(); try { targets = new string[1]; targets[0] = "Build"; myEngine.GlobalProperties.SetProperty("MyGlobalProp", "SomePropertyText"); myEngine.BuildProjectFile(projectFile, targets); myEngine.AssertLogContains("SomePropertyText"); } finally { myEngine.UnregisterAllLoggers(); myEngine.UnloadAllProjects(); File.Delete(projectFile); } }