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);
            }
        }
Пример #2
0
        public async Task PackagePath_NotNull()
        {
            // Prepare
            var solutionManager = Mock.Of <INuGetSolutionManagerService>();
            var uiContext       = new Mock <INuGetUIContext>();

            uiContext.Setup(x => x.SolutionManagerService)
            .Returns(solutionManager);
            var searchService = new Mock <IReconnectingNuGetSearchService>(MockBehavior.Strict);

            var packageSearchMetadata = new PackageSearchMetadataBuilder.ClonedPackageSearchMetadata()
            {
                Identity       = new PackageIdentity("NuGet.org", new NuGetVersion("1.0")),
                PrefixReserved = true,
                PackagePath    = "somesillypath",
            };

            var packageSearchMetadataContextInfo = new List <PackageSearchMetadataContextInfo>()
            {
                PackageSearchMetadataContextInfo.Create(packageSearchMetadata)
            };

            var searchResult = new SearchResultContextInfo(packageSearchMetadataContextInfo, new Dictionary <string, LoadingStatus> {
                { "Search", LoadingStatus.Loading }
            }, false);

            searchService.Setup(x =>
                                x.SearchAsync(
                                    It.IsAny <IReadOnlyCollection <IProjectContextInfo> >(),
                                    It.IsAny <IReadOnlyCollection <PackageSourceContextInfo> >(),
                                    It.IsAny <IReadOnlyCollection <string> >(),
                                    It.IsAny <string>(),
                                    It.IsAny <SearchFilter>(),
                                    It.IsAny <NuGet.VisualStudio.Internal.Contracts.ItemFilter>(),
                                    It.IsAny <bool>(),
                                    It.IsAny <CancellationToken>()))
            .Returns(new ValueTask <SearchResultContextInfo>(searchResult));

            var packageFileService = new Mock <INuGetPackageFileService>();

            uiContext.Setup(x => x.ServiceBroker)
            .Returns(Mock.Of <IServiceBroker>());

            using (var localFeedDir = TestDirectory.Create()) // local feed
            {
                // create test package
                var pkgId = new PackageIdentity("nuget.lpsm.test", new NuGetVersion(0, 0, 1));
                var pkg   = new SimpleTestPackageContext(pkgId.Id, pkgId.Version.ToNormalizedString());
                await SimpleTestPackageUtility.CreatePackagesAsync(localFeedDir.Path, pkg);

                // local test source
                var localUri    = new Uri(localFeedDir.Path, UriKind.Absolute);
                var localSource = new PackageSource(localUri.ToString(), "LocalSource");

                var sourceRepositoryProvider = TestSourceRepositoryUtility.CreateSourceRepositoryProvider(new[] { localSource });
                var repositories             = sourceRepositoryProvider.GetRepositories();

                var context = new PackageLoadContext(isSolution: false, uiContext.Object);

                var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: null);
                var loader      = await PackageItemLoader.CreateAsync(
                    Mock.Of <IServiceBroker>(),
                    context,
                    new List <PackageSourceContextInfo> {
                    PackageSourceContextInfo.Create(localSource)
                },
                    NuGet.VisualStudio.Internal.Contracts.ItemFilter.All,
                    searchService.Object,
                    packageFileService.Object,
                    TestSearchTerm);

                // Act
                await loader.LoadNextAsync(progress : null, CancellationToken.None);

                var results = loader.GetCurrent();

                // Assert
                Assert.Single(results);
                Assert.NotNull(results.First().PackagePath);
            }
        }
Пример #3
0
        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());
                }
        }
Пример #4
0
        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")));
                }
            }
        }
Пример #5
0
        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");
            }
        }
Пример #6
0
        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"));
            }
        }
