public async Task RestoreCommand_WhenSwitchingBetweenLowercaseSettings_LockFileAlwaysRespectsLatestSetting(bool isLowercase) { // Arrange using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); sourceDir.Create(); projectDir.Create(); var resolverA = new VersionFolderPathResolver(packagesDir.FullName, !isLowercase); var resolverB = new VersionFolderPathResolver(packagesDir.FullName, isLowercase); var sources = new List <string>(); sources.Add(sourceDir.FullName); var projectJson = @" { ""frameworks"": { ""netstandard1.0"": { ""dependencies"": { ""PackageA"": ""1.0.0-Beta"" } } } }"; File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson); var specPath = Path.Combine(projectDir.FullName, "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath); var logger = new TestLogger(); var lockFilePath = Path.Combine(projectDir.FullName, "project.lock.json"); var lockFileFormat = new LockFileFormat(); var packageId = "PackageA"; var packageVersion = "1.0.0-Beta"; var packageAContext = new SimpleTestPackageContext(packageId, packageVersion); packageAContext.AddFile("lib/netstandard1.0/a.dll"); SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext); // Act // Execute the first restore with the opposite lowercase setting. var requestA = new TestRestoreRequest( spec, sources.Select(x => Repository.Factory.GetCoreV3(x)), packagesDir.FullName, Enumerable.Empty <string>(), logger) { LockFilePath = lockFilePath, IsLowercasePackagesDirectory = !isLowercase }; var commandA = new RestoreCommand(requestA); var resultA = await commandA.ExecuteAsync(); await resultA.CommitAsync(logger, CancellationToken.None); // Execute the second restore with the request lowercase setting. var requestB = new TestRestoreRequest( spec, sources.Select(x => Repository.Factory.GetCoreV3(x)), packagesDir.FullName, Enumerable.Empty <string>(), logger) { LockFilePath = lockFilePath, IsLowercasePackagesDirectory = isLowercase, ExistingLockFile = lockFileFormat.Read(lockFilePath) }; var commandB = new RestoreCommand(requestB); var resultB = await commandB.ExecuteAsync(); await resultB.CommitAsync(logger, CancellationToken.None); // Assert // Commands should have succeeded. Assert.True(resultA.Success); Assert.True(resultB.Success); // The lock file library path should match the requested case. var libraryA = resultA .LockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(libraryA); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolverA.GetPackageDirectory(packageId, libraryA.Version)), libraryA.Path); Assert.True(File.Exists(resolverA.GetPackageFilePath(packageId, libraryA.Version))); var libraryB = resultB .LockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(libraryB); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)), libraryB.Path); Assert.True(File.Exists(resolverB.GetPackageFilePath(packageId, libraryB.Version))); // The lock file on disk should match the second restore's library. var diskLockFile = lockFileFormat.Read(lockFilePath); var lockFileLibrary = diskLockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(lockFileLibrary); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)), libraryB.Path); Assert.Equal(libraryB, lockFileLibrary); } }
public async Task MsbuildRestore_SupportsPackageSaveModeAsync() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = new SimpleTestProjectContext( "a", ProjectStyle.PackagesConfig, pathContext.SolutionRoot); projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461)); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/a.dll"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); using (var writer = new StreamWriter(Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "packages.config"))) { writer.Write( @"<packages> <package id=""x"" version=""1.0.0"" targetFramework=""net461"" /> </packages>"); } var configPath = Path.Combine(Path.GetDirectoryName(pathContext.SolutionRoot), "NuGet.Config"); var doc = XDocument.Parse(File.ReadAllText(configPath)); var root = doc.Element(XName.Get("configuration")); var config = root.Element(XName.Get("config")); var setting = new XElement(XName.Get("add")); setting.Add(new XAttribute(XName.Get("key"), "PackageSaveMode")); setting.Add(new XAttribute(XName.Get("value"), "nuspec;nupkg")); config.Add(setting); File.Delete(configPath); File.WriteAllText(configPath, doc.ToString()); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, packageX); var pkgPath = Path.Combine(pathContext.SolutionRoot, "packages", "x.1.0.0"); // Act var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore {pathContext.SolutionRoot} /p:RestorePackagesConfig=true", ignoreExitCode: true); // Assert Assert.True(result.ExitCode == 0, result.AllOutput); Assert.True(File.Exists(Path.Combine(pkgPath, "x.1.0.0.nupkg"))); Assert.True(File.Exists(Path.Combine(pkgPath, "x.nuspec"))); } }
public async Task MsbuildRestore_WithLegacyPackageReferenceProject_BothStaticGraphAndRegularRestoreNoOp() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var project = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); project.AddPackageToAllFrameworks(packageX); packageX.AddFile("lib/net461/a.dll"); solution.Projects.Add(project); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, packageX); var projectOutputPaths = new[] { project.AssetsFileOutputPath, project.PropsOutput, project.TargetsOutput, project.CacheFileOutputPath, }; var projectOutputTimestamps = new Dictionary <string, DateTime>(); // Restore the project with a PackageReference which generates assets var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore {project.ProjectPath}", ignoreExitCode: true); result.Success.Should().BeTrue(because: result.AllOutput); foreach (var asset in projectOutputPaths) { var fileInfo = new FileInfo(asset); fileInfo.Exists.Should().BeTrue(because: result.AllOutput); projectOutputTimestamps.Add(asset, fileInfo.LastWriteTimeUtc); } // Restore the project with a PackageReference which generates assets result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore /p:RestoreUseStaticGraphEvaluation=true {project.ProjectPath}", ignoreExitCode: true); result.Success.Should().BeTrue(because: result.AllOutput); foreach (var asset in projectOutputPaths) { var fileInfo = new FileInfo(asset); fileInfo.Exists.Should().BeTrue(because: result.AllOutput); fileInfo.LastWriteTimeUtc.Should().Be(projectOutputTimestamps[asset]); } } }
public async Task Restore_LegacyPackageReference_SkipBuildTransitive() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile("lib/net461/y.dll"); packageY.AddFile("build/y.targets"); packageY.AddFile("buildCrossTargeting/y.targets"); packageY.AddFile("build/y.props"); packageY.AddFile("buildCrossTargeting/y.props"); packageY.AddFile("buildTransitive/y.targets"); packageY.Exclude = "buildTransitive"; var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/x.dll"); packageX.Dependencies.Add(packageY); projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); // Act var result = RunRestore(pathContext); // Assert var assetsFile = projectA.AssetsFile; Assert.NotNull(assetsFile); foreach (var target in assetsFile.Targets) { var library = target.Libraries.FirstOrDefault(lib => lib.Name.Equals("y")); Assert.NotNull(library); Assert.False(library.Build.Any(build => build.Path.Equals("buildTransitive/y.targets"))); Assert.False(library.Build.Any(build => build.Path.Equals("build/y.props"))); } } }
public async Task AddPackageToSource_InstallsPackageAsync() { using (var testDirectory = TestDirectory.Create()) { var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0")); var packageContext = new SimpleTestPackageContext() { Id = packageIdentity.Id, Version = packageIdentity.Version.ToNormalizedString(), Nuspec = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?> <package> <metadata> <id>{packageIdentity.Id}</id> <version>{packageIdentity.Version.ToNormalizedString()}</version> <title /> <frameworkAssemblies> <frameworkAssembly assemblyName=""System.Runtime"" /> </frameworkAssemblies> <contentFiles> <files include=""lib/net45/{packageIdentity.Id}.dll"" copyToOutput=""true"" flatten=""false"" /> </contentFiles> </metadata> </package>") }; packageContext.AddFile($"lib/net45/{packageIdentity.Id}.dll"); var sourcePackageDirectoryPath = Path.Combine(testDirectory.Path, "source"); var destinationDirectoryPath = Path.Combine(testDirectory.Path, "destination"); Directory.CreateDirectory(destinationDirectoryPath); await SimpleTestPackageUtility.CreatePackagesAsync(sourcePackageDirectoryPath, packageContext); var sourcePackageFilePath = Path.Combine( sourcePackageDirectoryPath, $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg"); var destinationPackageDirectoryPath = Path.Combine( destinationDirectoryPath, packageIdentity.Id, packageIdentity.Version.ToNormalizedString()); var extractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv3, PackageExtractionBehavior.XmlDocFileSaveMode, NullLogger.Instance, signedPackageVerifier: null, signedPackageVerifierSettings: null); var context = new OfflineFeedAddContext( sourcePackageFilePath, destinationDirectoryPath, NullLogger.Instance, throwIfSourcePackageIsInvalid: false, throwIfPackageExistsAndInvalid: false, throwIfPackageExists: false, extractionContext: extractionContext); await OfflineFeedUtility.AddPackageToSource(context, CancellationToken.None); Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg"))); Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg.sha512"))); Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, $"{packageIdentity.Id}.nuspec"))); Assert.True(File.Exists(Path.Combine(destinationPackageDirectoryPath, "lib", "net45", $"{packageIdentity.Id}.dll"))); } }
public async Task ContentFilesMSBuild_VerifyConditionForFallbackContentItemGroupAsync(string files, string expected) { // Arrange var logger = new TestLogger(); using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var tfi = new List <TargetFrameworkInformation> { new TargetFrameworkInformation() { FrameworkName = NuGetFramework.Parse("net462") } }; var spec = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "net46"); spec.Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("a", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); var project = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, spec).Single(); var packageA = new SimpleTestPackageContext("a"); packageA.AddFile("contentFiles/any/any/anyMarker.txt"); foreach (var file in files.Split('|')) { packageA.AddFile(file); } await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageA); // Create dg file var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec); dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); // Act var result = (await NETCoreRestoreTestUtility.RunRestore( pathContext, logger, new List <PackageSource>() { new PackageSource(pathContext.PackageSource) }, dgFile, cacheContext)).Single(); var props = XDocument.Load(project.PropsOutput); var itemGroups = props.Root.Elements(XName.Get("ItemGroup", "http://schemas.microsoft.com/developer/msbuild/2003")).ToArray(); var group = itemGroups.Single(e => e.ToString().Contains("anyMarker.txt")); // Assert Assert.True(result.Success, logger.ShowErrors()); Assert.Equal(expected.Trim(), group.Attribute(XName.Get("Condition")).Value.Trim()); } }
public async Task CompatilibityChecker_RuntimeFoundInSamePackage_Success() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": { ""version"": ""1.0.0"" } } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); request.RequestedRuntimes.Add("win7-x86"); var packageA = new SimpleTestPackageContext("packageA"); packageA.AddFile("ref/netstandard1.3/a.dll"); packageA.AddFile("ref/netstandard1.3/b.dll"); packageA.AddFile("ref/netstandard1.3/c.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/a.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/b.ni.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.1/c.dll"); SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.True(result.Success, logger.ShowErrors()); // Verify both libraries were installed Assert.Equal(1, result.LockFile.Libraries.Count); // Verify no compatibility issues Assert.True(result.CompatibilityCheckResults.All(check => check.Success)); } }
public async Task RelatedProperty_TopLevelPackageWithAssemblyExtensions_RelatedPropertyAddedCorrectly( string assemblyExtension, string assemblyName, string[] assetFileList, string expectedRelatedProperty) { // Arrange using (var pathContext = new SimpleTestPathContext()) { var framework = "net5.0"; // A -> packaegX var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK( "A", pathContext.SolutionRoot, framework); var packageX = new SimpleTestPackageContext("packageX", "1.0.0"); packageX.Files.Clear(); packageX.AddFile($"lib/net5.0/{assemblyName}{assemblyExtension}"); foreach (string assetFile in assetFileList) { packageX.AddFile($"lib/net5.0/{assetFile}"); } await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageX); projectA.AddPackageToAllFrameworks(packageX); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); projectA.Sources = sources; projectA.FallbackFolders = new List <string>(); projectA.FallbackFolders.Add(pathContext.FallbackFolder); projectA.GlobalPackagesFolder = pathContext.UserPackagesFolder; var logger = new TestLogger(); var request = new TestRestoreRequest(projectA.PackageSpec, projectA.Sources, pathContext.UserPackagesFolder, logger) { LockFilePath = projectA.AssetsFileOutputPath }; // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Asert Assert.True(result.Success); var assetsFile = projectA.AssetsFile; Assert.NotNull(assetsFile); var targets = assetsFile.GetTarget(NuGetFramework.Parse(framework), null); var lib = targets.Libraries.Single(); var compileAssemblies = lib.CompileTimeAssemblies; var runtimeAssemblies = lib.RuntimeAssemblies; // Compile, "related" property is applied. AssertRelatedProperty(compileAssemblies, $"lib/net5.0/{assemblyName}{assemblyExtension}", expectedRelatedProperty); // Runtime, "related" property is applied. AssertRelatedProperty(runtimeAssemblies, $"lib/net5.0/{assemblyName}{assemblyExtension}", expectedRelatedProperty); } }
public async Task DotnetRestore_LockedMode_NewProjectOutOfBox() { using (var pathContext = new SimpleTestPathContext()) { // Set up solution, and project var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var projFramework = FrameworkConstants.CommonFrameworks.Net462.GetShortFolderName(); var projectA = SimpleTestProjectContext.CreateNETCore( "a", pathContext.SolutionRoot, NuGetFramework.Parse(projFramework)); var runtimeidentifiers = new List <string>() { "win7-x64", "win-x86", "win" }; projectA.Properties.Add("RuntimeIdentifiers", string.Join(";", runtimeidentifiers)); projectA.Properties.Add("RestorePackagesWithLockFile", "true"); //Setup packages and feed var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/netcoreapp2.0/x.dll"); packageX.AddFile("ref/netcoreapp2.0/x.dll"); packageX.AddFile("lib/net461/x.dll"); packageX.AddFile("ref/net461/x.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX); //add the packe to the project projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); solution.Save(); projectA.Save(); // Act var args = $" --source \"{pathContext.PackageSource}\" "; var projdir = Path.GetDirectoryName(projectA.ProjectPath); var projfilename = Path.GetFileNameWithoutExtension(projectA.ProjectName); _msbuildFixture.RestoreProject(projdir, projfilename, args); Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); //Now set it to locked mode projectA.Properties.Add("RestoreLockedMode", "true"); projectA.Save(); //Act //Run the restore and it should still properly restore. //Assert within RestoreProject piece _msbuildFixture.RestoreProject(projdir, projfilename, args); Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); } }
public async Task RelatedProperty_TransitivePackageReferenceWithMultipleAssets_RelatedPropertyAppliedOnCompileRuntimeEmbedOnly() { // Arrange using (var pathContext = new SimpleTestPathContext()) { var framework = "net5.0"; // A -> packageX -> packageY var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK( "A", pathContext.SolutionRoot, framework); var packageX = new SimpleTestPackageContext("packageX", "1.0.0"); packageX.Files.Clear(); packageX.AddFile($"lib/net5.0/X.dll"); var packageY = new SimpleTestPackageContext("packageY", "1.0.0"); packageY.Files.Clear(); // Compile packageY.AddFile("ref/net5.0/Y.dll"); packageY.AddFile("ref/net5.0/Y.xml"); // Runtime packageY.AddFile("lib/net5.0/Y.dll"); packageY.AddFile("lib/net5.0/Y.xml"); // Embed packageY.AddFile("embed/net5.0/Y.dll"); packageY.AddFile("embed/net5.0/Y.xml"); // Resources packageY.AddFile("lib/net5.0/en-US/Y.resources.dll"); packageY.AddFile("lib/net5.0/en-US/Y.resources.xml"); packageX.Dependencies.Add(packageY); await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageX, packageY); projectA.AddPackageToAllFrameworks(packageX); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); projectA.Sources = sources; projectA.FallbackFolders = new List <string>(); projectA.FallbackFolders.Add(pathContext.FallbackFolder); projectA.GlobalPackagesFolder = pathContext.UserPackagesFolder; var logger = new TestLogger(); var request = new TestRestoreRequest(projectA.PackageSpec, projectA.Sources, pathContext.UserPackagesFolder, logger) { LockFilePath = projectA.AssetsFileOutputPath }; // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Asert Assert.True(result.Success); var assetsFile = projectA.AssetsFile; Assert.NotNull(assetsFile); var targets = assetsFile.GetTarget(NuGetFramework.Parse(framework), null); var libX = targets.Libraries.Single(i => i.Name.Equals("packageX")); var runtimeAssembliesX = libX.RuntimeAssemblies; AssertRelatedProperty(runtimeAssembliesX, $"lib/net5.0/X.dll", null); var libY = targets.Libraries.Single(i => i.Name.Equals("packageY")); // Compile, "related" property is applied. var compileAssembliesY = libY.CompileTimeAssemblies; AssertRelatedProperty(compileAssembliesY, $"ref/net5.0/Y.dll", ".xml"); // Runtime, "related" property is applied. var runtimeAssembliesY = libY.RuntimeAssemblies; AssertRelatedProperty(runtimeAssembliesY, $"lib/net5.0/Y.dll", ".xml"); // Embed, "related" property is applied. var embedAssembliesY = libY.EmbedAssemblies; AssertRelatedProperty(embedAssembliesY, $"embed/net5.0/Y.dll", ".xml"); // Resources, "related" property is NOT applied. var resourceAssembliesY = libY.ResourceAssemblies; AssertRelatedProperty(resourceAssembliesY, "lib/net5.0/en-US/Y.resources.dll", null); } }
public async Task RelatedProperty_TopLevelPackageWithMultipleAssetsMultipleTFMs_RelatedPropertyAppliedOnCompileRuntimeEmbedOnly() { // Arrange using (var pathContext = new SimpleTestPathContext()) { var frameworks = new string[] { "net5.0", "net6.0" }; // A -> packaegX var projectA = SimpleTestProjectContext.CreateNETCoreWithSDK( "A", pathContext.SolutionRoot, frameworks); var packageX = new SimpleTestPackageContext("packageX", "1.0.0"); packageX.Files.Clear(); // Compile packageX.AddFile("ref/net5.0/X.dll"); packageX.AddFile("ref/net5.0/X.xml"); packageX.AddFile("ref/net6.0/X.dll"); packageX.AddFile("ref/net6.0/X.pdb"); // Runtime packageX.AddFile("lib/net5.0/X.dll"); packageX.AddFile("lib/net5.0/X.xml"); packageX.AddFile("lib/net6.0/X.dll"); packageX.AddFile("lib/net6.0/X.pdb"); // Embed packageX.AddFile("embed/net5.0/X.dll"); packageX.AddFile("embed/net5.0/X.xml"); packageX.AddFile("embed/net6.0/X.dll"); packageX.AddFile("embed/net6.0/X.pdb"); // Resources packageX.AddFile("lib/net5.0/en-US/X.resources.dll"); packageX.AddFile("lib/net5.0/en-US/X.resources.xml"); packageX.AddFile("lib/net6.0/en-US/X.resources.dll"); packageX.AddFile("lib/net6.0/en-US/X.resources.pdb"); await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageX); projectA.AddPackageToAllFrameworks(packageX); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); projectA.Sources = sources; projectA.FallbackFolders = new List <string>(); projectA.FallbackFolders.Add(pathContext.FallbackFolder); projectA.GlobalPackagesFolder = pathContext.UserPackagesFolder; var logger = new TestLogger(); var request = new TestRestoreRequest(projectA.PackageSpec, projectA.Sources, pathContext.UserPackagesFolder, logger) { LockFilePath = projectA.AssetsFileOutputPath }; // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Asert Assert.True(result.Success); var assetsFile = projectA.AssetsFile; Assert.NotNull(assetsFile); var targetsNet5 = assetsFile.GetTarget(NuGetFramework.Parse("net5.0"), null); var libNet5 = targetsNet5.Libraries.Single(); var targetsNet6 = assetsFile.GetTarget(NuGetFramework.Parse("net6.0"), null); var libNet6 = targetsNet6.Libraries.Single(); // Compile, "related" property is applied. var compileAssembliesNet5 = libNet5.CompileTimeAssemblies; AssertRelatedProperty(compileAssembliesNet5, "ref/net5.0/X.dll", ".xml"); var compileAssembliesNet6 = libNet6.CompileTimeAssemblies; AssertRelatedProperty(compileAssembliesNet6, "ref/net6.0/X.dll", ".pdb"); // Runtime, "related" property is applied. var runtimeAssembliesNet5 = libNet5.RuntimeAssemblies; AssertRelatedProperty(runtimeAssembliesNet5, "lib/net5.0/X.dll", ".xml"); var runtimeAssembliesNet6 = libNet6.RuntimeAssemblies; AssertRelatedProperty(runtimeAssembliesNet6, "lib/net6.0/X.dll", ".pdb"); // Embed, "related" property is applied. var embedAssembliesNet5 = libNet5.EmbedAssemblies; AssertRelatedProperty(embedAssembliesNet5, "embed/net5.0/X.dll", ".xml"); var embedAssembliesNet6 = libNet6.EmbedAssemblies; AssertRelatedProperty(embedAssembliesNet6, "embed/net6.0/X.dll", ".pdb"); // Resources, "related" property is NOT applied. var resourceAssembliesNet5 = libNet5.ResourceAssemblies; AssertRelatedProperty(resourceAssembliesNet5, "lib/net5.0/en-US/X.resources.dll", null); var resourceAssembliesNet6 = libNet6.ResourceAssemblies; AssertRelatedProperty(resourceAssembliesNet6, "lib/net6.0/en-US/X.resources.dll", null); } }
public async Task RestoreSemVer_RestorePackageFloatOnReleaseLabel() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0-alpha.1.*"" } } } }"; using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new RestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var packages = new List <SimpleTestPackageContext>(); var package1 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.10.1" }; package1.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package1); var package2 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.11.1" }; package2.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package2); var package3 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.9.2" }; package3.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package3); var package4 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1" }; package4.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package4); var package5 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-beta.1.99" }; package5.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package5); var package6 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.2.99" }; package6.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package6); var package7 = new SimpleTestPackageContext("packageA") { Version = "1.0.0-alpha.1.2+skip" }; package7.AddFile("lib/netstandard1.5/a.dll"); packages.Add(package7); SimpleTestPackageUtility.CreatePackages(packages, packageSource.FullName); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), null) .Libraries .Single(library => library.Name == "packageA"); var compile = targetLib.CompileTimeAssemblies.Single(); // Assert Assert.True(result.Success); Assert.Equal("lib/netstandard1.5/a.dll", compile.Path); Assert.Equal("1.0.0-alpha.1.11.1", targetLib.Version.ToNormalizedString()); } }
public async Task MsbuildRestore_WithCPPCliVcxproj_WithNativeAndManagedTransitiveDependency_Succeeds() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set-up packages // Managed 1.0.0 -> Managed.Child 1.0.0 // Native 1.0.0 -> Native.Child 1.0. var packageNativeChild = new SimpleTestPackageContext("native.child", "1.0.0"); packageNativeChild.AddFile("build/native/native.child.targets"); packageNativeChild.AddFile("lib/native/native.child.dll"); var packageNative = new SimpleTestPackageContext("native", "1.0.0"); packageNative.AddFile("build/native/native.targets"); packageNative.AddFile("lib/native/native.dll"); packageNative.PerFrameworkDependencies.Add(FrameworkConstants.CommonFrameworks.Native, new List <SimpleTestPackageContext> { packageNativeChild }); var packageManagedChild = new SimpleTestPackageContext("managed.child", "1.0.0"); packageManagedChild.AddFile("build/net5.0/managed.child.targets"); packageManagedChild.AddFile("lib/net5.0/managed.child.dll"); var packageManaged = new SimpleTestPackageContext("managed", "1.0.0"); packageManaged.AddFile("build/net5.0/managed.targets"); packageManaged.AddFile("lib/net5.0/managed.dll"); packageManaged.PerFrameworkDependencies.Add(FrameworkConstants.CommonFrameworks.Net50, new List <SimpleTestPackageContext> { packageManagedChild }); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, packageNative, packageNativeChild, packageManaged, packageManagedChild); // Set up project var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var framework = NuGetFramework.Parse("net5.0-windows7.0"); var projectA = SimpleTestProjectContext.CreateNETCore("projectName", pathContext.SolutionRoot, framework); projectA.Properties.Add("CLRSupport", "NetCore"); //update path to vcxproj projectA.ProjectPath = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), projectA.ProjectName + ".vcxproj"); projectA.AddPackageToAllFrameworks(packageNative); projectA.AddPackageToAllFrameworks(packageManaged); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); // Act var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore {pathContext.SolutionRoot}"); // Assert result.Success.Should().BeTrue(because: result.AllOutput); File.Exists(projectA.AssetsFileOutputPath).Should().BeTrue(because: result.AllOutput); File.Exists(projectA.TargetsOutput).Should().BeTrue(because: result.AllOutput); File.Exists(projectA.PropsOutput).Should().BeTrue(because: result.AllOutput); var targetsSection = projectA.AssetsFile.Targets.First(e => string.IsNullOrEmpty(e.RuntimeIdentifier)); targetsSection.Libraries.Should().Contain(e => e.Name.Equals("native"), because: string.Join(",", targetsSection.Libraries)); targetsSection.Libraries.Should().Contain(e => e.Name.Equals("native.child"), because: string.Join(",", targetsSection.Libraries)); targetsSection.Libraries.Should().Contain(e => e.Name.Equals("managed"), because: string.Join(",", targetsSection.Libraries)); targetsSection.Libraries.Should().Contain(e => e.Name.Equals("managed.child"), because: string.Join(",", targetsSection.Libraries)); var nativeChild = targetsSection.Libraries.First(e => e.Name.Equals("native.child")); nativeChild.CompileTimeAssemblies.Should().Contain("lib/native/native.child.dll"); nativeChild.Build.Should().Contain("build/native/native.child.targets"); } }
public async Task RestoreCommand_VerifyRuntimeSpecificAssetsAreNotIncludedForCompile_RuntimeAndRef() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } }, ""runtimes"": { ""win7-x64"": {} } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var packageAContext = new SimpleTestPackageContext("packageA"); packageAContext.AddFile("ref/netstandard1.5/a.dll"); packageAContext.AddFile("runtimes/win7-x64/lib/netstandard1.5/a.dll"); SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), "win7-x64") .Libraries .Single(library => library.Name == "packageA"); // Assert Assert.True(result.Success); Assert.Equal("ref/netstandard1.5/a.dll", targetLib.CompileTimeAssemblies.Single()); Assert.Equal("runtimes/win7-x64/lib/netstandard1.5/a.dll", targetLib.RuntimeAssemblies.Single()); } }
public async Task RestoreTargets_RestoreWithRuntimesAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandardapp1.5"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; request.RequestedRuntimes.Add("win7-x86"); var packageA = new SimpleTestPackageContext() { Id = "packageA" }; packageA.AddFile("lib/netstandard1.5/a.dll"); packageA.AddFile("native/a.dll"); packageA.AddFile("runtimes/unix/native/a.dll"); packageA.AddFile("runtimes/unix/lib/netstandard1.5/a.dll"); packageA.AddFile("runtimes/win7/lib/netstandard1.5/a.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.5/a.dll"); packageA.AddFile("runtimes/win7-x86/lib/netstandard1.5/en-us/a.resources.dll"); await SimpleTestPackageUtility.CreatePackagesAsync(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); var format = new LockFileFormat(); var lockFile = format.Read(request.LockFilePath); var targetLib = lockFile.Targets.Single(graph => graph.RuntimeIdentifier == null).Libraries.Single(); var ridTargetLib = lockFile.Targets.Single(graph => graph.RuntimeIdentifier != null).Libraries.Single(); // Assert Assert.True(result.Success); Assert.Equal(5, targetLib.RuntimeTargets.Count); Assert.Equal("runtimes/unix/lib/netstandard1.5/a.dll", targetLib.RuntimeTargets[0].Path); Assert.Equal("runtime", targetLib.RuntimeTargets[0].Properties["assetType"]); Assert.Equal("unix", targetLib.RuntimeTargets[0].Properties["rid"]); Assert.Equal("runtimes/win7-x86/lib/netstandard1.5/en-us/a.resources.dll", targetLib.RuntimeTargets[3].Path); Assert.Equal("resource", targetLib.RuntimeTargets[3].Properties["assetType"]); Assert.Equal("win7-x86", targetLib.RuntimeTargets[3].Properties["rid"]); Assert.Equal("runtimes/unix/native/a.dll", targetLib.RuntimeTargets[1].Path); Assert.Equal("native", targetLib.RuntimeTargets[1].Properties["assetType"]); Assert.Equal("unix", targetLib.RuntimeTargets[1].Properties["rid"]); // This section does not exist for RID graphs Assert.Equal(0, ridTargetLib.RuntimeTargets.Count); } }
public async Task RestoreTargets_RestoreWithNoRuntimes() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageA = new SimpleTestPackageContext() { Id = "packageA" }; packageA.AddFile("lib/a.dll"); packageA.AddFile("lib/netstandard1.5/a.dll"); packageA.AddFile("lib/netstandard1.5/en-us/a.resource.dll"); packageA.AddFile("native/a.dll"); packageA.AddFile("ref/netstandard1.5/a.dll"); packageA.AddFile("contentFiles/any/any/a.dll"); SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.Targets.Single(graph => graph.RuntimeIdentifier == null).Libraries.Single(); // Assert Assert.True(result.Success); Assert.Equal(1, lockFile.Libraries.Count); Assert.Equal(0, targetLib.RuntimeTargets.Count); } }
public async Task RestoreSemVer_RestorePackageWithMetadata_DifferentMetadataDoesNotMatterAsync() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.5"": { ""dependencies"": { ""packageA"": ""1.0.0+1"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger) { LockFilePath = Path.Combine(project1.FullName, "project.lock.json") }; var packageAContext = new SimpleTestPackageContext("packageA") { Version = "1.0.0+B" }; packageAContext.AddFile("lib/netstandard1.5/a.dll"); await SimpleTestPackageUtility.CreateFullPackageAsync(packageSource.FullName, packageAContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; await result.CommitAsync(logger, CancellationToken.None); var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), null) .Libraries .Single(library => library.Name == "packageA"); var compile = targetLib.CompileTimeAssemblies.Single(); // Assert Assert.True(result.Success); Assert.Equal("lib/netstandard1.5/a.dll", compile.Path); Assert.Equal("1.0.0", targetLib.Version.ToNormalizedString()); } }
public async Task DotnetToolTests_ToolRestoreWithRuntimeIdentiferGraphPath_SucceedsAsync() { using (var pathContext = new SimpleTestPathContext()) { string testDirectory = pathContext.WorkingDirectory; var tfm = "netcoreapp2.0"; var projectName = "ToolRestoreProject"; var workingDirectory = Path.Combine(testDirectory, projectName); var packageSource = Path.Combine(testDirectory, "packageSource"); var rid = "win-x64"; var packageRid = "win"; var packageName = string.Join("ToolPackage-", tfm, rid); var packageVersion = NuGetVersion.Parse("1.0.0"); var packages = new List <PackageIdentity>() { new PackageIdentity(packageName, packageVersion) }; var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion); package.Files.Clear(); package.AddFile($"tools/{tfm}/{packageRid}/a.dll"); package.AddFile($"tools/{tfm}/{packageRid}/Settings.json"); package.PackageType = PackageType.DotnetTool; package.UseDefaultRuntimeAssemblies = false; package.PackageTypes.Add(PackageType.DotnetTool); await SimpleTestPackageUtility.CreatePackagesAsync(packageSource, package); _msbuildFixture.CreateDotnetToolProject(testDirectory, projectName, tfm, rid, packageSource, packages); // set up rid graph var ridGraphPath = Path.Combine(testDirectory, "runtime.json"); File.WriteAllBytes(ridGraphPath, GetTestUtilityResource("runtime.json")); using (var stream = File.Open(Path.Combine(workingDirectory, projectName + ".csproj"), FileMode.Open, FileAccess.ReadWrite)) { var xml = XDocument.Load(stream); ProjectFileUtils.AddProperty( xml, "RuntimeIdentifierGraphPath", ridGraphPath); ProjectFileUtils.WriteXmlToFile(xml, stream); } // Act var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty); // Assert Assert.True(result.ExitCode == 0, result.AllOutput); // Verify the assets file var lockFile = LockFileUtilities.GetLockFile(Path.Combine(testDirectory, projectName, "project.assets.json"), NullLogger.Instance); Assert.NotNull(lockFile); Assert.Equal(2, lockFile.Targets.Count); var ridTargets = lockFile.Targets.Where(e => e.RuntimeIdentifier != null ? e.RuntimeIdentifier.Equals(rid, StringComparison.CurrentCultureIgnoreCase) : false); Assert.Equal(1, ridTargets.Count()); var toolsAssemblies = ridTargets.First().Libraries.First().ToolsAssemblies; Assert.Equal(2, toolsAssemblies.Count); Assert.True(toolsAssemblies.Contains($"tools/{tfm}/{packageRid}/a.dll")); Assert.True(toolsAssemblies.Contains($"tools/{tfm}/{packageRid}/Settings.json")); } }
public async Task CompatilibityChecker_PackageCompatibility_VerifyNoAvailableFrameworks() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""netstandard1.0"": { ""dependencies"": { ""packageA"": { ""version"": ""1.0.0"" } } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); var logger = new TestLogger(); var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger); request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json"); var packageA = new SimpleTestPackageContext("packageA"); packageA.AddFile("ref/a.dll"); SimpleTestPackageUtility.CreatePackages(packageSource.FullName, packageA); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); await result.CommitAsync(logger, CancellationToken.None); // Assert Assert.False(result.Success, logger.ShowErrors()); // Verify both libraries were installed Assert.Equal(1, result.LockFile.Libraries.Count); var issue = result.CompatibilityCheckResults.SelectMany(check => check.Issues).Single(); Assert.Equal(@"Package packageA 1.0.0 is not compatible with netstandard1.0 (.NETStandard,Version=v1.0). Package packageA 1.0.0 does not support any target frameworks.".Replace("\n", Environment.NewLine), issue.Format()); } }
public async Task Restore_PackageNamespace_Fails() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages"); var externalRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ExternalRepository"); Directory.CreateDirectory(externalRepositoryPath); var contosoRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ContosoRepository"); Directory.CreateDirectory(contosoRepositoryPath); var configPath = Path.Combine(pathContext.WorkingDirectory, "nuget.config"); SettingsTestUtils.CreateConfigurationFile(configPath, $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> <!--To inherit the global NuGet package sources remove the <clear/> line below --> <clear /> <add key=""ExternalRepository"" value=""{externalRepositoryPath}"" /> <add key=""ContosoRepository"" value=""{contosoRepositoryPath}"" /> </packageSources> <packageNamespaces> <packageSource key=""ExternalRepository""> <namespace id=""External.*"" /> <namespace id=""Others.*"" /> </packageSource> <packageSource key=""ContosoRepository""> <namespace id=""Contoso.*"" /> <!--Contoso.A package doesn't exist Contoso repository, so restore should fail--> <namespace id=""Test.*"" /> </packageSource> </packageNamespaces> </configuration>"); var ExternalA = new SimpleTestPackageContext() { Id = "Contoso.A", // Initial version had package id conflict with Contoso repository Version = "1.0.0" }; ExternalA.AddFile("lib/net461/externalA.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalA); var ExternalB = new SimpleTestPackageContext() { Id = "External.B", // name conflict resolved. Version = "2.0.0" }; ExternalB.AddFile("lib/net461/externalB.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalB); Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""Contoso.A"" version=""1.0.0"" targetFramework=""net461"" /> <package id=""External.B"" version=""2.0.0"" targetFramework=""net461"" /> </packages>"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); // Act var result = RunRestore(pathContext, _failureExitCode); // Assert Assert.Contains("Unable to find version '1.0.0' of package 'Contoso.A'", result.Errors); } }
public async Task Restore_LegacyPackagesConfig_WithNuGetLockFileLockedMode() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/x.dll"); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile("lib/net461/y.dll"); Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""x"" version=""1.0.0"" targetFramework=""net461"" /> </packages>"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); // Restore to set up lock file var result = RunRestore(pathContext, _successExitCode, "-UseLockFile"); Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); // Change packages to cause lock file difference Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""y"" version=""1.0.0"" targetFramework=""net461"" /> </packages>"); // Act result = RunRestore(pathContext, _failureExitCode, "-UseLockFile", "-LockedMode"); // Assert Assert.Contains("NU1004:", result.Errors); } }
public async Task Restore_WithLockedModeAndNoObjFolder_RestoreFailsAndWritesOutRestoreResultFiles() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/a.dll"); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile("lib/net461/y.dll"); projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); var result = RunRestore(pathContext, _successExitCode, "-UseLockFile"); Assert.True(result.Success); Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); var originalPackagesLockFileWriteTime = new FileInfo(projectA.NuGetLockFileOutputPath).LastWriteTimeUtc; projectA.AddPackageToAllFrameworks(packageY); projectA.Save(); // Remove old obj folders. Directory.Delete(Path.GetDirectoryName(projectA.AssetsFileOutputPath), recursive: true); // Act result = RunRestore(pathContext, _failureExitCode, "-LockedMode"); // Assert Assert.Contains("NU1004:", result.Errors); var logCodes = projectA.AssetsFile.LogMessages.Select(e => e.Code); Assert.Contains(NuGetLogCode.NU1004, logCodes); var ridlessMainTarget = projectA.AssetsFile.Targets.FirstOrDefault(e => string.IsNullOrEmpty(e.RuntimeIdentifier)); Assert.Equal(net461, ridlessMainTarget.TargetFramework); Assert.True(File.Exists(projectA.PropsOutput)); Assert.True(File.Exists(projectA.TargetsOutput)); Assert.True(File.Exists(projectA.CacheFileOutputPath)); var packagesLockFileWriteTime = new FileInfo(projectA.NuGetLockFileOutputPath).LastWriteTimeUtc; packagesLockFileWriteTime.Should().Be(originalPackagesLockFileWriteTime, because: "Locked mode must not overwrite the lock file"); } }
public async Task Restore_LegacyPackageReference_WithNuGetLockFilePath() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = "net461"; var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, NuGetFramework.Parse(net461)); var projectB = SimpleTestProjectContext.CreateLegacyPackageReference( "b", pathContext.SolutionRoot, NuGetFramework.Parse(net461)); // set up packages var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile($"lib/{0}/x.dll", net461); var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageY.Files.Clear(); packageY.AddFile($"lib/{0}/y.dll", net461); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, PackageSaveMode.Defaultv3, packageX, packageY); // set up projects and solution projectB.AddPackageToAllFrameworks(packageY); projectA.Properties.Add("RestorePackagesWithLockFile", "true"); var packagesLockFilePath = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "packages.custom.lock.json"); projectA.Properties.Add("NuGetLockFilePath", packagesLockFilePath); projectA.AddProjectToAllFrameworks(projectB); projectA.AddPackageToAllFrameworks(packageX); solution.Projects.Add(projectA); solution.Projects.Add(projectB); solution.Create(pathContext.SolutionRoot); // Act var result = RunRestore(pathContext); // Assert Assert.True(File.Exists(projectA.NuGetLockFileOutputPath)); Assert.Equal(packagesLockFilePath, projectA.NuGetLockFileOutputPath); var lockFile = PackagesLockFileFormat.Read(projectA.NuGetLockFileOutputPath); Assert.Equal(4, lockFile.Targets.Count); var targets = lockFile.Targets.Where(t => t.Dependencies.Count > 0).ToList(); Assert.Equal(1, targets.Count); Assert.Equal(".NETFramework,Version=v4.6.1", targets[0].Name); Assert.Equal(3, targets[0].Dependencies.Count); Assert.Equal("x", targets[0].Dependencies[0].Id); Assert.Equal(PackageDependencyType.Direct, targets[0].Dependencies[0].Type); Assert.Equal("y", targets[0].Dependencies[1].Id); Assert.Equal(PackageDependencyType.Transitive, targets[0].Dependencies[1].Type); Assert.Equal("b", targets[0].Dependencies[2].Id); Assert.Equal(PackageDependencyType.Project, targets[0].Dependencies[2].Type); } }
public async Task Restore_PackageNamespace_Succeed() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = SimpleTestProjectContext.CreateLegacyPackageReference( "a", pathContext.SolutionRoot, net461); var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages"); var externalRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ExternalRepository"); Directory.CreateDirectory(externalRepositoryPath); var contosoRepositoryPath = Path.Combine(pathContext.SolutionRoot, "ContosoRepository"); Directory.CreateDirectory(contosoRepositoryPath); var configPath = Path.Combine(pathContext.WorkingDirectory, "nuget.config"); SettingsTestUtils.CreateConfigurationFile(configPath, $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> <!--To inherit the global NuGet package sources remove the <clear/> line below --> <clear /> <add key=""ExternalRepository"" value=""{externalRepositoryPath}"" /> <add key=""ContosoRepository"" value=""{contosoRepositoryPath}"" /> </packageSources> <packageNamespaces> <packageSource key=""externalRepository""> <namespace id=""External.*"" /> <namespace id=""Others.*"" /> </packageSource> <packageSource key=""contosoRepository""> <namespace id=""Contoso.*"" /> <namespace id=""Test.*"" /> </packageSource> </packageNamespaces> </configuration>"); var ContosoReal = new SimpleTestPackageContext() { Id = "Contoso.A", Version = "1.0.0" }; ContosoReal.AddFile("lib/net461/contosoA.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( contosoRepositoryPath, PackageSaveMode.Defaultv3, ContosoReal); var ExternalA = new SimpleTestPackageContext() { Id = "Contoso.A", // Initial version had package id conflict with Contoso repository Version = "1.0.0" }; ExternalA.AddFile("lib/net461/externalA.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalA); var ExternalB = new SimpleTestPackageContext() { Id = "External.B", // name conflict resolved. Version = "2.0.0" }; ExternalB.AddFile("lib/net461/externalB.dll"); await SimpleTestPackageUtility.CreateFolderFeedV3Async( externalRepositoryPath, PackageSaveMode.Defaultv3, ExternalB); Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config", @"<packages> <package id=""Contoso.A"" version=""1.0.0"" targetFramework=""net461"" /> <package id=""External.B"" version=""2.0.0"" targetFramework=""net461"" /> </packages>"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); // Act var result = RunRestore(pathContext, _successExitCode); // Assert var contosoRestorePath = Path.Combine(projectAPackages, ContosoReal.ToString(), ContosoReal.ToString() + ".nupkg"); using (var nupkgReader = new PackageArchiveReader(contosoRestorePath)) { var allFiles = nupkgReader.GetFiles().ToList(); // Assert correct Contoso package from Contoso repository was restored. Assert.Contains("lib/net461/contosoA.dll", allFiles); } var externalRestorePath = Path.Combine(projectAPackages, ExternalB.ToString(), ExternalB.ToString() + ".nupkg"); Assert.True(File.Exists(externalRestorePath)); } }
public async Task MsbuildRestore_RequiresSolutionDirAsync() { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = new SimpleTestProjectContext( "a", ProjectStyle.PackagesConfig, pathContext.SolutionRoot); projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461)); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); packageX.AddFile("lib/net461/a.dll"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); using (var writer = new StreamWriter(Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "packages.config"))) { writer.Write( @"<packages> <package id=""x"" version=""1.0.0"" targetFramework=""net461"" /> </packages>"); } // SimpleTestPathContext adds a NuGet.Config with a repositoryPath, // so we go ahead and remove that config before running MSBuild. var configPath = Path.Combine(Path.GetDirectoryName(pathContext.SolutionRoot), "NuGet.Config"); var doc = XDocument.Parse(File.ReadAllText(configPath)); var root = doc.Element(XName.Get("configuration")); var config = root.Element(XName.Get("config")); foreach (var item in config.Elements(XName.Get("add")).Where(e => ((string)e.Attribute("key")).Equals("repositoryPath", StringComparison.OrdinalIgnoreCase)).ToArray()) { item.Remove(); } File.Delete(configPath); File.WriteAllText(configPath, doc.ToString()); await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, packageX); // Act var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore {projectA.ProjectPath} /p:RestorePackagesConfig=true", ignoreExitCode: true); // Assert Assert.True(result.ExitCode == 1, result.AllOutput); Assert.Contains("No solution found", result.AllOutput); } }
public async Task RestoreBuildTargetsAndProps_VerifyPropsAndTargetsGenerated() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec = GetProject("projectA", "net462", "netstandard1.6"); spec.RestoreMetadata.CrossTargeting = true; spec.Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("x", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); // Create fake projects, the real data is in the specs var projects = CreateProjectsFromSpecs(pathContext, spec); // Create dg file var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec); dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.AddFile("build/x.targets"); packageX.AddFile("build/x.props"); packageX.AddFile("contentFiles/any/any/_._"); SimpleTestPackageUtility.CreatePackages(pathContext.PackageSource, packageX); var project = projects[0]; // Act var summaries = await RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); // Assert Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); var targetsXML = XDocument.Parse(File.ReadAllText(project.TargetsOutput)); var targetItemGroups = targetsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList(); var propsXML = XDocument.Parse(File.ReadAllText(project.PropsOutput)); var propsItemGroups = propsXML.Root.Elements().Where(e => e.Name.LocalName == "ImportGroup").ToList(); Assert.Equal("'$(TargetFramework)' == 'net462' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(TargetFramework)' == 'netstandard1.6' AND '$(ExcludeRestorePackageImports)' != 'true'", targetItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(TargetFramework)' == 'net462' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[0].Attribute(XName.Get("Condition")).Value.Trim()); Assert.Equal("'$(TargetFramework)' == 'netstandard1.6' AND '$(ExcludeRestorePackageImports)' != 'true'", propsItemGroups[1].Attribute(XName.Get("Condition")).Value.Trim()); } }
public async Task MsbuildRestore_StaticGraphEvaluation_CleanupAssetsForUnsupportedProjectsAsync(bool cleanupAssetsForUnsupportedProjects) { // Arrange using (var pathContext = new SimpleTestPathContext()) { // Set up solution, project, and packages var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot); var net461 = NuGetFramework.Parse("net461"); var projectA = new SimpleTestProjectContext( "a", ProjectStyle.PackageReference, pathContext.SolutionRoot); projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461)); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.Files.Clear(); projectA.AddPackageToAllFrameworks(packageX); packageX.AddFile("lib/net461/a.dll"); solution.Projects.Add(projectA); solution.Create(pathContext.SolutionRoot); var configAPath = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), "NuGet.Config"); var configText = $@"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <packageSources> <add key=""LocalSource"" value=""{pathContext.PackageSource}"" /> </packageSources> </configuration>"; using (var writer = new StreamWriter(configAPath)) { writer.Write(configText); } await SimpleTestPackageUtility.CreateFolderFeedV3Async( pathContext.PackageSource, packageX); // Restore the project with a PackageReference which generates assets var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore /p:RestoreUseStaticGraphEvaluation=true /p:RestoreCleanupAssetsForUnsupportedProjects={cleanupAssetsForUnsupportedProjects} {projectA.ProjectPath}", ignoreExitCode: true); Assert.True(result.ExitCode == 0, result.AllOutput); var assets = new[] { projectA.AssetsFileOutputPath, projectA.PropsOutput, projectA.TargetsOutput, projectA.CacheFileOutputPath, }; foreach (var asset in assets) { Assert.True(File.Exists(asset), result.AllOutput); } // Recreate the project with Unknown project style and no PackageReferences projectA = new SimpleTestProjectContext( "a", ProjectStyle.Unknown, pathContext.SolutionRoot); projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461)); projectA.Save(); // Restore the project with a PackageReference which generates assets result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore /p:RestoreUseStaticGraphEvaluation=true /p:RestoreCleanupAssetsForUnsupportedProjects={cleanupAssetsForUnsupportedProjects} {projectA.ProjectPath}", ignoreExitCode: true); // Assert Assert.True(result.ExitCode == 0, result.AllOutput); foreach (var asset in assets) { if (cleanupAssetsForUnsupportedProjects) { Assert.False(File.Exists(asset), result.AllOutput); } else { Assert.True(File.Exists(asset), result.AllOutput); } } } }
public async Task RestoreBuildTargetsAndProps_VerifyRestoreChange() { // Arrange using (var cacheContext = new SourceCacheContext()) using (var pathContext = new SimpleTestPathContext()) { var logger = new TestLogger(); var sources = new List <PackageSource>(); sources.Add(new PackageSource(pathContext.PackageSource)); var spec = GetProject("projectA", "net462", "netstandard1.6"); spec.RestoreMetadata.CrossTargeting = true; spec.Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("x", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); // Create fake projects, the real data is in the specs var projects = CreateProjectsFromSpecs(pathContext, spec); // Create dg file var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec); dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName); dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg")); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; var packageY = new SimpleTestPackageContext() { Id = "y", Version = "1.0.0" }; packageX.AddFile("build/x.targets"); packageX.AddFile("build/x.props"); packageX.AddFile("contentFiles/any/any/_._"); packageY.AddFile("build/y.targets"); packageY.AddFile("build/y.props"); packageY.AddFile("contentFiles/any/any/_._"); SimpleTestPackageUtility.CreatePackages(pathContext.PackageSource, packageX, packageY); var project = projects[0]; // First restore var summaries = await RunRestore(pathContext, logger, sources, dgFile, cacheContext); var success = summaries.All(s => s.Success); Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); // Modify spec spec.Dependencies.Add(new LibraryDependency() { LibraryRange = new LibraryRange("y", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package) }); // Act summaries = await RunRestore(pathContext, logger, sources, dgFile, cacheContext); success = summaries.All(s => s.Success); Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages)); // Verify the file was rewritten Assert.Contains("y.targets", File.ReadAllText(project.TargetsOutput)); Assert.Contains("y.props", File.ReadAllText(project.PropsOutput)); } }
public async Task RestoreRunner_BasicRestore_VerifyFailureWritesFiles() { // Arrange var sources = new List <PackageSource>(); var project1Json = @" { ""version"": ""1.0.0"", ""description"": """", ""authors"": [ ""author"" ], ""tags"": [ """" ], ""projectUrl"": """", ""licenseUrl"": """", ""frameworks"": { ""net45"": { ""dependencies"": { ""x"": ""1.0.0"" } } } }"; using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var project1 = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); packageSource.Create(); project1.Create(); sources.Add(new PackageSource(packageSource.FullName)); File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json); var specPath1 = Path.Combine(project1.FullName, "project.json"); var spec1 = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1); spec1 = spec1.EnsureRestoreMetadata(); spec1.RestoreMetadata.Sources = new List <PackageSource> { new PackageSource(packageSource.FullName) }; spec1.RestoreMetadata.PackagesPath = packagesDir.FullName; var dgFile = new DependencyGraphSpec(); dgFile.AddProject(spec1); dgFile.AddRestore("project1"); var logger = new TestLogger(); var lockPath = Path.Combine(project1.FullName, "project.assets.json"); var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList(); var packageX = new SimpleTestPackageContext() { Id = "x", Version = "1.0.0" }; packageX.AddFile("build/net45/x.targets"); var packageY = new SimpleTestPackageContext("y"); packageX.Dependencies.Add(packageY); var yPath = SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageY); SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageX); // y does not exist yPath.Delete(); var providerCache = new RestoreCommandProvidersCache(); using (var cacheContext = new SourceCacheContext()) { var restoreContext = new RestoreArgs() { CacheContext = cacheContext, DisableParallel = true, GlobalPackagesFolder = packagesDir.FullName, Sources = new List <string>() { packageSource.FullName }, Log = logger, CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(sources)), PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>() { new DependencyGraphSpecRequestProvider(providerCache, dgFile) } }; var targetsPath = Path.Combine(project1.FullName, "project1.csproj.nuget.g.targets"); var propsPath = Path.Combine(project1.FullName, "project1.nuget.props"); // Act var summaries = await RestoreRunner.RunAsync(restoreContext); var summary = summaries.Single(); var targets = TargetsUtility.GetMSBuildPackageImports(targetsPath); // Assert Assert.False(summary.Success); Assert.True(File.Exists(lockPath), lockPath); Assert.True(File.Exists(targetsPath)); Assert.False(File.Exists(propsPath)); Assert.Equal(1, targets.Count); } } }
public async Task RestoreCommand_ObservesLowercaseFlag(bool isLowercase) { // Arrange using (var workingDir = TestDirectory.Create()) { var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages")); var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource")); var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1")); packagesDir.Create(); sourceDir.Create(); projectDir.Create(); var resolver = new VersionFolderPathResolver(packagesDir.FullName, isLowercase); var sources = new List <string>(); sources.Add(sourceDir.FullName); var projectJson = @" { ""frameworks"": { ""netstandard1.0"": { ""dependencies"": { ""PackageA"": ""1.0.0-Beta"" } } } }"; File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson); var specPath = Path.Combine(projectDir.FullName, "project.json"); var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath); var logger = new TestLogger(); var request = new TestRestoreRequest( spec, sources.Select(x => Repository.Factory.GetCoreV3(x)), packagesDir.FullName, Enumerable.Empty <string>(), logger) { IsLowercasePackagesDirectory = isLowercase }; request.LockFilePath = Path.Combine(projectDir.FullName, "project.lock.json"); var packageId = "PackageA"; var packageVersion = "1.0.0-Beta"; var packageAContext = new SimpleTestPackageContext(packageId, packageVersion); packageAContext.AddFile("lib/netstandard1.0/a.dll"); SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext); // Act var command = new RestoreCommand(request); var result = await command.ExecuteAsync(); var lockFile = result.LockFile; // Assert Assert.True(result.Success); var library = lockFile .Libraries .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion); Assert.NotNull(library); Assert.Equal( PathUtility.GetPathWithForwardSlashes(resolver.GetPackageDirectory(packageId, library.Version)), library.Path); Assert.True(File.Exists(resolver.GetPackageFilePath(packageId, library.Version))); } }