public void PeekWithNamespaceNode() { MockEngine engine = new MockEngine(true); string xmlInputPath; Prepare(_xmlFileWithNs, out xmlInputPath); XmlPeek p = new XmlPeek(); p.BuildEngine = engine; p.XmlInputPath = new TaskItem(xmlInputPath); p.Query = "//s:variable/."; p.Namespaces = "<Namespace Prefix=\"s\" Uri=\"http://nsurl\" />"; Assert.True(p.Execute()); // "Test should've passed" Assert.Equal(3, p.Result.Length); // "result Length should be 3" string[] results = new string[] { "<s:variable Type=\"String\" Name=\"a\" xmlns:s=\"http://nsurl\"></s:variable>", "<s:variable Type=\"String\" Name=\"b\" xmlns:s=\"http://nsurl\"></s:variable>", "<s:variable Type=\"String\" Name=\"c\" xmlns:s=\"http://nsurl\"></s:variable>" }; for (int i = 0; i < p.Result.Length; i++) { Assert.True(p.Result[i].ItemSpec.Equals(results[i]), "Results don't match: " + p.Result[i].ItemSpec); } }
public void PokeNoNamespace() { MockEngine engine = new MockEngine(true); string xmlInputPath; Prepare(_xmlFileNoNs, out xmlInputPath); XmlPoke p = new XmlPoke(); p.BuildEngine = engine; p.XmlInputPath = new TaskItem(xmlInputPath); p.Query = "//variable/@Name"; p.Value = new TaskItem("Mert"); p.Execute(); List<int> positions = new List<int>(); positions.AddRange(new int[] { 117, 172, 227 }); string result; using (StreamReader sr = new StreamReader(xmlInputPath)) { result = sr.ReadToEnd(); Regex r = new Regex("Mert"); MatchCollection mc = r.Matches(result); foreach (Match m in mc) { Assert.True(positions.Contains(m.Index), "This test should effect 3 positions. There should be 3 occurances of 'Mert'\n" + result); } } }
public void TestResourceAccess() { MyToolTaskExtension t = new MyToolTaskExtension(); MockEngine engine = new MockEngine(); t.BuildEngine = engine; // No need to actually check the outputted strings. We only care that this doesn't throw, which means that // the resource strings were reachable. // Normal CSC messages first, from private XMakeTasks resources. They should be accessible with t.Log t.Log.LogErrorWithCodeFromResources("Csc.AssemblyAliasContainsIllegalCharacters", "PlanetSide", "Knights of the Old Republic"); t.Log.LogWarningWithCodeFromResources("Csc.InvalidParameter"); t.Log.LogMessageFromResources("Vbc.ParameterHasInvalidValue", "Rome Total War", "Need for Speed Underground"); // Now shared messages. Should be accessible with the private LogShared property PropertyInfo logShared = typeof(ToolTask).GetProperty("LogShared", BindingFlags.Instance | BindingFlags.NonPublic); TaskLoggingHelper log = (TaskLoggingHelper)logShared.GetValue(t, null); log.LogWarningWithCodeFromResources("Shared.FailedCreatingTempFile", "Gothic II"); log.LogMessageFromResources("Shared.CannotConvertStringToBool", "foo"); // Now private Utilities messages. Should be accessible with the private LogPrivate property PropertyInfo logPrivate = typeof(ToolTask).GetProperty("LogPrivate", BindingFlags.Instance | BindingFlags.NonPublic); log = (TaskLoggingHelper)logPrivate.GetValue(t, null); log.LogErrorWithCodeFromResources("ToolTask.CommandTooLong", "Painkiller"); log.LogWarningWithCodeFromResources("ToolTask.CouldNotStartToolExecutable", "Fallout Tactics", "Fallout 2"); log.LogMessageFromResources("ToolsLocationHelper.InvalidRedistFile", "Deus Ex", "Fallout"); }
public void ResourceAccessSanityCheck() { Csc t = new Csc(); MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.Log.LogErrorFromResources("Beyond Good and Evil"); }
public void ResourceAccessSanityCheck() { MyToolTaskExtension t = new MyToolTaskExtension(); MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.Log.LogErrorFromResources("Beyond Good and Evil"); }
private ExecWrapper PrepareExecWrapper(string command) { IBuildEngine2 mockEngine = new MockEngine(true); ExecWrapper exec = new ExecWrapper(); exec.BuildEngine = mockEngine; exec.Command = command; return exec; }
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 ResourceAccessSanityCheck() { Assert.Throws<ArgumentException>(() => { MyToolTaskExtension t = new MyToolTaskExtension(); MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.Log.LogErrorFromResources("Beyond Good and Evil"); } ); }
public void TestGeneralFrameworkMonikerGood() { string targetFrameworkMoniker = ".NetFramework, Version=v4.5"; MockEngine engine = new MockEngine(); GetReferenceAssemblyPaths getReferencePaths = new GetReferenceAssemblyPaths(); getReferencePaths.BuildEngine = engine; getReferencePaths.TargetFrameworkMoniker = targetFrameworkMoniker; getReferencePaths.Execute(); string[] returnedPaths = getReferencePaths.ReferenceAssemblyPaths; Assert.Equal(ToolLocationHelper.GetPathToReferenceAssemblies(new FrameworkNameVersioning(targetFrameworkMoniker)).Count, returnedPaths.Length); Assert.Equal(0, engine.Errors); // "Expected the log to contain no errors" }
public void Setup() { // Create a delegate helper to make the testing of a method which uses a lot of fileExists a bit easier _mockExists = new MockFileExists(_defaultSdkToolsPath); // We need an engine to see any logging messages the method may log _mockEngine = new MockEngine(); // Dummy task to get a TaskLoggingHelper TaskToLogFrom loggingTask = new TaskToLogFrom(); loggingTask.BuildEngine = _mockEngine; _log = loggingTask.Log; _log.TaskResources = AssemblyResources.PrimaryResources; }
public void TestInputChecks1() { MockEngine engine = new MockEngine(); SGenExtension sgen = new SGenExtension(); sgen.BuildEngine = engine; sgen.BuildAssemblyName = "MyAsm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" + Path.GetInvalidPathChars()[0]; sgen.BuildAssemblyPath = "C:\\SomeFolder\\MyAsm.dll"; sgen.ShouldGenerateSerializer = true; sgen.UseProxyTypes = false; // This should result in a quoted parameter... sgen.KeyFile = "c:\\Some Folder\\MyKeyFile.snk"; string commandLine = sgen.CommandLine(); Assert.IsTrue(engine.Errors == 1); }
public void ErrorInNamespaceDecl() { MockEngine engine = new MockEngine(true); string xmlInputPath; Prepare(_xmlFileWithNs, out xmlInputPath); XmlPeek p = new XmlPeek(); p.BuildEngine = engine; p.XmlInputPath = new TaskItem(xmlInputPath); p.Query = "//s:variable/@Name"; p.Namespaces = "<!THIS IS ERROR Namespace Prefix=\"s\" Uri=\"http://nsurl\" />"; bool executeResult = p.Execute(); Assert.IsTrue(engine.Log.Contains("MSB3742"), "Engine Log: " + engine.Log); Assert.IsFalse(executeResult, "Execution should've failed"); }
public void CombineFileDirectory() { WriteCodeFragment task = new WriteCodeFragment(); MockEngine engine = new MockEngine(true); task.BuildEngine = engine; task.Language = "c#"; task.AssemblyAttributes = new TaskItem[] { new TaskItem("aa") }; task.OutputFile = new TaskItem("CombineFileDirectory.tmp"); task.OutputDirectory = new TaskItem(Path.GetTempPath()); bool result = task.Execute(); Assert.AreEqual(true, result); string file = Path.Combine(Path.GetTempPath(), "CombineFileDirectory.tmp"); Assert.AreEqual(file, task.OutputFile.ItemSpec); Assert.AreEqual(true, File.Exists(file)); }
public void EmptyMessage() { MockEngine e = new MockEngine(); Message m = new Message(); m.BuildEngine = e; // don't set text bool retval = m.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.IsTrue(retval); Assert.IsTrue(e.Messages == 0); }
public void SomeInputsFailToCreate() { string temp = Path.GetTempPath(); string file = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A38e"); string dir = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A38f"); string invalid = "!@#$%^&*()|"; string dir2 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A390"); try { FileStream fs = File.Create(file); fs.Close(); //we're gonna try to delete it MakeDir t = new MakeDir(); MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.Directories = new ITaskItem[] { new TaskItem(dir), new TaskItem(file), new TaskItem(invalid), new TaskItem(dir2) }; bool success = t.Execute(); Assert.IsTrue(!success); Assert.AreEqual(2, t.DirectoriesCreated.Length); Assert.AreEqual(dir, t.DirectoriesCreated[0].ItemSpec); Assert.AreEqual(dir2, t.DirectoriesCreated[1].ItemSpec); Assert.IsTrue ( engine.Log.Contains ( String.Format(AssemblyResources.GetString("MakeDir.Comment"), dir) ) ); } finally { Directory.Delete(dir); File.Delete(file); Directory.Delete(dir2); } }
public void MultilineMessage() { MockEngine e = new MockEngine(); Message m = new Message(); m.BuildEngine = e; m.Text = "messagetext\n messagetext2 \n\nmessagetext3"; bool retval = m.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.IsTrue(retval); Assert.IsTrue(e.Log.IndexOf("messagetext\n messagetext2 \n\nmessagetext3") != -1); }
public void Message() { MockEngine e = new MockEngine(); Message m = new Message(); m.BuildEngine = e; m.Text = "messagetext"; bool retval = m.Execute(); Console.WriteLine("==="); Console.WriteLine(e.Log); Console.WriteLine("==="); Assert.True(retval); Assert.NotEqual(-1, e.Log.IndexOf("messagetext")); }
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 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 TestGeneralFrameworkMonikerGoodWithRoot() { string tempDirectory = Path.Combine(Path.GetTempPath(), "TestGeneralFrameworkMonikerGoodWithRoot"); 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' Name='.NET Framework 4.1'>" + "<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; string displayName = getReferencePaths.TargetFrameworkMonikerDisplayName; Assert.Equal(1, returnedPaths.Length); Assert.True(returnedPaths[0].Equals(framework41Directory, StringComparison.OrdinalIgnoreCase)); Assert.Equal(0, engine.Log.Length); // "Expected the log to contain nothing" Assert.True(displayName.Equals(".NET Framework 4.1", StringComparison.OrdinalIgnoreCase)); } finally { if (Directory.Exists(framework41Directory)) { Directory.Delete(framework41Directory, true); } } }
public void GetResolvedRuleSetPath_FullPath_Existent() { MockEngine mockEngine = new MockEngine(); ResolveCodeAnalysisRuleSet task = new ResolveCodeAnalysisRuleSet(); task.BuildEngine = mockEngine; string codeAnalysisRuleSet = Path.Combine(Path.GetTempPath(), @"CodeAnalysis.ruleset"); task.CodeAnalysisRuleSet = codeAnalysisRuleSet; task.MSBuildProjectDirectory = null; task.CodeAnalysisRuleSetDirectories = null; using (new TemporaryFile(codeAnalysisRuleSet, "foo")) { bool result = task.Execute(); string resolvedRuleSet = task.ResolvedCodeAnalysisRuleSet; Assert.AreEqual(expected: true, actual: result); Assert.AreEqual(expected: codeAnalysisRuleSet, actual: resolvedRuleSet); mockEngine.AssertLogDoesntContain("MSB3884"); } }
public void AttributeForwarding() { string temp = Path.GetTempPath(); string dir = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A391"); try { MakeDir t = new MakeDir(); MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.Directories = new ITaskItem[] { new TaskItem(dir) }; t.Directories[0].SetMetadata("Locale", "en-GB"); bool success = t.Execute(); Assert.IsTrue(success); Assert.AreEqual(1, t.DirectoriesCreated.Length); Assert.AreEqual(dir, t.DirectoriesCreated[0].ItemSpec); Assert.IsTrue ( engine.Log.Contains ( String.Format(AssemblyResources.GetString("MakeDir.Comment"), dir) ) ); Assert.AreEqual("en-GB", t.DirectoriesCreated[0].GetMetadata("Locale")); // Output ItemSpec should not be overwritten. Assert.AreEqual(dir, t.DirectoriesCreated[0].ItemSpec); } finally { Directory.Delete(dir); } }
public void MissingNamespaceParameters() { MockEngine engine = new MockEngine(true); string xmlInputPath; Prepare(_xmlFileWithNs, out xmlInputPath); string[] attrs = new string[] { "Prefix=\"s\"", "Uri=\"http://nsurl\"" }; for (int i = 0; i < Math.Pow(2, attrs.Length); i++) { string res = ""; for (int k = 0; k < attrs.Length; k++) { if ((i & (int)Math.Pow(2, k)) != 0) { res += attrs[k] + " "; } } XmlPoke p = new XmlPoke(); p.BuildEngine = engine; p.XmlInputPath = new TaskItem(xmlInputPath); p.Query = "//s:variable/@Name"; p.Namespaces = "<Namespace " + res + " />"; p.Value = new TaskItem("Nur"); bool result = p.Execute(); if (i == 3) { Assert.IsTrue(result, "Only 3rd value should pass."); } else { Assert.IsFalse(result, "Only 3rd value should pass."); } } }
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 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 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 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 DefineConstants() { IBuildEngine2 mockEngine = new MockEngine(); Csc t = new Csc(); t.BuildEngine = mockEngine; // Perfectly valid, so no change expected. Assert.AreEqual("DEBUG;TRACE", t.GetDefineConstantsSwitch("DEBUG;TRACE")); // Spaces should be removed. Assert.AreEqual("DEBUG;TRACE", t.GetDefineConstantsSwitch("DEBUG; TRACE")); // Commas become semicolons. Assert.AreEqual("DEBUG;TRACE", t.GetDefineConstantsSwitch("DEBUG , TRACE")); // We ignore anything that has quotes. Assert.AreEqual("DEBUG", t.GetDefineConstantsSwitch("DEBUG , \"TRACE\"")); // We ignore anything that has an equals sign. Assert.AreEqual("DEBUG;TRACE", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE=MYVALUE")); // Since we split on space and comma, what seems like a value actually // becomes a new constant. Yes, this is really what happens in // Everett VS. Assert.AreEqual("DEBUG;TRACE;MYDEFINE;MYVALUE", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE = MYVALUE")); // Since we split on space and comma/semicolon, what seems like a value actually // becomes a new constant. Yes, this is really what happens in // Everett VS. Assert.AreEqual("DEBUG;TRACE;MYDEFINE;MY;VALUE", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE = MY VALUE")); // Even if the comma is inside quotes, we still split on it. Yup, this // is what VS did in Everett. Assert.AreEqual("DEBUG;TRACE;MYDEFINE;WEIRD", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE = \"MY,WEIRD,VALUE\"")); // Once again, quotes aren't allowed. Assert.AreEqual("DEBUG;TRACE;MYDEFINE", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE = \"MY VALUE\"")); // (,),@,%,$ aren't allowed, and spaces are a valid delimiter. Assert.AreEqual("DEBUG;TRACE;a;b", t.GetDefineConstantsSwitch("DEBUG;TRACE;a b;(;);@;%;$")); // Dash is not allowed either. It's not a valid character in an // identifier. Assert.AreEqual("DEBUG;TRACE;MYDEFINE", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE = -1")); // Identifiers cannot begin with numbers. Assert.AreEqual("DEBUG;TRACE;MYDEFINE", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE;123ABC")); // But identifiers can contain numbers. Assert.AreEqual("DEBUG;TRACE;MYDEFINE;ABC123", t.GetDefineConstantsSwitch("DEBUG,TRACE,MYDEFINE;ABC123")); // Identifiers can contain initial underscores and embedded underscores. Assert.AreEqual("_DEBUG;MY_DEFINE", t.GetDefineConstantsSwitch("_DEBUG, MY_DEFINE")); // We should get back "null" if there's nothing valid in there. Assert.AreEqual(null, t.GetDefineConstantsSwitch("DEBUG=\"myvalue\"")); }
public GetFileHash_Tests(ITestOutputHelper output) { _mockEngine = new MockEngine(output); }
/// <summary> /// Prepares the test environment, creates necessary files. /// </summary> /// <param name="dir">The temp dir</param> /// <param name="xmlPaths">The xml file's path</param> /// <param name="xslPath">The xsl file's path</param> /// <param name="xslCompiledPath">The xsl dll's path</param> /// <param name="outputPaths">The output file's path</param> /// <param name="xmlInputs">The xml input ways</param> /// <param name="xslInputs">The xsl input ways</param> /// <param name="engine">The Mock engine</param> private void Prepare(out string dir, out TaskItem[] xmlPaths, out TaskItem xslPath, out TaskItem xslCompiledPath, out TaskItem[] outputPaths, out List <KeyValuePair <XslTransformation.XmlInput.XmlModes, object> > xmlInputs, out List <KeyValuePair <XslTransformation.XsltInput.XslModes, object> > xslInputs, out MockEngine engine) { dir = Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString()); Directory.CreateDirectory(dir); // save XML and XSLT documents. xmlPaths = new TaskItem[] { new TaskItem(Path.Combine(dir, "doc.xml")) }; xslPath = new TaskItem(Path.Combine(dir, "doc.xslt")); xslCompiledPath = new TaskItem(Path.Combine(dir, "doc.dll")); outputPaths = new TaskItem[] { new TaskItem(Path.Combine(dir, "testout.xml")) }; using (StreamWriter sw = new StreamWriter(xmlPaths[0].ItemSpec, false)) { sw.Write(_xmlDocument); sw.Close(); } using (StreamWriter sw = new StreamWriter(xslPath.ItemSpec, false)) { sw.Write(_xslDocument); sw.Close(); } xmlInputs = new List <KeyValuePair <XslTransformation.XmlInput.XmlModes, object> >(); xslInputs = new List <KeyValuePair <XslTransformation.XsltInput.XslModes, object> >(); xmlInputs.Add(new KeyValuePair <XslTransformation.XmlInput.XmlModes, object>(XslTransformation.XmlInput.XmlModes.Xml, _xmlDocument)); xmlInputs.Add(new KeyValuePair <XslTransformation.XmlInput.XmlModes, object>(XslTransformation.XmlInput.XmlModes.XmlFile, xmlPaths)); xslInputs.Add(new KeyValuePair <XslTransformation.XsltInput.XslModes, object>(XslTransformation.XsltInput.XslModes.Xslt, _xslDocument)); xslInputs.Add(new KeyValuePair <XslTransformation.XsltInput.XslModes, object>(XslTransformation.XsltInput.XslModes.XsltFile, xslPath)); #if FEATURE_COMPILED_XSL Compile(xslPath.ItemSpec, xslCompiledPath.ItemSpec); #endif engine = new MockEngine(); List <bool> results = new List <bool>(); }
public void OutputsOnlyIncludeSuccessfulMoves() { string temp = Path.GetTempPath(); string inFile1 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A392"); string inFile2 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A393"); string invalidFile = "!@#$%^&*()|"; string validOutFile = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A394"); try { FileStream fs = null; FileStream fs2 = null; try { fs = File.Create(inFile1); fs2 = File.Create(inFile2); } finally { fs.Dispose(); fs2.Dispose(); } Move t = new Move(); MockEngine engine = new MockEngine(true /* log to console */); t.BuildEngine = engine; ITaskItem i1 = new TaskItem(inFile1); i1.SetMetadata("Locale", "en-GB"); i1.SetMetadata("Color", "taupe"); t.SourceFiles = new ITaskItem[] { new TaskItem(inFile2), i1 }; ITaskItem o1 = new TaskItem(validOutFile); o1.SetMetadata("Locale", "fr"); o1.SetMetadata("Flavor", "Pumpkin"); t.DestinationFiles = new ITaskItem[] { new TaskItem(invalidFile), o1 }; bool success = t.Execute(); Assert.False(success); Assert.Single(t.MovedFiles); Assert.Equal(validOutFile, t.MovedFiles[0].ItemSpec); Assert.Equal(2, t.DestinationFiles.Length); Assert.Equal("fr", t.DestinationFiles[1].GetMetadata("Locale")); // Output ItemSpec should not be overwritten. Assert.Equal(invalidFile, t.DestinationFiles[0].ItemSpec); Assert.Equal(validOutFile, t.DestinationFiles[1].ItemSpec); Assert.Equal(validOutFile, t.MovedFiles[0].ItemSpec); // Sources attributes should be left untouched. Assert.Equal("en-GB", t.SourceFiles[1].GetMetadata("Locale")); Assert.Equal("taupe", t.SourceFiles[1].GetMetadata("Color")); // Attributes not on Sources should be left untouched. Assert.Equal("Pumpkin", t.DestinationFiles[1].GetMetadata("Flavor")); Assert.Equal("Pumpkin", t.MovedFiles[0].GetMetadata("Flavor")); // Attribute should have been forwarded Assert.Equal("taupe", t.DestinationFiles[1].GetMetadata("Color")); Assert.Equal("taupe", t.MovedFiles[0].GetMetadata("Color")); // Attribute should not have been updated if it already existed on destination Assert.Equal("fr", t.DestinationFiles[1].GetMetadata("Locale")); Assert.Equal("fr", t.MovedFiles[0].GetMetadata("Locale")); } finally { File.Delete(inFile1); File.Delete(inFile2); File.Delete(validOutFile); } }
/// <summary> /// Given a log and a resource string, acquires the text of that resource string and /// compares it to the log. Assert fails if the log 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 VerifyLogDoesNotContainResource(MockEngine e, TaskLoggingHelper log, string messageResource, params object[] args) { string message = log.FormatResourceString(messageResource, args); e.AssertLogDoesntContain(message); }
public void OutputsOnlyIncludeSuccessfulCopies() { string temp = Path.GetTempPath(); string inFile1 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A392"); string inFile2 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A393"); string invalidFile = "!@#$%^&*()|"; string validOutFile = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A394"); try { FileStream fs = null; FileStream fs2 = null; try { fs = File.Create(inFile1); fs2 = File.Create(inFile2); } finally { fs.Close(); fs2.Close(); } 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; ITaskItem i1 = new TaskItem(inFile1); i1.SetMetadata("Locale", "en-GB"); i1.SetMetadata("Color", "taupe"); t.SourceFiles = new ITaskItem[] { new TaskItem(inFile2), i1 }; ITaskItem o1 = new TaskItem(validOutFile); o1.SetMetadata("Locale", "fr"); o1.SetMetadata("Flavor", "Pumpkin"); t.DestinationFiles = new ITaskItem[] { new TaskItem(invalidFile), o1 }; bool success = t.Execute(); Assert.IsTrue(!success); Assert.AreEqual(1, t.CopiedFiles.Length); Assert.AreEqual(validOutFile, t.CopiedFiles[0].ItemSpec); Assert.AreEqual(2, t.DestinationFiles.Length); Assert.AreEqual("fr", t.DestinationFiles[1].GetMetadata("Locale")); // Output ItemSpec should not be overwritten. Assert.AreEqual(invalidFile, t.DestinationFiles[0].ItemSpec); Assert.AreEqual(validOutFile, t.DestinationFiles[1].ItemSpec); Assert.AreEqual(validOutFile, t.CopiedFiles[0].ItemSpec); // Sources attributes should be left untouched. Assert.AreEqual("en-GB", t.SourceFiles[1].GetMetadata("Locale")); Assert.AreEqual("taupe", t.SourceFiles[1].GetMetadata("Color")); // Attributes not on Sources should be left untouched. Assert.AreEqual("Pumpkin", t.DestinationFiles[1].GetMetadata("Flavor")); Assert.AreEqual("Pumpkin", t.CopiedFiles[0].GetMetadata("Flavor")); // Attribute should have been forwarded Assert.AreEqual("taupe", t.DestinationFiles[1].GetMetadata("Color")); Assert.AreEqual("taupe", t.CopiedFiles[0].GetMetadata("Color")); // Attribute should not have been updated if it already existed on destination Assert.AreEqual("fr", t.DestinationFiles[1].GetMetadata("Locale")); Assert.AreEqual("fr", t.CopiedFiles[0].GetMetadata("Locale")); ((MockEngine)t.BuildEngine).AssertLogDoesntContain("MSB3026"); // Didn't do retries } finally { File.Delete(inFile1); File.Delete(inFile2); File.Delete(validOutFile); } }
public void CopyFileOnItself() { string temp = Path.GetTempPath(); string file = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A395"); try { FileStream fs = null; try { fs = File.Create(file); } finally { fs.Close(); } 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 ITaskItem[] { new TaskItem(file) }; t.DestinationFiles = new ITaskItem[] { new TaskItem(file) }; t.SkipUnchangedFiles = true; bool success = t.Execute(); Assert.IsTrue(success); Assert.AreEqual(1, t.DestinationFiles.Length); Assert.AreEqual(file, t.DestinationFiles[0].ItemSpec); ((MockEngine)t.BuildEngine).AssertLogDoesntContain("MSB3026"); // Didn't do retries, nothing to do t = new Copy(); // Allow the task's default (false) to have a chance if (useHardLinks) { t.UseHardlinksIfPossible = useHardLinks; } engine = new MockEngine(); t.BuildEngine = engine; t.SourceFiles = new ITaskItem[] { new TaskItem(file) }; t.DestinationFiles = new ITaskItem[] { new TaskItem(file) }; t.SkipUnchangedFiles = false; success = t.Execute(); Assert.IsTrue(success); Assert.AreEqual(1, t.DestinationFiles.Length); Assert.AreEqual(file, t.DestinationFiles[0].ItemSpec); Assert.AreEqual(1, t.CopiedFiles.Length); ((MockEngine)t.BuildEngine).AssertLogDoesntContain("MSB3026"); // Didn't do retries, nothing to do } finally { File.Delete(file); } }
[PlatformSpecific(TestPlatforms.Windows)] // "Under Unix all filenames are valid and this test is not useful" public void SomeInputsFailToCreate() { string temp = Path.GetTempPath(); string file = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A38e"); string dir = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A38f"); string invalid = "!@#$%^&*()|"; string dir2 = Path.Combine(temp, "2A333ED756AF4dc392E728D0F864A390"); try { FileStream fs = File.Create(file); fs.Dispose(); //we're gonna try to delete it MakeDir t = new MakeDir(); MockEngine engine = new MockEngine(); t.BuildEngine = engine; t.Directories = new ITaskItem[] { new TaskItem(dir), new TaskItem(file), new TaskItem(invalid), new TaskItem(dir2) }; bool success = t.Execute(); if (NativeMethodsShared.IsWindows) { Assert.False(success); Assert.Equal(2, t.DirectoriesCreated.Length); Assert.Equal(dir2, t.DirectoriesCreated[1].ItemSpec); } else { // Since Unix pretty much does not have invalid characters, // the invalid name is not really invalid Assert.True(success); Assert.Equal(3, t.DirectoriesCreated.Length); Assert.Equal(dir2, t.DirectoriesCreated[2].ItemSpec); } Assert.Equal(dir, t.DirectoriesCreated[0].ItemSpec); Assert.True ( engine.Log.Contains ( String.Format(AssemblyResources.GetString("MakeDir.Comment"), dir) ) ); } finally { FileUtilities.DeleteWithoutTrailingBackslash(dir); File.Delete(file); if (!NativeMethodsShared.IsWindows) { File.Delete(invalid); } FileUtilities.DeleteWithoutTrailingBackslash(dir2); } }