Пример #7
0
        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 FindPackageByIdResource_V2V3CompareAsync()
        {
            using (var rootV3 = TestDirectory.Create())
                using (var rootV2 = TestDirectory.Create())
                {
                    // Arrange
                    var testLogger = new TestLogger();

                    var a1 = new PackageIdentity("a", NuGetVersion.Parse("1.0.0-alpha.1.2"));
                    var a2 = new PackageIdentity("a", NuGetVersion.Parse("1.0.0+server.2"));
                    var b  = new PackageIdentity("b", NuGetVersion.Parse("1.0.0.0"));

                    await SimpleTestPackageUtility.CreateFolderFeedV2Async(rootV2, a1, a2, b);

                    await SimpleTestPackageUtility.CreateFolderFeedV3Async(rootV3, a1, a2, b);

                    var resourceV2 = new LocalV2FindPackageByIdResource(new PackageSource(rootV2));
                    var resourceV3 = new LocalV3FindPackageByIdResource(new PackageSource(rootV3));

                    using (var cacheContext = new SourceCacheContext())
                    {
                        var bNonNorm = new PackageIdentity("B", NuGetVersion.Parse("1.0"));

                        // Act
                        var versionsV2 = new HashSet <NuGetVersion>(await resourceV2.GetAllVersionsAsync(
                                                                        "A",
                                                                        cacheContext,
                                                                        testLogger,
                                                                        CancellationToken.None));

                        var versionsV3 = new HashSet <NuGetVersion>(await resourceV3.GetAllVersionsAsync(
                                                                        "A",
                                                                        cacheContext,
                                                                        testLogger,
                                                                        CancellationToken.None));

                        var emptyV2 = (await resourceV2.GetAllVersionsAsync(
                                           "c",
                                           cacheContext,
                                           testLogger,
                                           CancellationToken.None))
                                      .ToList();

                        var emptyV3 = (await resourceV3.GetAllVersionsAsync("c",
                                                                            cacheContext,
                                                                            testLogger,
                                                                            CancellationToken.None))
                                      .ToList();

                        var v2Stream = new MemoryStream();
                        await resourceV2.CopyNupkgToStreamAsync(
                            bNonNorm.Id,
                            bNonNorm.Version,
                            v2Stream,
                            cacheContext,
                            testLogger,
                            CancellationToken.None);

                        var v3Stream = new MemoryStream();
                        await resourceV3.CopyNupkgToStreamAsync(
                            bNonNorm.Id,
                            bNonNorm.Version,
                            v3Stream,
                            cacheContext,
                            testLogger,
                            CancellationToken.None);

                        var depV2 = await resourceV2.GetDependencyInfoAsync(
                            bNonNorm.Id,
                            bNonNorm.Version,
                            cacheContext,
                            testLogger,
                            CancellationToken.None);

                        var depV3 = await resourceV3.GetDependencyInfoAsync(
                            bNonNorm.Id,
                            bNonNorm.Version,
                            cacheContext,
                            testLogger,
                            CancellationToken.None);

                        var depEmptyV2 = await resourceV2.GetDependencyInfoAsync(
                            bNonNorm.Id,
                            NuGetVersion.Parse("2.9"),
                            cacheContext,
                            testLogger,
                            CancellationToken.None);

                        var depEmptyV3 = await resourceV3.GetDependencyInfoAsync(
                            bNonNorm.Id,
                            NuGetVersion.Parse("2.9"),
                            cacheContext,
                            testLogger,
                            CancellationToken.None);

                        // Assert
                        Assert.True(versionsV2.SetEquals(versionsV3));
                        Assert.Equal(0, emptyV2.Count);
                        Assert.Equal(0, emptyV3.Count);
                        Assert.True(v2Stream.Length > 0);
                        Assert.True(v3Stream.Length > 0);
                        Assert.Equal(0, depV2.DependencyGroups.Count);
                        Assert.Equal(0, depV3.DependencyGroups.Count);
                        Assert.Null(depEmptyV2);
                        Assert.Null(depEmptyV3);
                    }
                }
        }
