public void CanResolveHintPath() { var tempFile = _env.CreateFile("FakeSystem.Net.Http.dll", ""); bool result = ResolveHintPath(tempFile.Path); result.ShouldBe(true); }
public void CanUnzip() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder source = testEnvironment.CreateFolder(createFolder: true); TransientTestFolder destination = testEnvironment.CreateFolder(createFolder: false); testEnvironment.CreateFile(source, "BE78A17D30144B549D21F71D5C633F7D.txt", "file1"); testEnvironment.CreateFile(source, "A04FF4B88DF14860B7C73A8E75A4FB76.txt", "file2"); TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(destination.Path), OverwriteReadOnlyFiles = true, SkipUnchangedFiles = false, SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) } }; unzip.Execute().ShouldBeTrue(() => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "BE78A17D30144B549D21F71D5C633F7D.txt"), () => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "A04FF4B88DF14860B7C73A8E75A4FB76.txt"), () => _mockEngine.Log); } }
public void LogsErrorIfExcludeContainsPropertyReferences() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder source = testEnvironment.CreateFolder(createFolder: true); TransientTestFolder destination = testEnvironment.CreateFolder(createFolder: false); testEnvironment.CreateFile(source, "BE78A17D30144B549D21F71D5C633F7D.txt", "file1"); testEnvironment.CreateFile(source, "A04FF4B88DF14860B7C73A8E75A4FB76.txt", "file2"); TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(destination.Path), OverwriteReadOnlyFiles = true, SkipUnchangedFiles = false, SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, Exclude = "$(Include)" }; unzip.Execute().ShouldBeFalse(() => _mockEngine.Log); _mockEngine.Log.ShouldContain("MSB3938", () => _mockEngine.Log); } }
public void CanUnzip_WithIncludeAndExcludeFilter() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder source = testEnvironment.CreateFolder(createFolder: true); TransientTestFolder destination = testEnvironment.CreateFolder(createFolder: false); TransientTestFolder sub = source.CreateDirectory("sub"); testEnvironment.CreateFile(source, "file1.js", "file1"); testEnvironment.CreateFile(source, "file1.js.map", "file2"); testEnvironment.CreateFile(source, "file2.js", "file3"); testEnvironment.CreateFile(source, "readme.txt", "file4"); testEnvironment.CreateFile(sub, "subfile.js", "File5"); TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(destination.Path), OverwriteReadOnlyFiles = true, SkipUnchangedFiles = false, SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) }, Include = "*.js", Exclude = "*.js.map;sub\\*.js" }; unzip.Execute().ShouldBeTrue(() => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "file1.js"), () => _mockEngine.Log); _mockEngine.Log.ShouldNotContain(Path.Combine(destination.Path, "file1.js.map"), () => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "file2.js"), () => _mockEngine.Log); _mockEngine.Log.ShouldNotContain(Path.Combine(destination.Path, "readme.txt"), () => _mockEngine.Log); _mockEngine.Log.ShouldNotContain(Path.Combine(destination.Path, "sub", "subfile.js"), () => _mockEngine.Log); } }
public void CanUnzip_ExplicitDirectoryEntries() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder source = testEnvironment.CreateFolder(createFolder: true); TransientTestFolder destination = testEnvironment.CreateFolder(createFolder: false); testEnvironment.CreateFile(source, "BE78A17D30144B549D21F71D5C633F7D.txt", "file1"); testEnvironment.CreateFile(source, "A04FF4B88DF14860B7C73A8E75A4FB76.txt", "file2"); TransientTestFolder emptyDir = source.CreateDirectory("emptyDir"); TransientTestFolder subDir = source.CreateDirectory("subDir"); subDir.CreateFile("F83E9633685494E53BEF3794EDEEE6A6.txt", "file3"); subDir.CreateFile("21D6D4596067723B3AC5DF9A8B3CBFE7.txt", "file4"); TransientZipArchive zipArchive = TransientZipArchive.Create(source, testEnvironment.CreateFolder(createFolder: true)); Unzip unzip = new Unzip { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(destination.Path), OverwriteReadOnlyFiles = true, SkipUnchangedFiles = false, SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) } }; unzip.Execute().ShouldBeTrue(() => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "BE78A17D30144B549D21F71D5C633F7D.txt"), () => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "A04FF4B88DF14860B7C73A8E75A4FB76.txt"), () => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "subdir", "F83E9633685494E53BEF3794EDEEE6A6.txt"), () => _mockEngine.Log); _mockEngine.Log.ShouldContain(Path.Combine(destination.Path, "subdir", "21D6D4596067723B3AC5DF9A8B3CBFE7.txt"), () => _mockEngine.Log); Directory.Exists(Path.Combine(destination.Path, "emptyDir")); } }
public void PassedInFileSystemShouldBeReusedInSharedContext() { var projectFiles = new[] { _env.CreateFile("1.proj", @"<Project> <PropertyGroup Condition=`Exists('1.file')`></PropertyGroup> </Project>".Cleanup()).Path, _env.CreateFile("2.proj", @"<Project> <PropertyGroup Condition=`Exists('2.file')`></PropertyGroup> </Project>".Cleanup()).Path }; var projectCollection = _env.CreateProjectCollection().Collection; var fileSystem = new Helpers.LoggingFileSystem(); var evaluationContext = EvaluationContext.Create(EvaluationContext.SharingPolicy.Shared, fileSystem); foreach (var projectFile in projectFiles) { Project.FromFile( projectFile, new ProjectOptions { ProjectCollection = projectCollection, EvaluationContext = evaluationContext } ); } fileSystem.ExistenceChecks.OrderBy(kvp => kvp.Key) .ShouldBe( new Dictionary <string, int> { { Path.Combine(_env.DefaultTestDirectory.Path, "1.file"), 1 }, { Path.Combine(_env.DefaultTestDirectory.Path, "2.file"), 1 } }.OrderBy(kvp => kvp.Key)); fileSystem.FileOrDirectoryExistsCalls.ShouldBe(2); }
public MSBuildTestAssemblyFixture() { // Set field to indicate tests are running in the TestInfo class in Microsoft.Build.Framework. // See the comments on the TestInfo class for an explanation of why it works this way. var frameworkAssembly = typeof(Microsoft.Build.Framework.ITask).Assembly; var testInfoType = frameworkAssembly.GetType("Microsoft.Build.Framework.TestInfo"); var runningTestsField = testInfoType.GetField("s_runningTests", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static); runningTestsField.SetValue(null, true); _testEnvironment = TestEnvironment.Create(); _testEnvironment.DoNotLaunchDebugger(); // Reset the VisualStudioVersion environment variable. This will be set if tests are run from a VS command prompt. However, // if the environment variable is set, it will interfere with tests which set the SubToolsetVersion // (VerifySubToolsetVersionSetByConstructorOverridable), as the environment variable would take precedence. _testEnvironment.SetEnvironmentVariable("VisualStudioVersion", string.Empty); // Prevent test assemblies from logging any performance info. // https://github.com/dotnet/msbuild/pull/6274 _testEnvironment.SetEnvironmentVariable("DOTNET_PERFLOG_DIR", string.Empty); SetDotnetHostPath(_testEnvironment); // Use a project-specific temporary path // This is so multiple test projects can be run in parallel without sharing the same temp directory var subdirectory = Path.GetRandomFileName(); string newTempPath = Path.Combine(Path.GetTempPath(), subdirectory); var assemblyTempFolder = _testEnvironment.CreateFolder(newTempPath); _testEnvironment.SetTempPath(assemblyTempFolder.Path); _testEnvironment.CreateFile( transientTestFolder: assemblyTempFolder, fileName: "MSBuild_Tests.txt", contents: $"Temporary test folder for tests from {AppContext.BaseDirectory}"); // Ensure that we stop looking for a D.B.rsp at the root of the test temp _testEnvironment.CreateFile( transientTestFolder: assemblyTempFolder, fileName: "Directory.Build.rsp", contents: string.Empty); _testEnvironment.CreateFile( transientTestFolder: assemblyTempFolder, fileName: "Directory.Build.props", contents: "<Project />"); _testEnvironment.CreateFile( transientTestFolder: assemblyTempFolder, fileName: "Directory.Build.targets", contents: "<Project />"); }
private void AssertBuild( string[] targets, Action <BuildResult, MockLogger> assert, bool buildDeclaredReference = false, bool buildUndeclaredReference = false, bool addContinueOnError = false, bool excludeReferencesFromConstraints = false, bool isolateProjects = true, Func <string, string> projectReferenceModifier = null, Func <string, string> msbuildOnDeclaredReferenceModifier = null) { var rootProjectFile = _env.CreateFile().Path; var declaredReferenceFile = _env.CreateFile().Path; var undeclaredReferenceFile = _env.CreateFile().Path; var projectContents = string.Format( _project.Cleanup(), projectReferenceModifier?.Invoke(declaredReferenceFile) ?? declaredReferenceFile, msbuildOnDeclaredReferenceModifier?.Invoke(declaredReferenceFile) ?? declaredReferenceFile, undeclaredReferenceFile, addContinueOnError ? "ContinueOnError='WarnAndContinue'" : string.Empty, excludeReferencesFromConstraints ? $"{declaredReferenceFile};{undeclaredReferenceFile}" : string.Empty) .Cleanup(); File.WriteAllText(rootProjectFile, projectContents); File.WriteAllText(declaredReferenceFile, _declaredReference); File.WriteAllText(undeclaredReferenceFile, _undeclaredReference); var buildParameters = _buildParametersPrototype.Clone(); buildParameters.IsolateProjects = isolateProjects; using (var buildManagerSession = new Helpers.BuildManagerSession(_env, buildParameters)) { if (buildDeclaredReference) { buildManagerSession.BuildProjectFile(declaredReferenceFile, new[] { "DeclaredReferenceTarget" }) .OverallResult.ShouldBe(BuildResultCode.Success); } if (buildUndeclaredReference) { buildManagerSession.BuildProjectFile(undeclaredReferenceFile, new[] { "UndeclaredReferenceTarget" }) .OverallResult.ShouldBe(BuildResultCode.Success); } var result = buildManagerSession.BuildProjectFile(rootProjectFile, targets); assert(result, buildManagerSession.Logger); } }
public void InvalidSolutionFilters(string slnfValue, string exceptionReason) { Assert.False(File.Exists("C:\\notAPath2\\MSBuild.Dev.sln")); using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder folder = testEnvironment.CreateFolder(createFolder: true); TransientTestFile sln = testEnvironment.CreateFile(folder, "Dev.sln"); TransientTestFile slnf = testEnvironment.CreateFile(folder, "Dev.slnf", slnfValue.Replace(@"C:\\notAPath\\MSBuild.Dev.sln", sln.Path.Replace("\\", "\\\\"))); InvalidProjectFileException e = Should.Throw <InvalidProjectFileException>(() => SolutionFile.Parse(slnf.Path)); e.HelpKeyword.ShouldBe(exceptionReason); } }
public void SkippedTargetsShouldNotTriggerCacheMissEnforcement() { var referenceFile = _env.CreateFile( "reference", @" <Project DefaultTargets=`DefaultTarget` InitialTargets=`InitialTarget`> <Target Name=`A` Condition=`true == false`/> <Target Name=`DefaultTarget` Condition=`true == false`/> <Target Name=`InitialTarget` Condition=`true == false`/> </Project> ".Cleanup()).Path; var projectFile = _env.CreateFile( "proj", $@" <Project DefaultTargets=`Build`> <ItemGroup> <ProjectReference Include=`{referenceFile}` /> </ItemGroup> <Target Name=`Build`> <MSBuild Projects=`@(ProjectReference)` Targets=`A` /> <MSBuild Projects=`@(ProjectReference)` /> </Target> </Project> ".Cleanup()).Path; _buildParametersPrototype.IsolateProjects.ShouldBeTrue(); var buildParameters = _buildParametersPrototype.Clone(); using (var buildManagerSession = new Helpers.BuildManagerSession(_env, buildParameters)) { // seed caches with results from the reference buildManagerSession.BuildProjectFile(referenceFile).OverallResult.ShouldBe(BuildResultCode.Success); buildManagerSession.BuildProjectFile(referenceFile, new [] { "A" }).OverallResult.ShouldBe(BuildResultCode.Success); buildManagerSession.BuildProjectFile(projectFile).OverallResult.ShouldBe(BuildResultCode.Success); buildManagerSession.Logger.WarningCount.ShouldBe(0); buildManagerSession.Logger.ErrorCount.ShouldBe(0); // twice for the initial target, once for A, once for DefaultTarget buildManagerSession.Logger.AssertMessageCount("Previously built successfully", 4); } }
public void ASolutionShouldBeTheSingleEntryPoint(params string[] files) { for (var i = 0; i < files.Length; i++) { files[i] = _env.CreateFile(files[i], string.Empty).Path; } var exception = Should.Throw <ArgumentException>( () => { new ProjectGraph(files); }); exception.Message.ShouldContain("MSB4261"); }
public void TaskNodesDieAfterBuild() { using (TestEnvironment env = TestEnvironment.Create()) { string pidTaskProject = $@" <Project> <UsingTask TaskName=""ProcessIdTask"" AssemblyName=""net.r_eg.IeXod.Engine.UnitTests"" TaskFactory=""TaskHostFactory"" /> <Target Name='AccessPID'> <ProcessIdTask> <Output PropertyName=""PID"" TaskParameter=""Pid"" /> </ProcessIdTask> </Target> </Project>"; TransientTestFile project = env.CreateFile("testProject.csproj", pidTaskProject); ProjectInstance projectInstance = new ProjectInstance(project.Path); projectInstance.Build().ShouldBeTrue(); string processId = projectInstance.GetPropertyValue("PID"); string.IsNullOrEmpty(processId).ShouldBeFalse(); Int32.TryParse(processId, out int pid).ShouldBeTrue(); Process.GetCurrentProcess().Id.ShouldNotBe <int>(pid); try { Process taskHostNode = Process.GetProcessById(pid); taskHostNode.WaitForExit(2000).ShouldBeTrue(); } // We expect the TaskHostNode to exit quickly. If it exits before Process.GetProcessById, it will throw an ArgumentException. catch (ArgumentException e) { e.Message.ShouldBe($"Process with an Id of {pid} is not running."); } } }
public void TestPrecomputedCacheOutput() { using (TestEnvironment env = TestEnvironment.Create()) { TransientTestFile standardCache = env.CreateFile(".cache"); ResolveAssemblyReference t = new ResolveAssemblyReference() { _cache = new SystemState() }; t._cache.instanceLocalFileStateCache = new Dictionary <string, SystemState.FileState>() { { Path.Combine(standardCache.Path, "assembly1"), new SystemState.FileState(DateTime.Now) }, { Path.Combine(standardCache.Path, "assembly2"), new SystemState.FileState(DateTime.Now) { Assembly = new Shared.AssemblyNameExtension("hi") } } }; t._cache.IsDirty = true; t.StateFile = standardCache.Path; t.WriteStateFile(); int standardLen = File.ReadAllText(standardCache.Path).Length; File.Delete(standardCache.Path); standardLen.ShouldBeGreaterThan(0); string precomputedPath = standardCache.Path + ".cache"; t._cache.IsDirty = true; t.AssemblyInformationCacheOutputPath = precomputedPath; t.WriteStateFile(); File.Exists(standardCache.Path).ShouldBeFalse(); int preLen = File.ReadAllText(precomputedPath).Length; preLen.ShouldBeGreaterThan(0); preLen.ShouldNotBe(standardLen); } }
public void SdkReferenceIsCorrect_CreatedFromOnDiskProject_SdkAttributeSet() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFile projectFile = testEnvironment.CreateFile( "test.proj", @" <Project> <Import Project=""Sdk.props"" Sdk=""My.Sdk"" /> </Project>"); ProjectRootElement rootElement = ProjectRootElement.Open(projectFile.Path); ProjectImportElement importElement = rootElement.Imports.First(); importElement.SdkReference.Name.ShouldBe("My.Sdk"); importElement.SdkReference.Version.ShouldBeNull(); importElement.SdkReference.MinimumVersion.ShouldBeNull(); SetPropertyAndExpectProjectXmlChangedEventToNotFire(rootElement, () => importElement.Sdk = "My.Sdk"); SetPropertyAndExpectProjectXmlChangedEventToFire(rootElement, () => importElement.Version = "1.2.0", "Set Import Version 1.2.0"); SetPropertyAndExpectProjectXmlChangedEventToNotFire(rootElement, () => importElement.Version = "1.2.0"); importElement.SdkReference.Name.ShouldBe("My.Sdk"); importElement.SdkReference.Version.ShouldBe("1.2.0"); importElement.SdkReference.MinimumVersion.ShouldBeNull(); SetPropertyAndExpectProjectXmlChangedEventToFire(rootElement, () => importElement.MinimumVersion = "1.0.0", "Set Import Minimum Version 1.0.0"); SetPropertyAndExpectProjectXmlChangedEventToNotFire(rootElement, () => importElement.MinimumVersion = "1.0.0"); importElement.SdkReference.Name.ShouldBe("My.Sdk"); importElement.SdkReference.Version.ShouldBe("1.2.0"); importElement.SdkReference.MinimumVersion.ShouldBe("1.0.0"); } }
public void LogsErrorIfReadOnlyFileCannotBeOverwitten() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder source = testEnvironment.CreateFolder(createFolder: true); TransientTestFolder destination = testEnvironment.CreateFolder(createFolder: false); TransientTestFile file1 = testEnvironment.CreateFile(source, "D6DFD219DACE48F8B86EFCDF98433333.txt", "file1"); new FileInfo(file1.Path).IsReadOnly = true; TransientZipArchive zipArchive = TransientZipArchive.Create(source, destination); Unzip unzip = new Unzip { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(source.Path), OverwriteReadOnlyFiles = false, SkipUnchangedFiles = false, SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) } }; unzip.Execute().ShouldBeFalse(() => _mockEngine.Log); _mockEngine.Log.ShouldContain($"D6DFD219DACE48F8B86EFCDF98433333.txt{ (NativeMethodsShared.IsMono ? "\"" : "'") } is denied", () => _mockEngine.Log); } }
public void SkipUnchangedFiles() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder folder = testEnvironment.CreateFolder(createFolder: true); DownloadFile downloadFile = new DownloadFile { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(folder.Path), HttpMessageHandler = new MockHttpMessageHandler((message, token) => new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("C197675A3CC64CAA80680128CF4578C9") { Headers = { LastModified = DateTimeOffset.UtcNow.AddDays(-1) } }, RequestMessage = new HttpRequestMessage(HttpMethod.Get, "http://success/foo.txt") }), SkipUnchangedFiles = true, SourceUrl = "http://success/foo.txt" }; testEnvironment.CreateFile(folder, "foo.txt", "C197675A3CC64CAA80680128CF4578C9"); downloadFile.Execute().ShouldBeTrue(); _mockEngine.Log.ShouldContain("Did not download file from \"http://success/foo.txt\"", () => _mockEngine.Log); } }
private static TransientTestFile CreateProject( TestEnvironment env, int projectNumber, int[] projectReferences = null, Dictionary <string, string[]> projectReferenceTargets = null, string defaultTargets = null) { var sb = new StringBuilder(64); // Use "Build" when the default target is unspecified since in practice that is usually the default target. sb.AppendFormat("<Project DefaultTargets=\"{0}\"><ItemGroup>", defaultTargets ?? "Build"); if (projectReferences != null) { foreach (int projectReference in projectReferences) { sb.AppendFormat("<ProjectReference Include=\"{0}.proj\" />", projectReference); } } if (projectReferenceTargets != null) { foreach (KeyValuePair <string, string[]> pair in projectReferenceTargets) { sb.AppendFormat("<ProjectReferenceTargets Include=\"{0}\" Targets=\"{1}\" />", pair.Key, string.Join(";", pair.Value)); } } sb.Append("</ItemGroup></Project>"); return(env.CreateFile(projectNumber + ".proj", sb.ToString())); }
public void CanOverwriteReadOnlyFile() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder source = testEnvironment.CreateFolder(createFolder: true); TransientTestFolder destination = testEnvironment.CreateFolder(createFolder: false); TransientTestFile file1 = testEnvironment.CreateFile(source, "638AF4AE88A146E09CB69FE1CA7083DC.txt", "file1"); new FileInfo(file1.Path).IsReadOnly = true; TransientZipArchive zipArchive = TransientZipArchive.Create(source, destination); Unzip unzip = new Unzip { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(source.Path), OverwriteReadOnlyFiles = true, SkipUnchangedFiles = false, SourceFiles = new ITaskItem[] { new TaskItem(zipArchive.Path) } }; unzip.Execute().ShouldBeTrue(() => _mockEngine.Log); _mockEngine.Log.ShouldContain("638AF4AE88A146E09CB69FE1CA7083DC", () => _mockEngine.Log); } }
public void TestOldNuget() { string msbuildExePath = Path.GetDirectoryName(RunnerUtilities.PathToCurrentlyRunningMsBuildExe); using TestEnvironment testEnvironment = TestEnvironment.Create(); TransientTestFolder folder = testEnvironment.CreateFolder(createFolder: true); // The content of the solution isn't known to matter, but having a custom solution makes it easier to add requirements should they become evident. TransientTestFile sln = testEnvironment.CreateFile(folder, "test.sln", @" Microsoft Visual Studio Solution File, Format Version 12.00 \# Visual Studio 15 VisualStudioVersion = 15.0.26124.0 MinimumVisualStudioVersion = 15.0.26124.0 Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal "); RunnerUtilities.RunProcessAndGetOutput(Path.Combine(msbuildExePath, "nuget", "NuGet.exe"), "restore " + sln.Path + " -MSBuildPath \"" + msbuildExePath + "\"", out bool success, outputHelper: _output); success.ShouldBeTrue(); }
public void InlineTaskWithAssembly() { using (TestEnvironment env = TestEnvironment.Create()) { TransientTestFolder folder = env.CreateFolder(createFolder: true); TransientTestFile assemblyProj = env.CreateFile(folder, "5106.csproj", @$ " <Project DefaultTargets=" "Build" "> <PropertyGroup> <TargetFrameworkVersion>{MSBuildConstants.StandardTestTargetFrameworkVersion}</TargetFrameworkVersion>
/// <summary> /// Retrieves a Project with the specified contents using the specified projectCollection /// </summary> private Project CreateProject(string contents, string toolsVersion, ProjectCollection projectCollection) { Project project = new Project(XmlReader.Create(new StringReader(contents)), null, toolsVersion, projectCollection) { FullPath = _env.CreateFile().Path }; project.Save(); return(project); }
public void TestPreComputedCacheInputMatchesOutput() { using (TestEnvironment env = TestEnvironment.Create()) { TransientTestFile precomputedCache = env.CreateFile(".cache"); ResolveAssemblyReference rarWriterTask = new ResolveAssemblyReference() { _cache = new SystemState() }; string dllName = Path.Combine(Path.GetDirectoryName(precomputedCache.Path), "randomFolder", "dll.dll"); rarWriterTask._cache.instanceLocalFileStateCache = new Dictionary <string, SystemState.FileState>() { { Path.Combine(precomputedCache.Path, "..", "assembly1", "assembly1"), new SystemState.FileState(DateTime.Now) }, { Path.Combine(precomputedCache.Path, "assembly2"), new SystemState.FileState(DateTime.Now) { Assembly = new Shared.AssemblyNameExtension("hi") } }, { dllName, new SystemState.FileState(DateTime.Now) { Assembly = null, RuntimeVersion = "v4.0.30319", FrameworkNameAttribute = new System.Runtime.Versioning.FrameworkName(".NETFramework", Version.Parse("4.7.2"), "Profile"), scatterFiles = new string[] { "first", "second" } } } }; rarWriterTask.AssemblyInformationCacheOutputPath = precomputedCache.Path; rarWriterTask._cache.IsDirty = true; // Throws an exception because precomputedCache.Path already exists. Should.Throw <InvalidOperationException>(() => rarWriterTask.WriteStateFile()); File.Delete(precomputedCache.Path); rarWriterTask.WriteStateFile(); ResolveAssemblyReference rarReaderTask = new ResolveAssemblyReference(); rarReaderTask.StateFile = precomputedCache.Path.Substring(0, precomputedCache.Path.Length - 6); // Not a real path; should not be used. rarReaderTask.AssemblyInformationCachePaths = new ITaskItem[] { new TaskItem(precomputedCache.Path) }; // At this point, the standard cache does not exist, so it defaults to reading the "precomputed" cache. // Then we verify that the information contained in that cache matches what we'd expect. rarReaderTask.ReadStateFile(p => true); rarReaderTask._cache.instanceLocalFileStateCache.ShouldContainKey(dllName); SystemState.FileState assembly3 = rarReaderTask._cache.instanceLocalFileStateCache[dllName]; assembly3.Assembly.ShouldBeNull(); assembly3.RuntimeVersion.ShouldBe("v4.0.30319"); assembly3.FrameworkNameAttribute.Version.ShouldBe(Version.Parse("4.7.2")); assembly3.scatterFiles.Length.ShouldBe(2); assembly3.scatterFiles[1].ShouldBe("second"); } }
public void CanOvewriteExistingFile() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder sourceFolder = testEnvironment.CreateFolder(createFolder: true); testEnvironment.CreateFile(sourceFolder, "F1C22D660B0D4DAAA296C1B980320B03.txt", "F1C22D660B0D4DAAA296C1B980320B03"); testEnvironment.CreateFile(sourceFolder, "AA825D1CB154492BAA58E1002CE1DFEB.txt", "AA825D1CB154492BAA58E1002CE1DFEB"); TransientTestFile file = testEnvironment.CreateFile(testEnvironment.DefaultTestDirectory, "test.zip", contents: "test"); ZipDirectory zipDirectory = new ZipDirectory { BuildEngine = _mockEngine, DestinationFile = new TaskItem(file.Path), Overwrite = true, SourceDirectory = new TaskItem(sourceFolder.Path) }; zipDirectory.Execute().ShouldBeTrue(() => _mockEngine.Log); _mockEngine.Log.ShouldContain(sourceFolder.Path, () => _mockEngine.Log); _mockEngine.Log.ShouldContain(file.Path, () => _mockEngine.Log); using (FileStream stream = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.Read)) using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read)) { archive.Entries .Select(i => i.FullName) .ToList() .ShouldBe( new List <string> { "F1C22D660B0D4DAAA296C1B980320B03.txt", "AA825D1CB154492BAA58E1002CE1DFEB.txt" }, ignoreOrder: true); } } }
public void ParseSolutionFilter() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder folder = testEnvironment.CreateFolder(createFolder: true); TransientTestFolder src = testEnvironment.CreateFolder(Path.Combine(folder.Path, "src"), createFolder: true); TransientTestFile microsoftBuild = testEnvironment.CreateFile(src, "Microsoft.Build.csproj"); TransientTestFile msbuild = testEnvironment.CreateFile(src, "MSBuild.csproj"); TransientTestFile commandLineUnitTests = testEnvironment.CreateFile(src, "Microsoft.Build.CommandLine.UnitTests.csproj"); TransientTestFile tasksUnitTests = testEnvironment.CreateFile(src, "Microsoft.Build.Tasks.UnitTests.csproj"); // The important part of this .sln is that it has references to each of the four projects we just created. TransientTestFile sln = testEnvironment.CreateFile(folder, "Microsoft.Build.Dev.sln", @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 15 VisualStudioVersion = 15.0.27004.2009 MinimumVisualStudioVersion = 10.0.40219.1 Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""Microsoft.Build"", """ + Path.Combine("src", Path.GetFileName(microsoftBuild.Path)) + @""", ""{69BE05E2-CBDA-4D27-9733-44E12B0F5627}"" EndProject Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""MSBuild"", """ + Path.Combine("src", Path.GetFileName(msbuild.Path)) + @""", ""{6F92CA55-1D15-4F34-B1FE-56C0B7EB455E}"" EndProject Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""Microsoft.Build.CommandLine.UnitTests"", """ + Path.Combine("src", Path.GetFileName(commandLineUnitTests.Path)) + @""", ""{0ADDBC02-0076-4159-B351-2BF33FAA46B2}"" EndProject Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""Microsoft.Build.Tasks.UnitTests"", """ + Path.Combine("src", Path.GetFileName(tasksUnitTests.Path)) + @""", ""{CF999BDE-02B3-431B-95E6-E88D621D9CBF}"" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution EndGlobalSection EndGlobal "); TransientTestFile slnf = testEnvironment.CreateFile(folder, "Dev.slnf", @" { ""solution"": { ""path"": """ + sln.Path.Replace("\\", "\\\\") + @""", ""projects"": [ """ + Path.Combine("src", Path.GetFileName(microsoftBuild.Path) !).Replace("\\", "\\\\") + @""", """ + Path.Combine("src", Path.GetFileName(tasksUnitTests.Path) !).Replace("\\", "\\\\") + @""" ] } }"); SolutionFile sp = SolutionFile.Parse(slnf.Path); sp.ProjectShouldBuild(Path.Combine("src", Path.GetFileName(microsoftBuild.Path) !)).ShouldBeTrue(); sp.ProjectShouldBuild(Path.Combine("src", Path.GetFileName(tasksUnitTests.Path) !)).ShouldBeTrue(); (sp.ProjectShouldBuild(Path.Combine("src", Path.GetFileName(commandLineUnitTests.Path) !)) || sp.ProjectShouldBuild(Path.Combine("src", Path.GetFileName(msbuild.Path) !)) || sp.ProjectShouldBuild(Path.Combine("src", "notAProject.csproj"))) .ShouldBeFalse(); } }
public void CanZipDirectory() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder sourceFolder = testEnvironment.CreateFolder(createFolder: true); testEnvironment.CreateFile(sourceFolder, "6DE6060259C44DB6B145159376751C22.txt", "6DE6060259C44DB6B145159376751C22"); testEnvironment.CreateFile(sourceFolder, "CDA3DD8C25A54A7CAC638A444CB1EAD0.txt", "CDA3DD8C25A54A7CAC638A444CB1EAD0"); string zipFilePath = Path.Combine(testEnvironment.CreateFolder(createFolder: true).Path, "test.zip"); ZipDirectory zipDirectory = new ZipDirectory { BuildEngine = _mockEngine, DestinationFile = new TaskItem(zipFilePath), SourceDirectory = new TaskItem(sourceFolder.Path) }; zipDirectory.Execute().ShouldBeTrue(() => _mockEngine.Log); _mockEngine.Log.ShouldContain(sourceFolder.Path, () => _mockEngine.Log); _mockEngine.Log.ShouldContain(zipFilePath, () => _mockEngine.Log); using (FileStream stream = new FileStream(zipFilePath, FileMode.Open, FileAccess.Read, FileShare.Read)) using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Read)) { archive.Entries .Select(i => i.FullName) .ToList() .ShouldBe( new List <string> { "6DE6060259C44DB6B145159376751C22.txt", "CDA3DD8C25A54A7CAC638A444CB1EAD0.txt" }, ignoreOrder: true); } } }
public void InvalidCacheFilesShouldLogError(byte[] cacheContents) { var project = CreateProjectFileWithBuildTargetAndItems(_env, 1).Path; var existingFile = _env.CreateFile( "FileExists", new string( cacheContents.Select(Convert.ToChar) .ToArray())).Path; var result = BuildProjectFileUsingBuildManager( project, _logger, new BuildParameters { InputResultsCacheFiles = new[] { existingFile } }); result.OverallResult.ShouldBe(BuildResultCode.Failure); _logger.FullLog.ShouldContain("MSB4256:"); _logger.AllBuildEvents.Count.ShouldBe(4); _logger.ErrorCount.ShouldBe(1); }
public void CodeTypeFromTaskBody() { foreach (RoslynCodeTaskFactoryCodeType codeType in Enum.GetValues(typeof(RoslynCodeTaskFactoryCodeType)).Cast <RoslynCodeTaskFactoryCodeType>()) { TryLoadTaskBodyAndExpectSuccess($"<Code Type=\"{codeType}\">code</Code>", expectedCodeType: codeType); } using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFile file = testEnvironment.CreateFile(fileName: "236D48CE30064161B31B55DBF088C8B2", contents: "6159BD98607A460AA4F11D2FA92E5436"); TryLoadTaskBodyAndExpectSuccess($"<Code Source=\"{file.Path}\"/>", expectedCodeType: RoslynCodeTaskFactoryCodeType.Class); } }
public void SourceCodeFromFile() { const string sourceCodeFileContents = @" 1F214E27A13F432B9397F1733BC55929 9111DC29B0064E6994A68CFE465404D4"; using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFile file = testEnvironment.CreateFile(fileName: "CB3096DA4A454768AA9C0C4D422FC188.tmp", contents: sourceCodeFileContents); TryLoadTaskBodyAndExpectSuccess( $"<Code Source=\"{file.Path}\"/>", expectedSourceCode: sourceCodeFileContents, expectedCodeType: RoslynCodeTaskFactoryCodeType.Class); } }
public void StandardCacheTakesPrecedence() { using (TestEnvironment env = TestEnvironment.Create()) { TransientTestFile standardCache = env.CreateFile(".cache"); ResolveAssemblyReference rarWriterTask = new ResolveAssemblyReference() { _cache = new SystemState() }; rarWriterTask._cache.instanceLocalFileStateCache = new Dictionary <string, SystemState.FileState>(); rarWriterTask.StateFile = standardCache.Path; rarWriterTask._cache.IsDirty = true; // Write standard cache rarWriterTask.WriteStateFile(); string dllName = Path.Combine(Path.GetDirectoryName(standardCache.Path), "randomFolder", "dll.dll"); rarWriterTask._cache.instanceLocalFileStateCache.Add(dllName, new SystemState.FileState(DateTime.Now) { Assembly = null, RuntimeVersion = "v4.0.30319", FrameworkNameAttribute = new System.Runtime.Versioning.FrameworkName(".NETFramework", Version.Parse("4.7.2"), "Profile"), scatterFiles = new string[] { "first", "second" } }); string precomputedCachePath = standardCache.Path + ".cache"; rarWriterTask.AssemblyInformationCacheOutputPath = precomputedCachePath; rarWriterTask._cache.IsDirty = true; // Write precomputed cache rarWriterTask.WriteStateFile(); ResolveAssemblyReference rarReaderTask = new ResolveAssemblyReference(); rarReaderTask.StateFile = standardCache.Path; rarReaderTask.AssemblyInformationCachePaths = new ITaskItem[] { new TaskItem(precomputedCachePath) }; // At this point, we should have created two cache files: one "normal" one and one "precomputed" one. // When we read the state file, it should read from the caches produced in a normal build. In this case, // the normal cache does not have dll.dll, whereas the precomputed cache does, so it should not be // present when we read it. rarReaderTask.ReadStateFile(p => true); rarReaderTask._cache.instanceLocalFileStateCache.ShouldNotContainKey(dllName); } }
public void LogsErrorIfSourceFileCannotBeOpened() { using (TestEnvironment testEnvironment = TestEnvironment.Create()) { TransientTestFolder folder = testEnvironment.CreateFolder(createFolder: false); TransientTestFile file = testEnvironment.CreateFile("foo.txt", "foo"); Unzip unzip = new Unzip { BuildEngine = _mockEngine, DestinationFolder = new TaskItem(folder.Path), SourceFiles = new ITaskItem[] { new TaskItem(file.Path), } }; unzip.Execute().ShouldBeFalse(() => _mockEngine.Log); _mockEngine.Log.ShouldContain("MSB3933", () => _mockEngine.Log); } }