Пример #9
0
        public async Task GetInstallActionsAsync_WithProjectReferenceProject_WhenUpdatingPackage_ReturnsCorrectActions()
        {
            const string projectName        = "a";
            string       projectId          = Guid.NewGuid().ToString();
            var          projectSystemCache = new ProjectSystemCache();

            using (TestDirectory testDirectory = TestDirectory.Create())
            {
                var    packageV1 = new SimpleTestPackageContext(packageId: "b", version: "1.0.0");
                var    packageV2 = new SimpleTestPackageContext(packageV1.Id, version: "2.0.0");
                string packageSourceDirectoryPath = Path.Combine(testDirectory, "packageSource");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    packageSourceDirectoryPath,
                    PackageSaveMode.Defaultv3,
                    packageV1,
                    packageV2);

                var packageSource  = new PackageSource(packageSourceDirectoryPath);
                var packageSources = new List <PackageSource>()
                {
                    packageSource
                };

                Initialize(packageSources);

                string projectFullPath          = Path.Combine(testDirectory.Path, $"{projectName}.csproj");
                var    unconfiguredProject      = new Mock <UnconfiguredProject>();
                var    configuredProject        = new Mock <ConfiguredProject>();
                var    projectServices          = new Mock <ConfiguredProjectServices>();
                var    packageReferencesService = new Mock <IPackageReferencesService>();
                var    result = new Mock <IUnresolvedPackageReference>();

                unconfiguredProject.Setup(x => x.GetSuggestedConfiguredProjectAsync())
                .ReturnsAsync(configuredProject.Object);

                configuredProject.SetupGet(x => x.Services)
                .Returns(projectServices.Object);

                projectServices.SetupGet(x => x.PackageReferences)
                .Returns(packageReferencesService.Object);

                packageReferencesService.Setup(x => x.AddAsync(It.IsNotNull <string>(), It.IsNotNull <string>()))
                .ReturnsAsync(new AddReferenceResult <IUnresolvedPackageReference>(result.Object, added: true));

                var nuGetProjectServices = new Mock <INuGetProjectServices>();

                nuGetProjectServices.SetupGet(x => x.ScriptService)
                .Returns(Mock.Of <IProjectScriptHostService>());

                var project = new CpsPackageReferenceProject(
                    projectName: projectName,
                    projectUniqueName: projectFullPath,
                    projectFullPath: projectFullPath,
                    projectSystemCache,
                    unconfiguredProject.Object,
                    nuGetProjectServices.Object,
                    projectId);

                PackageSpec packageSpec = CreatePackageSpec(
                    project.ProjectName,
                    Path.Combine(testDirectory, "package.spec"));
                DependencyGraphSpec projectRestoreInfo = ProjectJsonTestHelpers.GetDGSpecFromPackageSpecs(packageSpec);
                projectRestoreInfo.AddProject(packageSpec);
                var projectNames = new ProjectNames(
                    fullName: projectFullPath,
                    uniqueName: projectFullPath,
                    shortName: projectName,
                    customUniqueName: projectName,
                    projectId: projectId);
                projectSystemCache.AddProjectRestoreInfo(projectNames, projectRestoreInfo, Array.Empty <IAssetsLogMessage>());

                _solutionManager.NuGetProjects.Add(project);

                string[] projectIds         = new[] { projectId };
                string[] packageSourceNames = new[] { packageSource.Name };

                await PerformOperationAsync(async (projectManager) =>
                {
                    IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync(
                        projectIds,
                        packageV1.Identity,
                        VersionConstraints.None,
                        includePrelease: true,
                        DependencyBehavior.Lowest,
                        packageSourceNames,
                        CancellationToken.None);

                    Assert.NotEmpty(actions);
                    Assert.Equal(1, actions.Count);

                    ProjectAction action = actions[0];

                    Assert.Equal(packageV1.Identity, action.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType);
                    Assert.Equal(projectId, action.ProjectId);

                    Assert.Equal(1, action.ImplicitActions.Count);

                    ImplicitProjectAction implicitAction = action.ImplicitActions[0];

                    Assert.Equal(packageV1.Identity, implicitAction.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Install, implicitAction.ProjectActionType);

                    await projectManager.ExecuteActionsAsync(actions, CancellationToken.None);
                });

                await PerformOperationAsync(async (projectManager) =>
                {
                    IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync(
                        projectIds,
                        packageV2.Identity,
                        VersionConstraints.None,
                        includePrelease: true,
                        DependencyBehavior.Lowest,
                        packageSourceNames,
                        CancellationToken.None);

                    Assert.NotEmpty(actions);
                    Assert.Equal(1, actions.Count);

                    ProjectAction action = actions[0];

                    Assert.Equal(packageV2.Identity, action.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType);
                    Assert.Equal(projectId, action.ProjectId);

                    Assert.Equal(2, action.ImplicitActions.Count);

                    ImplicitProjectAction implicitAction = action.ImplicitActions[0];

                    Assert.Equal(packageV1.Identity, implicitAction.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Uninstall, implicitAction.ProjectActionType);

                    implicitAction = action.ImplicitActions[1];

                    Assert.Equal(packageV2.Identity, implicitAction.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Install, implicitAction.ProjectActionType);
                });
            }
        }
        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 DotnetRestore_VerifyPerProjectConfigSourcesAreUsedForChildProjectsWithSolutionAsync()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var projects      = new Dictionary <string, SimpleTestProjectContext>();
                var sources       = new List <string>();
                var projFramework = FrameworkConstants.CommonFrameworks.Net462;

                foreach (var letter in new[] { "A", "B", "C" })
                {
                    // Project
                    var project = SimpleTestProjectContext.CreateNETCore(
                        $"project{letter}",
                        pathContext.SolutionRoot,
                        projFramework);

                    projects.Add(letter, project);

                    // Package
                    var package = new SimpleTestPackageContext()
                    {
                        Id      = $"package{letter}",
                        Version = "1.0.0"
                    };

                    // Do not flow the reference up
                    package.PrivateAssets = "all";

                    project.AddPackageToAllFrameworks(package);
                    project.Properties.Clear();

                    // Source
                    var source = Path.Combine(pathContext.WorkingDirectory, $"source{letter}");
                    await SimpleTestPackageUtility.CreatePackagesAsync(source, package);

                    sources.Add(source);

                    // Create a nuget.config for the project specific source.
                    var projectDir = Path.GetDirectoryName(project.ProjectPath);
                    Directory.CreateDirectory(projectDir);
                    var configPath = Path.Combine(projectDir, "NuGet.Config");

                    var doc           = new XDocument();
                    var configuration = new XElement(XName.Get("configuration"));
                    doc.Add(configuration);

                    var config = new XElement(XName.Get("config"));
                    configuration.Add(config);

                    var packageSources = new XElement(XName.Get("packageSources"));
                    configuration.Add(packageSources);

                    var sourceEntry = new XElement(XName.Get("add"));
                    sourceEntry.Add(new XAttribute(XName.Get("key"), "projectSource"));
                    sourceEntry.Add(new XAttribute(XName.Get("value"), source));
                    packageSources.Add(sourceEntry);

                    File.WriteAllText(configPath, doc.ToString());
                }

                // Create root project
                var projectRoot = SimpleTestProjectContext.CreateNETCore(
                    "projectRoot",
                    pathContext.SolutionRoot,
                    projFramework);

                // Link the root project to all other projects
                // Save them.
                foreach (var child in projects.Values)
                {
                    projectRoot.AddProjectToAllFrameworks(child);
                    child.Save();
                }
                projectRoot.Save();
                var solutionPath = Path.Combine(pathContext.SolutionRoot, "solution.sln");
                _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"new sln {solutionPath}");

                foreach (var child in projects.Values)
                {
                    _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"sln {solutionPath} add {child.ProjectPath}");
                }
                _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"sln {solutionPath} add {projectRoot.ProjectPath}");

                // Act
                var result = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"restore {solutionPath}");

                result.Success.Should().BeTrue(because: result.AllOutput);

                // Assert
                projects.Count.Should().BeGreaterThan(0);

                foreach (var letter in projects.Keys)
                {
                    projects[letter].AssetsFile.Should().NotBeNull(because: result.AllOutput);
                    projects[letter].AssetsFile.Libraries.Select(e => e.Name).Should().Contain($"package{letter}", because: result.AllOutput);
                }
            }
        }
        public async Task DotnetRestore_OneLinePerRestore()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var testDirectory = pathContext.SolutionRoot;
                var pkgX          = new SimpleTestPackageContext("x", "1.0.0");
                await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, pkgX);

                var projectName1      = "ClassLibrary1";
                var workingDirectory1 = Path.Combine(testDirectory, projectName1);
                var projectFile1      = Path.Combine(workingDirectory1, $"{projectName1}.csproj");
                _msbuildFixture.CreateDotnetNewProject(testDirectory, projectName1, " classlib");

                using (var stream = File.Open(projectFile1, FileMode.Open, FileAccess.ReadWrite))
                {
                    var xml = XDocument.Load(stream);
                    ProjectFileUtils.SetTargetFrameworkForProject(xml, "TargetFrameworks", "net45");

                    var attributes = new Dictionary <string, string>()
                    {
                        { "Version", "1.0.0" }
                    };

                    ProjectFileUtils.AddItem(
                        xml,
                        "PackageReference",
                        "x",
                        "netstandard1.3",
                        new Dictionary <string, string>(),
                        attributes);

                    ProjectFileUtils.WriteXmlToFile(xml, stream);
                }

                var slnContents = @"
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.27330.1
MinimumVisualStudioVersion = 10.0.40219.1
Project(""{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"") = ""ClassLibrary1"", ""ClassLibrary1\ClassLibrary1.csproj"", ""{216FF388-8C16-4AF4-87A8-9094030692FA}""
EndProject
Global
	GlobalSection(SolutionConfigurationPlatforms) = preSolution
		Debug|Any CPU = Debug|Any CPU
		Release|Any CPU = Release|Any CPU
	EndGlobalSection
	GlobalSection(ProjectConfigurationPlatforms) = postSolution
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Debug|Any CPU.Build.0 = Debug|Any CPU
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Release|Any CPU.ActiveCfg = Release|Any CPU
		{216FF388-8C16-4AF4-87A8-9094030692FA}.Release|Any CPU.Build.0 = Release|Any CPU
	EndGlobalSection
	GlobalSection(SolutionProperties) = preSolution
		HideSolutionNode = FALSE
	EndGlobalSection
	GlobalSection(ExtensibilityGlobals) = postSolution
		SolutionGuid = {9A6704E2-6E77-4FF4-9E54-B789D88829DD}
	EndGlobalSection
EndGlobal";

                var slnPath = Path.Combine(pathContext.SolutionRoot, "proj.sln");
                File.WriteAllText(slnPath, slnContents);

                // Act
                var result = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"restore proj.sln {$"--source \"{pathContext.PackageSource}\""}", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0);
                Assert.True(1 == result.AllOutput.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Length, result.AllOutput);

                // Act - make sure no-op does the same thing.
                result = _msbuildFixture.RunDotnet(pathContext.SolutionRoot, $"restore proj.sln {$"--source \"{pathContext.PackageSource}\""}", ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0);
                Assert.True(1 == result.AllOutput.Split(Environment.NewLine, StringSplitOptions.RemoveEmptyEntries).Length, result.AllOutput);
            }
        }
Пример #13
0
        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).EnsureProjectJsonRestoreMetadata();

                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 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);
            }
        }
Пример #15
0
        public async Task LocalPackageSearchResource_FileSourceAsync()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                var testLogger = new TestLogger();

                var nuspec = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <package>
                        <metadata>
                            <id>myPackage</id>
                            <version>1.0.0-alpha.1.2+5</version>
                            <description>package description</description>
                            <tags>a b c</tags>
                        </metadata>
                        </package>");

                var packageA = new SimpleTestPackageContext()
                {
                    Id      = "myPackage",
                    Version = "1.0.0-alpha.1.2+5",
                    Nuspec  = nuspec
                };

                var nuspec2 = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <package>
                        <metadata>
                            <id>myOtherPackage</id>
                            <version>1.0.0-alpha.1.3+5</version>
                            <description>package description</description>
                            <tags>a b c</tags>
                        </metadata>
                        </package>");

                var packageA2 = new SimpleTestPackageContext()
                {
                    Id      = "myOtherPackage",
                    Version = "1.0.0-alpha.1.3+5",
                    Nuspec  = nuspec2
                };

                var packageContexts = new SimpleTestPackageContext[]
                {
                    packageA,
                    packageA2
                };

                var fileUrl = "file://" + root.Path.Replace(@"\", @"/");

                await SimpleTestPackageUtility.CreatePackagesAsync(root, packageContexts);

                var localResource = new FindLocalPackagesResourceV2(fileUrl);
                var resource      = new LocalPackageSearchResource(localResource);

                var filter = new SearchFilter(includePrerelease: true);

                // Act
                var packages = (await resource.SearchAsync(
                                    "mypackage",
                                    filter,
                                    skip: 0,
                                    take: 30,
                                    log: testLogger,
                                    token: CancellationToken.None))
                               .OrderBy(p => p.Identity.Id)
                               .ToList();

                var package = packages.First();

                // Assert
                Assert.Equal(1, packages.Count);
                Assert.Equal("myPackage", package.Identity.Id);
                Assert.Equal("1.0.0-alpha.1.2+5", package.Identity.Version.ToFullString());
            }
        }
Пример #16
0
        public async Task GetInstallActionsAsync_WithPackagesConfigProject_WhenUpdatingPackage_ReturnsCorrectActions()
        {
            const string projectName = "a";
            string       projectId   = Guid.NewGuid().ToString();

            using (TestDirectory testDirectory = TestDirectory.Create())
            {
                var    packageV1 = new SimpleTestPackageContext(packageId: "b", version: "1.0.0");
                var    packageV2 = new SimpleTestPackageContext(packageV1.Id, version: "2.0.0");
                string packageSourceDirectoryPath = Path.Combine(testDirectory, "packageSource");

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    packageSourceDirectoryPath,
                    PackageSaveMode.Defaultv3,
                    packageV1,
                    packageV2);

                var packageSource  = new PackageSource(packageSourceDirectoryPath);
                var packageSources = new List <PackageSource>()
                {
                    packageSource
                };

                Initialize(packageSources);

                string         projectFullPath           = Path.Combine(testDirectory.Path, $"{projectName}.csproj");
                NuGetFramework targetFramework           = NuGetFramework.Parse("net46");
                var            msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(targetFramework, new TestNuGetProjectContext());
                var            project = new TestMSBuildNuGetProject(msBuildNuGetProjectSystem, testDirectory.Path, projectFullPath, projectId);

                _solutionManager.NuGetProjects.Add(project);

                string[] projectIds         = new[] { projectId };
                string[] packageSourceNames = new[] { packageSource.Name };

                await PerformOperationAsync(async (projectManager) =>
                {
                    IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync(
                        projectIds,
                        packageV1.Identity,
                        VersionConstraints.None,
                        includePrelease: true,
                        DependencyBehavior.Lowest,
                        packageSourceNames,
                        CancellationToken.None);

                    Assert.NotEmpty(actions);
                    Assert.Equal(1, actions.Count);

                    ProjectAction action = actions[0];

                    Assert.Equal(packageV1.Identity, action.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType);
                    Assert.Equal(projectId, action.ProjectId);

                    Assert.Empty(action.ImplicitActions);

                    await projectManager.ExecuteActionsAsync(actions, CancellationToken.None);
                });

                await PerformOperationAsync(async (projectManager) =>
                {
                    IReadOnlyList <ProjectAction> actions = await projectManager.GetInstallActionsAsync(
                        projectIds,
                        packageV2.Identity,
                        VersionConstraints.None,
                        includePrelease: true,
                        DependencyBehavior.Lowest,
                        packageSourceNames,
                        CancellationToken.None);

                    Assert.NotEmpty(actions);
                    Assert.Equal(2, actions.Count);

                    ProjectAction action = actions[0];

                    Assert.Equal(packageV1.Identity, action.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Uninstall, action.ProjectActionType);
                    Assert.Equal(projectId, action.ProjectId);

                    action = actions[1];

                    Assert.Equal(packageV2.Identity, action.PackageIdentity);
                    Assert.Equal(NuGetProjectActionType.Install, action.ProjectActionType);
                    Assert.Equal(projectId, action.ProjectId);
                });
            }
        }
Пример #17
0
        public async Task RuntimePackage_RejectedPackagesAreNotMerged()
        {
            // Arrange
            var logger    = new TestLogger();
            var framework = "net46";

            using (var workingDir = CreateTestFolders())
            {
                var repository  = Path.Combine(workingDir, "repository");
                var projectDir  = Path.Combine(workingDir, "project");
                var packagesDir = Path.Combine(workingDir, "packages");

                var runtimeJsonX1 = @"{
                  ""runtimes"": {
                    ""unix"": {
                            ""packageX"": {
                                ""runtime.packageX"": ""1.0.0""
                            }
                          }
                        },
                ""supports"": {
                    ""x1.app"": {
                            ""uap10.0"": [
                                ""win10-x86""
                        ]
                    }
                   }
                  }";

                var runtimeJsonX2 = @"{
                  ""runtimes"": {
                    ""unix"": {
                            ""packageX"": {
                                ""runtime.packageX"": ""2.0.0""
                            }
                          }
                        },
                ""supports"": {
                    ""x2.app"": {
                            ""uap10.0"": [
                                ""win10-x86""
                        ]
                    }
                   }
                  }";

                var packages = new List <SimpleTestPackageContext>();

                // A -> X 1.0.0 -> runtime.X 1.0.0
                // B -> X 2.0.0 -> runtime.X 2.0.0

                var packageX1 = new SimpleTestPackageContext()
                {
                    Id          = "packageX",
                    Version     = "1.0.0",
                    RuntimeJson = runtimeJsonX1
                };

                var packageX2 = new SimpleTestPackageContext()
                {
                    Id          = "packageX",
                    Version     = "2.0.0",
                    RuntimeJson = runtimeJsonX2
                };

                var packageB = new SimpleTestPackageContext()
                {
                    Id = "packageB"
                };

                var packageA = new SimpleTestPackageContext()
                {
                    Id = "packageA"
                };

                var packageX1Runtime = new SimpleTestPackageContext()
                {
                    Id      = "runtime.packageX",
                    Version = "1.0.0"
                };

                var packageX2Runtime = new SimpleTestPackageContext()
                {
                    Id      = "runtime.packageX",
                    Version = "2.0.0"
                };

                packageA.Dependencies.Add(packageX1);
                packageB.Dependencies.Add(packageX2);

                packages.Add(packageA);
                packages.Add(packageB);
                packages.Add(packageX1);
                packages.Add(packageX2);
                packages.Add(packageX1Runtime);
                packages.Add(packageX2Runtime);

                await SimpleTestPackageUtility.CreatePackagesAsync(packages, repository);

                var sources = new List <PackageSource>();
                sources.Add(new PackageSource(repository));

                var configJson = JObject.Parse(@"{
                    ""runtimes"": {
                        ""unix"": {}
                    },
                    ""dependencies"": {
                        ""packageA"": ""1.0.0"",
                        ""packageB"": ""1.0.0""
                    },
                    ""frameworks"": {
                        ""_FRAMEWORK_"": {}
                    }
                }".Replace("_FRAMEWORK_", framework));

                var specPath = Path.Combine(projectDir, "TestProject", "project.json");
                var spec     = JsonPackageSpecReader.GetPackageSpec(configJson.ToString(), "TestProject", specPath);

                var request = new TestRestoreRequest(spec, sources, packagesDir, logger);
                request.LockFilePath = Path.Combine(projectDir, "project.lock.json");

                var command = new RestoreCommand(request);

                // Act
                var result = await command.ExecuteAsync();

                await result.CommitAsync(logger, CancellationToken.None);

                var runtimeGraph = result.RestoreGraphs.Single(graph => graph.RuntimeIdentifier == "unix").RuntimeGraph;

                var selectedRuntimeDependency = runtimeGraph
                                                .Runtimes
                                                .Single()
                                                .Value
                                                .RuntimeDependencySets
                                                .Single()
                                                .Value
                                                .Dependencies
                                                .Single();

                var runtimeDependencyVersion = selectedRuntimeDependency.Value.VersionRange.ToLegacyShortString();

                // Assert
                Assert.True(result.Success);
                Assert.Equal("x2.app", runtimeGraph.Supports.Single().Key);
                Assert.Equal("2.0.0", runtimeDependencyVersion);
            }
        }
Пример #18
0
        public async Task FeedPackagePruning_GivenThatAV3FeedPrunesAPackageDuringRestoreVerifyRestoreRecoversAsync()
        {
            // Arrange
            using (var server = new MockServer())
                using (var pathContext = new SimpleTestPathContext())
                {
                    // Set up solution, project, and packages
                    var testLogger     = new TestLogger();
                    var solution       = new SimpleTestSolutionContext(pathContext.SolutionRoot);
                    var serverRepoPath = Path.Combine(pathContext.WorkingDirectory, "serverPackages");

                    var packageX100 = new SimpleTestPackageContext("x", "1.0.0");
                    var packageX200 = new SimpleTestPackageContext("x", "2.0.0");

                    await SimpleTestPackageUtility.CreatePackagesAsync(
                        serverRepoPath,
                        packageX100,
                        packageX200);

                    var projectA = SimpleTestProjectContext.CreateNETCore(
                        "a",
                        pathContext.SolutionRoot,
                        NuGetFramework.Parse("net45"));
                    projectA.AddPackageToAllFrameworks(packageX200);
                    solution.Projects.Add(projectA);

                    var projectB = SimpleTestProjectContext.CreateNETCore(
                        "b",
                        pathContext.SolutionRoot,
                        NuGetFramework.Parse("net45"));
                    projectB.AddPackageToAllFrameworks(packageX100);
                    solution.Projects.Add(projectB);

                    solution.Create(pathContext.SolutionRoot);

                    // Server setup
                    var indexJson = Util.CreateIndexJson();
                    Util.AddFlatContainerResource(indexJson, server);
                    Util.AddRegistrationResource(indexJson, server);

                    server.Get.Add("/", request =>
                    {
                        return(ServerHandlerV3(request, server, indexJson, serverRepoPath));
                    });

                    server.Start();

                    var feedUrl = server.Uri + "index.json";

                    // Restore x 2.0.0 and populate the http cache
                    var r = Util.Restore(pathContext, projectA.ProjectPath, 0, "-Source", feedUrl);

                    // Delete x 1.0.0
                    File.Delete(LocalFolderUtility.GetPackageV2(serverRepoPath, packageX100.Identity, testLogger).Path);

                    // Act
                    // Restore x 1.0.0
                    r = Util.Restore(pathContext, projectB.ProjectPath, 0, "-Source", feedUrl);

                    var xLib = projectB.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "x");

                    // Assert
                    Assert.Equal("2.0.0", xLib.Version.ToNormalizedString());
                }
        }
Пример #19
0
 public static async Task CreatePackageInSourceAsync(string packageSource, string packageName, string packageVersion)
 {
     var package = CreatePackage(packageName, packageVersion);
     await SimpleTestPackageUtility.CreatePackagesAsync(packageSource, package);
 }
Пример #20
0
        public async Task AddPkg_WhenPackageSourceMappingConfiguredCanotInstallsPackagesFromRestoreSources_Fails()
        {
            using var pathContext = new SimpleTestPathContext();

            // Set up solution, and project
            var solution    = new SimpleTestSolutionContext(pathContext.SolutionRoot);
            var projectName = "projectA";
            var projectA    = XPlatTestUtils.CreateProject(projectName, pathContext, "net5.0");

            const string version = "1.0.0";
            const string packageX = "X", packageZ = "Z";

            var packageFrameworks = "net472; net5.0";
            var packageX100       = XPlatTestUtils.CreatePackage(packageX, version, frameworkString: packageFrameworks);
            var packageZ100       = XPlatTestUtils.CreatePackage(packageZ, version, frameworkString: packageFrameworks);

            packageX100.Dependencies.Add(packageZ100);

            var packageSource2 = new DirectoryInfo(Path.Combine(pathContext.WorkingDirectory, "source2"));

            packageSource2.Create();

            await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                pathContext.PackageSource,
                PackageSaveMode.Defaultv3,
                packageX100,
                packageZ100);

            await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                packageSource2.FullName,
                PackageSaveMode.Defaultv3,
                packageX100,
                packageZ100);

            var configFile = @$ "<?xml version=" "1.0" " encoding=" "utf-8" "?>
<configuration>
    <packageSources>
        <add key=" "source2" " value=" "{packageSource2.FullName}" " />
    </packageSources>
        <packageSourceMapping>
            <packageSource key=" "source2" ">
                <package pattern=" "{packageX}*" " />
            </packageSource>
    </packageSourceMapping>
</configuration>
";

            // Add RestoreSources
            projectA.Properties.Add("RestoreSources", $"{packageSource2.FullName};{pathContext.PackageSource}");

            solution.Projects.Add(projectA);
            solution.Create(pathContext.SolutionRoot);

            var projectADirectory = Path.Combine(pathContext.SolutionRoot, projectA.ProjectName);

            File.WriteAllText(Path.Combine(projectADirectory, "NuGet.Config"), configFile);

            //Act
            var result = _fixture.RunDotnet(projectADirectory, $"add {projectA.ProjectPath} package {packageX} -v {version} -s {packageSource2}", ignoreExitCode: true);

            // Assert
            result.Success.Should().BeFalse(because: result.AllOutput);
            Assert.Contains($"Installed {packageX} {version} from {packageSource2}", result.AllOutput);
            Assert.Contains($"NU1100: Unable to resolve '{packageZ} (>= {version})' for 'net5.0'", result.AllOutput);
        }
Пример #21
0
        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);
            }
        }
Пример #22
0
        public async Task BuildAssetsUtils_GeneratePathPropertyForTools(bool hasTools)
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                // Arrange
                var identity = new PackageIdentity("packagea", NuGetVersion.Parse("1.0.0"));

                var packageDirectory = Directory.CreateDirectory(Path.Combine(pathContext.UserPackagesFolder, identity.Id, identity.Version.ToNormalizedString()));

                File.WriteAllText(Path.Combine(packageDirectory.FullName, $"{identity.Id}.{identity.Version.ToNormalizedString()}.nupkg.sha512"), string.Empty);

                var packagePath = await SimpleTestPackageUtility.CreateFullPackageAsync(
                    packageDirectory.FullName,
                    identity.Id,
                    identity.Version.ToString());

                var logger = new TestLogger();

                const string referenceSpec    = @"
                {
                    ""frameworks"": {
                        ""netcoreapp1.0"": {
                            ""dependencies"": {
                            }
                        }
                    }
                }";
                var          projectName      = "a";
                var          rootProjectsPath = pathContext.WorkingDirectory;
                var          projectDirectory = Path.Combine(rootProjectsPath, projectName);

                var spec = JsonPackageSpecReader.GetPackageSpec(referenceSpec, projectName, Path.Combine(projectDirectory, projectName)).WithTestRestoreMetadata();

                spec.Dependencies.Add(new LibraryDependency
                {
                    IncludeType  = LibraryIncludeFlags.All,
                    LibraryRange = new LibraryRange(identity.Id, new VersionRange(identity.Version), LibraryDependencyTarget.Package)
                });

                var targetGraphs = new List <RestoreTargetGraph>
                {
                    OriginalCaseGlobalPackageFolderTests.GetRestoreTargetGraph(pathContext.PackageSource, identity, packagePath, logger)
                };

                targetGraphs[0].Graphs.FirstOrDefault().Item.Data.Dependencies = spec.Dependencies;

                var lockFile = new LockFile
                {
                    Libraries =
                    {
                        new LockFileLibrary
                        {
                            Name     = identity.Id,
                            Version  = identity.Version,
                            Path     = $"{identity.Id.ToLowerInvariant()}/{identity.Version.ToNormalizedString()}",
                            Type     = LibraryType.Package,
                            HasTools = hasTools,
                        }
                    },
                    Targets =
                    {
                        new LockFileTarget
                        {
                            RuntimeIdentifier = targetGraphs[0].RuntimeIdentifier,
                            TargetFramework   = targetGraphs[0].Framework,
                            Libraries         =
                            {
                                new LockFileTargetLibrary
                                {
                                    Name    = identity.Id,
                                    Version = identity.Version
                                }
                            }
                        }
                    }
                };

                var repositories = new List <NuGetv3LocalRepository>
                {
                    new NuGetv3LocalRepository(pathContext.UserPackagesFolder)
                };

                var restoreRequest = new TestRestoreRequest(spec, new[] { new PackageSource(pathContext.PackageSource) }, pathContext.PackagesV2, logger)
                {
                    ProjectStyle = spec.RestoreMetadata.ProjectStyle
                };

                var assetsFilePath = Path.Combine(projectDirectory, "obj", "project.assets.json");

                // Act
                var outputFiles = BuildAssetsUtils.GetMSBuildOutputFiles(spec, lockFile, targetGraphs, repositories, restoreRequest, assetsFilePath, true, logger);

                var expectedPropertyName = $"Pkg{identity.Id.Replace(".", "_")}";

                var actualPropertyElement = outputFiles.FirstOrDefault().Content.Root.Descendants().Where(i => i.Name.LocalName.Equals(expectedPropertyName)).FirstOrDefault();

                if (hasTools)
                {
                    // Assert
                    Assert.NotNull(actualPropertyElement);


                    Assert.Equal($" '$({actualPropertyElement.Name.LocalName})' == '' ", actualPropertyElement.Attribute("Condition")?.Value);

                    Assert.Equal(packageDirectory.FullName, actualPropertyElement?.Value, ignoreCase: true);

                    Assert.Equal(" '$(ExcludeRestorePackageImports)' != 'true' ", actualPropertyElement.Parent.Attribute("Condition")?.Value);
                }
                else
                {
                    Assert.Null(actualPropertyElement);
                }
            }
        }
Пример #23
0
        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);
            }
        }
Пример #24
0
        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);
            }
        }
Пример #25
0
        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));
            }
        }
Пример #26
0
        public async Task RestoreTargets_RestoreWithRuntimes()
        {
            // 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);

                request.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");

                SimpleTestPackageUtility.CreatePackages(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 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());
                }
        }
Пример #28
0
        public async Task RestoreCommand_VerifyMinClientVersionAlreadyInstalled()
        {
            // Arrange
            using (var emptyDir = TestFileSystemUtility.CreateRandomTestFolder())
                using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder())
                    using (var packagesDir = TestFileSystemUtility.CreateRandomTestFolder())
                        using (var projectDir = TestFileSystemUtility.CreateRandomTestFolder())
                        {
                            var logger = new TestLogger();

                            var packageContext = new SimpleTestPackageContext()
                            {
                                Id               = "packageA",
                                Version          = "1.0.0",
                                MinClientVersion = "9.9.9"
                            };

                            var packagePath = Path.Combine(workingDir, "packageA.1.0.0.nupkg");

                            SimpleTestPackageUtility.CreatePackages(workingDir, packageContext);

                            // install the package
                            using (var fileStream = File.OpenRead(packagePath))
                            {
                                await PackageExtractor.InstallFromSourceAsync((stream) =>
                                                                              fileStream.CopyToAsync(stream, 4096, CancellationToken.None),
                                                                              new VersionFolderPathContext(new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0")),
                                                                                                           packagesDir,
                                                                                                           logger,
                                                                                                           PackageSaveMode.Defaultv3,
                                                                                                           XmlDocFileSaveMode.None),
                                                                              CancellationToken.None);
                            }

                            var specPath = Path.Combine(projectDir, "TestProject", "project.json");
                            var spec     = XPlatTestUtils.BasicConfigNetCoreApp;

                            XPlatTestUtils.AddDependency(spec, "packageA", "1.0.0");
                            XPlatTestUtils.WriteJson(spec, specPath);

                            var lockFilePath = Path.Combine(projectDir, "project.lock.json");
                            var log          = new TestCommandOutputLogger();

                            var args = new string[]
                            {
                                "restore",
                                projectDir,
                                "-s",
                                emptyDir,
                                "--packages",
                                packagesDir
                            };

                            // Act
                            var exitCode = Program.MainInternal(args, log);

                            // Assert
                            Assert.Equal(1, log.Errors);
                            Assert.Contains("'packageA 1.0.0' package requires NuGet client version '9.9.9' or above", log.ShowMessages());
                            Assert.False(File.Exists(lockFilePath));
                        }
        }
Пример #29
0
        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 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);
            }
        }