Exemplo n.º 1
0
        public void GetClientPolicy_MutipleConfigs_ReadsParsesAndMergesTrustedSigners()
        {
            // Arrange
            var config1 = @"
<configuration>
    <config>
        <add key=""signatureValidationMode"" value=""require"" />
    </config>
    <trustedSigners>
        <author name=""author1"">
            <certificate fingerprint=""abc"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </author>
        <repository name=""repository1"" serviceIndex=""https://v3serviceIndex.test/api/json"">
            <certificate fingerprint=""def"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </repository>
    </trustedSigners>
</configuration>";

            var config2 = @"
<configuration>
    <config>
        <add key=""signatureValidationMode"" value=""require"" />
    </config>
    <trustedSigners>
        <author name=""author1"">
            <certificate fingerprint=""xyz"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </author>
        <repository name=""repository2"" serviceIndex=""https://v3serviceIndex2.test/api/json"">
            <certificate fingerprint=""rst"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </repository>
    </trustedSigners>
</configuration>";

            var config3 = @"
<configuration>
    <config>
        <add key=""signatureValidationMode"" value=""require"" />
    </config>
    <trustedSigners>
        <author name=""author2"">
            <certificate fingerprint=""xyz"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </author>
        <repository name=""repository1"" serviceIndex=""https://v3serviceIndex.test/api/json"">
            <certificate fingerprint=""opq"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false"" />
        </repository>
    </trustedSigners>
</configuration>";

            var nugetConfigPath = "NuGet.Config";

            using (var mockBaseDirectory = TestDirectory.Create())
                using (var innerMockDirectory = TestDirectory.Create(mockBaseDirectory))
                    using (var closerDirectory = TestDirectory.Create(innerMockDirectory))
                    {
                        SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, mockBaseDirectory, config1);
                        SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, innerMockDirectory, config2);
                        SettingsTestUtils.CreateConfigurationFile(nugetConfigPath, closerDirectory, config3);

                        // Act and Assert
                        var settings = Settings.LoadDefaultSettings(closerDirectory);
                        settings.Should().NotBeNull();

                        var expectedAllowList = new List <VerificationAllowListEntry>()
                        {
                            new TrustedSignerAllowListEntry(VerificationTarget.Author, SignaturePlacement.PrimarySignature, "xyz", HashAlgorithmName.SHA256),
                            new TrustedSignerAllowListEntry(VerificationTarget.Repository, SignaturePlacement.Any, "rst", HashAlgorithmName.SHA256),
                            new TrustedSignerAllowListEntry(VerificationTarget.Repository, SignaturePlacement.Any, "opq", HashAlgorithmName.SHA256)
                        };

                        var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, NullLogger.Instance);

                        clientPolicyContext.Policy.Should().Be(SignatureValidationMode.Require);
                        clientPolicyContext.AllowList.Count.Should().Be(3);
                        clientPolicyContext.AllowList.Should().BeEquivalentTo(expectedAllowList);

                        var verifierSettings = clientPolicyContext.VerifierSettings;

                        verifierSettings.AllowUnsigned.Should().BeFalse();
                        verifierSettings.AllowIllegal.Should().BeFalse();
                        verifierSettings.AllowUntrusted.Should().BeFalse();
                        verifierSettings.AllowIgnoreTimestamp.Should().BeTrue();
                        verifierSettings.AllowMultipleTimestamps.Should().BeTrue();
                        verifierSettings.AllowNoTimestamp.Should().BeTrue();
                        verifierSettings.AllowUnknownRevocation.Should().BeTrue();
                        verifierSettings.ReportUnknownRevocation.Should().BeTrue();
                        verifierSettings.VerificationTarget.Should().Be(VerificationTarget.All);
                        verifierSettings.SignaturePlacement.Should().Be(SignaturePlacement.Any);
                        verifierSettings.RepositoryCountersignatureVerificationBehavior.Should().Be(SignatureVerificationBehavior.IfExistsAndIsNecessary);
                        verifierSettings.RevocationMode.Should().Be(RevocationMode.Online);
                    }
        }
Exemplo n.º 2
0
        public void GetProjectReferences_WhenDuplicateExistsOrMetadataSpecified_DuplicatesIgnoredAndMetadataReadCorrectly()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var projectA = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectA", "ProjectA.csproj"));
                var projectB = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectB", "ProjectB.csproj"));
                var projectC = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectC", "ProjectC.csproj"));
                var projectD = new MockMSBuildProject(Path.Combine(testDirectory, "ProjectD", "ProjectD.csproj"));

                var project = new MockMSBuildProject(testDirectory)
                {
                    Items = new Dictionary <string, IList <IMSBuildItem> >
                    {
                        ["ProjectReference"] = new List <IMSBuildItem>
                        {
                            new MSBuildItem(@"ProjectA\ProjectA.csproj", new Dictionary <string, string> {
                                ["FullPath"] = projectA.FullPath
                            }),
                            new MSBuildItem(@"ProjectA\ProjectA.csproj", new Dictionary <string, string> {
                                ["FullPath"] = "ShouldBeDeduped"
                            }),
                            new MSBuildItem(@"ProjectB\ProjectB.csproj", new Dictionary <string, string> {
                                ["FullPath"] = projectB.FullPath, ["ExcludeAssets"] = $"{LibraryIncludeFlags.Compile};{LibraryIncludeFlags.Runtime}"
                            }),
                            new MSBuildItem(@"ProjectC\ProjectC.csproj", new Dictionary <string, string> {
                                ["FullPath"] = projectC.FullPath, ["IncludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.BuildTransitive}"
                            }),
                            new MSBuildItem(@"ProjectD\ProjectD.csproj", new Dictionary <string, string> {
                                ["FullPath"] = projectD.FullPath, ["PrivateAssets"] = $"{LibraryIncludeFlags.Runtime};{LibraryIncludeFlags.ContentFiles}"
                            }),
                            new MSBuildItem(@"ProjectE\ProjectE.csproj", new Dictionary <string, string> {
                                ["ReferenceOutputAssembly"] = bool.FalseString
                            }),
                        }
                    }
                };

                var actual = MSBuildStaticGraphRestore.GetProjectReferences(project);

                actual.ShouldBeEquivalentTo(new[]
                {
                    new ProjectRestoreReference
                    {
                        ProjectPath       = projectA.FullPath,
                        ProjectUniqueName = projectA.FullPath
                    },
                    new ProjectRestoreReference
                    {
                        ProjectPath       = projectB.FullPath,
                        ProjectUniqueName = projectB.FullPath,
                        ExcludeAssets     = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.Compile
                    },
                    new ProjectRestoreReference
                    {
                        ProjectPath       = projectC.FullPath,
                        ProjectUniqueName = projectC.FullPath,
                        IncludeAssets     = LibraryIncludeFlags.Build | LibraryIncludeFlags.BuildTransitive
                    },
                    new ProjectRestoreReference
                    {
                        ProjectPath       = projectD.FullPath,
                        ProjectUniqueName = projectD.FullPath,
                        PrivateAssets     = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.ContentFiles
                    }
                });
            }
        }
Exemplo n.º 3
0
        public async Task DoesNotSkipPackagesWhenExceptionOccurs(string catalogUri, string expectedCursorBeforeRetry)
        {
            // Arrange
            var storage        = new MemoryStorage();
            var storageFactory = new TestStorageFactory(name => storage.WithName(name));

            MockServerHttpClientHandler mockServer;

            mockServer = new MockServerHttpClientHandler();
            mockServer.SetAction("/", request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));

            var catalogStorage = Catalogs.CreateTestCatalogWithCommitThenTwoPackageCommit();
            await mockServer.AddStorageAsync(catalogStorage);

            // Make the first request for a catalog leaf node fail. This will cause the registration collector
            // to fail the first time but pass the second time.
            FailFirstRequest(mockServer, catalogUri);

            expectedCursorBeforeRetry = expectedCursorBeforeRetry ?? MemoryCursor.MinValue.ToString("O");

            ReadWriteCursor front = new DurableCursor(
                storage.ResolveUri("cursor.json"),
                storage,
                MemoryCursor.MinValue);
            ReadCursor back = MemoryCursor.CreateMax();

            using (var testDirectory = TestDirectory.Create())
            {
                var luceneDirectory = new SimpleFSDirectory(new DirectoryInfo(testDirectory));
                using (var indexWriter = Catalog2LuceneJob.CreateIndexWriter(luceneDirectory))
                {
                    var target = new SearchIndexFromCatalogCollector(
                        new Uri("http://tempuri.org/index.json"),
                        indexWriter,
                        commitEachBatch: true,
                        baseAddress: null,
                        telemetryService: new Mock <ITelemetryService>().Object,
                        logger: new TestLogger(),
                        handlerFunc: () => mockServer);

                    // Act
                    await Assert.ThrowsAsync <Exception>(() => target.RunAsync(front, back, CancellationToken.None));

                    var cursorBeforeRetry = front.Value;
                    await target.RunAsync(front, back, CancellationToken.None);

                    var cursorAfterRetry = front.Value;

                    // Assert
                    var reader    = indexWriter.GetReader();
                    var documents = Enumerable
                                    .Range(0, reader.NumDeletedDocs + reader.NumDocs())
                                    .Where(i => !reader.IsDeleted(i))
                                    .Select(i => reader.Document(i))
                                    .ToList();
                    Assert.Equal(4, documents.Count);

                    var documentsByType = documents
                                          .ToLookup(doc => doc
                                                    .fields_ForNUnit
                                                    .FirstOrDefault(f => f.Name == "@type")?
                                                    .StringValue);
                    var commitDocuments  = documentsByType[Schema.DataTypes.CatalogInfastructure.AbsoluteUri.ToString()].ToList();
                    var packageDocuments = documentsByType[null].ToList();
                    Assert.Equal(1, commitDocuments.Count);
                    Assert.Equal(3, packageDocuments.Count);

                    Assert.Equal(
                        "UnlistedPackage",
                        packageDocuments[0].fields_ForNUnit.FirstOrDefault(x => x.Name == Constants.LucenePropertyId)?.StringValue);
                    Assert.Equal(
                        "ListedPackage",
                        packageDocuments[1].fields_ForNUnit.FirstOrDefault(x => x.Name == Constants.LucenePropertyId)?.StringValue);
                    Assert.Equal(
                        "AnotherPackage",
                        packageDocuments[2].fields_ForNUnit.FirstOrDefault(x => x.Name == Constants.LucenePropertyId)?.StringValue);

                    Assert.Equal(DateTime.Parse(expectedCursorBeforeRetry).ToUniversalTime(), cursorBeforeRetry);
                    Assert.Equal(DateTime.Parse("2015-10-12T10:08:55.3335317Z").ToUniversalTime(), cursorAfterRetry);
                }
            }
        }
Exemplo n.º 4
0
        public async Task VerifySignaturesAsync_ExpiredCertificateAndTimestampWithTooLargeRange_Fails()
        {
            var testServer = await _testFixture.GetSigningTestServerAsync();

            var ca = await _testFixture.GetDefaultTrustedCertificateAuthorityAsync();

            var accuracy       = new BcAccuracy(seconds: new DerInteger(30), millis: null, micros: null);
            var serviceOptions = new TimestampServiceOptions()
            {
                Accuracy = accuracy
            };
            var timestampService = TimestampService.Create(ca, serviceOptions);
            var keyPair          = SigningTestUtility.GenerateKeyPair(publicKeyLength: 2048);
            var now          = DateTimeOffset.UtcNow;
            var issueOptions = new IssueCertificateOptions(keyPair.Public)
            {
                NotAfter    = now.AddSeconds(10),
                NotBefore   = now.AddSeconds(-2),
                SubjectName = new X509Name("CN=NuGet Test Expired Certificate")
            };
            var bcCertificate = ca.IssueCertificate(issueOptions);

            using (testServer.RegisterResponder(timestampService))
                using (var certificate = new X509Certificate2(bcCertificate.GetEncoded()))
                    using (var directory = TestDirectory.Create())
                    {
                        certificate.PrivateKey = DotNetUtilities.ToRSA(keyPair.Private as RsaPrivateCrtKeyParameters);

                        var packageContext    = new SimpleTestPackageContext();
                        var signedPackagePath = await SignedArchiveTestUtility.CreateSignedAndTimeStampedPackageAsync(
                            certificate,
                            packageContext,
                            directory,
                            timestampService.Url);

                        var waitDuration = (issueOptions.NotAfter - DateTimeOffset.UtcNow).Add(TimeSpan.FromSeconds(1));

                        // Wait for the certificate to expire.  Trust of the signature will require a valid timestamp.
                        if (waitDuration > TimeSpan.Zero)
                        {
                            await Task.Delay(waitDuration);
                        }

                        Assert.True(DateTime.UtcNow > issueOptions.NotAfter);

                        var verifier = new PackageSignatureVerifier(_trustProviders, SignedPackageVerifierSettings.VerifyCommandDefaultPolicy);

                        using (var packageReader = new PackageArchiveReader(signedPackagePath))
                        {
                            var results = await verifier.VerifySignaturesAsync(packageReader, CancellationToken.None);

                            var result = results.Results.Single();

                            Assert.False(results.Valid);
                            Assert.Equal(SignatureVerificationStatus.Untrusted, result.Trust);
                            Assert.Equal(1, result.Issues.Count(issue => issue.Level == LogLevel.Error));
                            Assert.Equal(0, result.Issues.Count(issue => issue.Level == LogLevel.Warning));

                            Assert.Contains(result.Issues, issue =>
                                            issue.Code == NuGetLogCode.NU3011 &&
                                            issue.Level == LogLevel.Error &&
                                            issue.Message == "The primary signature validity period has expired.");
                        }
                    }
        }
        public async Task GetPackageSpecsAsync_ReadSettingsWithFullPaths(string restorePackagesPath, string sources, string fallbackFolders)
        {
            // Arrange
            using (var testDirectory = TestDirectory.Create())
            {
                var projectAdapter = CreateProjectAdapter(testDirectory);
                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestorePackagesPath)
                .Returns(restorePackagesPath);

                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestoreSources)
                .Returns(sources);

                Mock.Get(projectAdapter)
                .SetupGet(x => x.RestoreFallbackFolders)
                .Returns(fallbackFolders);

                var projectServices = new TestProjectSystemServices();

                var testProject = new LegacyPackageReferenceProject(
                    projectAdapter,
                    Guid.NewGuid().ToString(),
                    projectServices,
                    _threadingService);

                var settings = NullSettings.Instance;
                var testDependencyGraphCacheContext = new DependencyGraphCacheContext(NullLogger.Instance, settings);

                await _threadingService.JoinableTaskFactory.SwitchToMainThreadAsync();

                // Act
                var packageSpecs = await testProject.GetPackageSpecsAsync(testDependencyGraphCacheContext);

                // Assert
                Assert.NotNull(packageSpecs);
                var actualRestoreSpec = packageSpecs.Single();
                SpecValidationUtility.ValidateProjectSpec(actualRestoreSpec);

                // Assert packagespath
                Assert.Equal(restorePackagesPath != null ? restorePackagesPath : SettingsUtility.GetGlobalPackagesFolder(settings), actualRestoreSpec.RestoreMetadata.PackagesPath);

                // assert sources
                var specSources     = actualRestoreSpec.RestoreMetadata.Sources.Select(e => e.Source);
                var expectedSources = sources != null?MSBuildStringUtility.Split(sources) : SettingsUtility.GetEnabledSources(settings).Select(e => e.Source);

                Assert.True(Enumerable.SequenceEqual(expectedSources.OrderBy(t => t), specSources.OrderBy(t => t)));

                // assert fallbackfolders
                var specFallback    = actualRestoreSpec.RestoreMetadata.FallbackFolders;
                var expectedFolders = fallbackFolders != null?MSBuildStringUtility.Split(fallbackFolders) : SettingsUtility.GetFallbackPackageFolders(settings);

                Assert.True(Enumerable.SequenceEqual(expectedFolders.OrderBy(t => t), specFallback.OrderBy(t => t)));

                // Verify
                Mock.Get(projectAdapter)
                .Verify(x => x.RestorePackagesPath, Times.Once);
                Mock.Get(projectAdapter)
                .Verify(x => x.RestoreSources, Times.Once);
                Mock.Get(projectAdapter)
                .Verify(x => x.RestoreFallbackFolders, Times.Once);
            }
        }
        public async Task LocalDependencyInfoResource_ResolvePackagesNearestDependencyGroup()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packageA = new SimpleTestPackageContext()
                {
                    Id      = "a",
                    Version = "1.0",
                    Nuspec  = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <package>
                        <metadata>
                            <id>a</id>
                            <version>1.0</version>
                            <title />
                            <dependencies>
                                <group>
                                    <dependency id=""b"" version=""1.0"" />
                                </group>
                                <group targetFramework=""net46"">
                                    <dependency id=""x"" />
                                </group>
                                <group targetFramework=""net461"">
                                </group>
                            </dependencies>
                        </metadata>
                        </package>")
                };

                var packageContexts = new SimpleTestPackageContext[]
                {
                    packageA
                };

                SimpleTestPackageUtility.CreatePackages(root, packageContexts);

                var source        = Repository.Factory.GetCoreV3(root);
                var localResource = new FindLocalPackagesResourceV2(root);
                var resource      = new LocalDependencyInfoResource(localResource, source);

                // Act
                var resultNet462 = (await resource.ResolvePackages(
                                        "a",
                                        NuGetFramework.Parse("net462"),
                                        NullSourceCacheContext.Instance,
                                        testLogger,
                                        CancellationToken.None)).Single();

                var resultNet46 = (await resource.ResolvePackages(
                                       "a",
                                       NuGetFramework.Parse("net46"),
                                       NullSourceCacheContext.Instance,
                                       testLogger,
                                       CancellationToken.None)).Single();

                var resultWin8 = (await resource.ResolvePackages(
                                      "a",
                                      NuGetFramework.Parse("win8"),
                                      NullSourceCacheContext.Instance,
                                      testLogger,
                                      CancellationToken.None)).Single();

                // Assert
                Assert.Equal(0, resultNet462.Dependencies.Count());
                Assert.Equal(1, resultNet46.Dependencies.Count());
                Assert.Equal(1, resultWin8.Dependencies.Count());

                Assert.Equal("x", resultNet46.Dependencies.Single().Id);
                Assert.Equal(VersionRange.All, resultNet46.Dependencies.Single().VersionRange);
                Assert.Equal("b", resultWin8.Dependencies.Single().Id);
                Assert.Equal(VersionRange.Parse("1.0"), resultWin8.Dependencies.Single().VersionRange);
            }
        }
        public async Task ProjectResolution_MSBuildProjectDoesNotResolveByDirectory()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""dependencies"": {
                ""project2"": ""1.0.0-*""
              },
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var globalJson = @"
            {
                ""projects"": [
                    ""projects""
                ]
            }";

            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"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);
                File.WriteAllText(Path.Combine(workingDir, "global.json"), globalJson);

                var project1CSProjPath = Path.Combine(project1.FullName, "project1.csproj");
                File.WriteAllText(project1CSProjPath, string.Empty);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1).EnsureProjectJsonRestoreMetadata();
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2).EnsureProjectJsonRestoreMetadata();

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                request.ExternalProjects.Add(
                    new ExternalProjectReference("project1", spec1, project1CSProjPath, new string[] { }));

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.False(result.Success);
                Assert.Equal(1, result.GetAllUnresolved().Count);
                Assert.Equal("project2", result.GetAllUnresolved().Single().Name);
            }
        }
Exemplo n.º 8
0
        public async Task GetInstalledVersion_WithAssetsFile_ChangingPackageSpec_ReturnsVersionsFromAssetsSpecs()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                // Setup
                var projectName     = "project1";
                var projectFullPath = Path.Combine(testDirectory.Path, projectName + ".csproj");

                // Project
                var projectCache = new ProjectSystemCache();
                IVsProjectAdapter projectAdapter = (new Mock <IVsProjectAdapter>()).Object;
                var project = CreateNetCorePackageReferenceProject(projectName, projectFullPath, projectCache);

                var projectNames = GetTestProjectNames(projectFullPath, projectName);
                var packageSpec  = GetPackageSpec(projectName, projectFullPath, "[2.0.0, )");

                // Restore info
                var projectRestoreInfo = ProjectJsonTestHelpers.GetDGSpecFromPackageSpecs(packageSpec);
                projectCache.AddProjectRestoreInfo(projectNames, projectRestoreInfo, new List <IAssetsLogMessage>());
                projectCache.AddProject(projectNames, projectAdapter, project).Should().BeTrue();

                // Package directories
                var sources       = new List <PackageSource>();
                var packagesDir   = new DirectoryInfo(Path.Combine(testDirectory, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(testDirectory, "packageSource"));
                packagesDir.Create();
                packageSource.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(packageSpec, sources, packagesDir.FullName, logger)
                {
                    LockFilePath = Path.Combine(testDirectory, "project.assets.json")
                };

                await SimpleTestPackageUtility.CreateFullPackageAsync(packageSource.FullName, "packageA", "2.0.0");

                await SimpleTestPackageUtility.CreateFullPackageAsync(packageSource.FullName, "packageA", "3.0.0");

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

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

                var packages = await project.GetInstalledPackagesAsync(CancellationToken.None);

                // Asert
                Assert.True(result.Success);
                packages.Should().Contain(a => a.PackageIdentity.Equals(new PackageIdentity("packageA", new NuGetVersion("2.0.0"))));

                // Setup
                packageSpec = GetPackageSpec(projectName, projectFullPath, "[3.0.0, )");

                // Restore info
                projectRestoreInfo = ProjectJsonTestHelpers.GetDGSpecFromPackageSpecs(packageSpec);
                projectCache.AddProjectRestoreInfo(projectNames, projectRestoreInfo, new List <IAssetsLogMessage>());
                projectCache.AddProject(projectNames, projectAdapter, project).Should().BeTrue();

                request = new TestRestoreRequest(packageSpec, sources, packagesDir.FullName, logger)
                {
                    LockFilePath = Path.Combine(testDirectory, "project.assets.json")
                };

                // Act
                command = new RestoreCommand(request);
                result  = await command.ExecuteAsync();

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

                packages = await project.GetInstalledPackagesAsync(CancellationToken.None);

                // Asert
                Assert.True(result.Success);
                packages.Should().Contain(a => a.PackageIdentity.Equals(new PackageIdentity("packageA", new NuGetVersion("3.0.0"))));
            }
        }
        public async Task ProjectResolution_ExternalReferenceWithNoProjectJson()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            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"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var msbuidPath1 = Path.Combine(project2.FullName, "project1.xproj");
                var msbuidPath2 = Path.Combine(project2.FullName, "project2.csproj");

                File.WriteAllText(msbuidPath1, string.Empty);
                File.WriteAllText(msbuidPath2, string.Empty);

                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);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                request.ExternalProjects.Add(new ExternalProjectReference(
                                                 "project1",
                                                 spec1,
                                                 msbuidPath1,
                                                 new string[] { "project2" }));

                request.ExternalProjects.Add(new ExternalProjectReference(
                                                 "project2",
                                                 null,
                                                 msbuidPath2,
                                                 new string[] { }));

                // 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().Libraries.Single();

                // Assert
                Assert.True(result.Success);

                // External projects that did not provide a framework should leave the framework property out
                Assert.Null(targetLib.Framework);
            }
        }
        public async Task ProjectResolution_HigherVersionForProjectReferences()
        {
            // Arrange
            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""2.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            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"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                var logger = new TestLogger();

                var restoreContext = new RestoreArgs()
                {
                    Sources = new List <string>()
                    {
                        packageSource.FullName
                    },
                    GlobalPackagesFolder = packagesDir.FullName,
                    Log          = logger,
                    CacheContext = new SourceCacheContext()
                };

                // Modify specs for netcore
                spec2 = spec2.WithTestRestoreMetadata();
                spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);

                var request = await ProjectTestHelpers.GetRequestAsync(restoreContext, spec1, spec2);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                // Assert
                Assert.True(result.Success);
                Assert.Equal(0, result.GetAllUnresolved().Count);
                Assert.Equal(0, logger.Messages.Where(s => s.IndexOf("Dependency specified was") > -1).Count());
            }
        }
        public async Task ProjectResolution_ProjectReferenceWithInCompatibleTFMNoRange()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""2.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net46"": {
                }
              }
            }";

            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"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                var logger = new TestLogger();

                var restoreContext = new RestoreArgs()
                {
                    Sources = new List <string>()
                    {
                        packageSource.FullName
                    },
                    GlobalPackagesFolder = packagesDir.FullName,
                    Log          = logger,
                    CacheContext = new SourceCacheContext()
                };

                // Modify specs for netcore
                spec2 = spec2.WithTestRestoreMetadata();
                spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);

                var request = await ProjectTestHelpers.GetRequestAsync(restoreContext, spec1, spec2);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var issue = result.CompatibilityCheckResults.SelectMany(ccr => ccr.Issues).Single();

                // Assert
                Assert.False(result.Success);
                Assert.Equal(0, result.GetAllUnresolved().Count);
                Assert.Equal("Project project2 is not compatible with net45 (.NETFramework,Version=v4.5). Project project2 supports: net46 (.NETFramework,Version=v4.6)", issue.Format());
                Assert.Equal(1, logger.ErrorMessages.Count());

                Assert.Contains("Project project2 is not compatible with net45 (.NETFramework,Version=v4.5). Project project2 supports: net46 (.NETFramework,Version=v4.6)", logger.ErrorMessages.Last());
            }
        }
        public async Task ProjectResolution_ProjectFrameworkAssemblyReferences()
        {
            // Arrange
            var project1Json = @"
            {
              ""version"": ""1.0.0-*"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var project2Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                   ""frameworkAssemblies"": {
                     ""ReferenceA"": """",
                     ""ReferenceB"": """",
                   },
                }
              }
            }";

            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"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(project2.FullName, "project.json"), project2Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var specPath2 = Path.Combine(project2.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var spec2     = JsonPackageSpecReader.GetPackageSpec(project2Json, "project2", specPath2);

                var logger = new TestLogger();

                var restoreContext = new RestoreArgs()
                {
                    Sources = new List <string>()
                    {
                        packageSource.FullName
                    },
                    GlobalPackagesFolder = packagesDir.FullName,
                    Log          = logger,
                    CacheContext = new SourceCacheContext()
                };

                // Modify specs for netcore
                spec2 = spec2.WithTestRestoreMetadata();
                spec1 = spec1.WithTestRestoreMetadata().WithTestProjectReference(spec2);

                var request = await ProjectTestHelpers.GetRequestAsync(restoreContext, spec1, spec2);

                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

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

                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var target              = result.LockFile.GetTarget(NuGetFramework.Parse("net45"), null);
                var project2Lib         = target.Libraries.Where(lib => lib.Name == "project2").Single();
                var frameworkReferences = project2Lib.FrameworkAssemblies;

                // Assert
                Assert.True(result.Success);
                Assert.Equal(2, frameworkReferences.Count);
                Assert.Equal("ReferenceA", frameworkReferences[0]);
                Assert.Equal("ReferenceB", frameworkReferences[1]);
            }
        }
Exemplo n.º 13
0
        [InlineData("{0}push")]       // delete package endpoint
        public void DeleteCommand_WithApiKeyFromConfig(string configKeyFormatString)
        {
            // Arrange
            Util.ClearWebCache();
            var testApiKey = Guid.NewGuid().ToString();

            using (var testFolder = TestDirectory.Create())
            {
                using (var server = new MockServer())
                {
                    // Server setup
                    var indexJson = Util.CreateIndexJson();

                    Util.AddFlatContainerResource(indexJson, server);
                    Util.AddPublishResource(indexJson, server);

                    server.Get.Add("/index.json", r =>
                    {
                        return(new Action <HttpListenerResponse>(response =>
                        {
                            response.StatusCode = 200;
                            response.ContentType = "text/javascript";
                            MockServer.SetResponseContent(response, indexJson.ToString());
                        }));
                    });

                    server.Delete.Add("/push/testPackage1/1.1", r =>
                    {
                        var h = r.Headers[ApiKeyHeader];
                        if (!string.Equals(h, testApiKey, StringComparison.OrdinalIgnoreCase))
                        {
                            return(HttpStatusCode.Unauthorized);
                        }

                        return(HttpStatusCode.OK);
                    });

                    server.Start();

                    var configKey = string.Format(configKeyFormatString, server.Uri);

                    var config = $@"<?xml version='1.0' encoding='utf-8'?>
<configuration>
    <packageSources>
        <add key='MockServer' value='{server.Uri}index.json' protocolVersion='3' />
    </packageSources>
    <apikeys>
        <add key='{configKey}' value='{Configuration.EncryptionUtility.EncryptString(testApiKey)}' />
    </apikeys>
</configuration>";

                    var configFileName = Path.Combine(testFolder, "nuget.config");
                    File.WriteAllText(configFileName, config);

                    // Act
                    var args = new[]
                    {
                        "delete",
                        "testPackage1",
                        "1.1.0",
                        "-Source",
                        "MockServer",
                        "-ConfigFile",
                        configFileName,
                        "-NonInteractive"
                    };

                    var result = CommandRunner.Run(
                        NuGetExePath,
                        Directory.GetCurrentDirectory(),
                        string.Join(" ", args),
                        waitForExit: true);

                    server.Stop();

                    // Assert
                    Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                    Assert.Contains("testPackage1 1.1.0 was deleted successfully.", result.Item2);
                }
            }
        }
        public async Task LocalPackageMetadataResourceTests_GetMetadataPrerelease()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };

                var packageA1 = new SimpleTestPackageContext()
                {
                    Id           = "a",
                    Version      = "1.0.0",
                    Dependencies = new List <SimpleTestPackageContext>()
                    {
                        packageX
                    }
                };

                var packageA2 = new SimpleTestPackageContext()
                {
                    Id           = "a",
                    Version      = "2.0.0-preview.12.4+server.a",
                    Dependencies = new List <SimpleTestPackageContext>()
                    {
                        packageX
                    }
                };

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

                SimpleTestPackageUtility.CreatePackages(root, packageContexts);

                var localResource = new FindLocalPackagesResourceV2(root);
                var resource      = new LocalPackageMetadataResource(localResource);

                // Act
                var results = (await resource.GetMetadataAsync(
                                   "A",
                                   includePrerelease: true,
                                   includeUnlisted: false,
                                   log: testLogger,
                                   token: CancellationToken.None))
                              .ToList();

                var package = results.OrderByDescending(p => p.Identity.Version).First();

                // Assert
                Assert.Equal("a", package.Identity.Id);
                Assert.Equal("2.0.0-preview.12.4+server.a", package.Identity.Version.ToFullString());
            }
        }
        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);
                });
            }
        }
Exemplo n.º 16
0
        public async Task RestoreRunner_RestoreWithRuntimeAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);

                spec1 = spec1.EnsureRestoreMetadata();
                spec1.RestoreMetadata.Sources = new List <PackageSource> {
                    new PackageSource(packageSource.FullName)
                };
                spec1.RestoreMetadata.PackagesPath = packagesDir.FullName;
                var dgSpec = new DependencyGraphSpec();
                dgSpec.AddProject(spec1);
                dgSpec.AddRestore("project1");

                var logger    = new TestLogger();
                var lockPath1 = Path.Combine(project1.FullName, "project.assets.json");

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = spec1.RestoreMetadata.PackagesPath,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Log = logger,
                        CachingSourceProvider     = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                        {
                            new DependencyGraphSpecRequestProvider(providerCache, dgSpec)
                        }
                    };

                    restoreContext.Runtimes.Add("linux-x86");

                    // Act
                    var summaries = await RestoreRunner.RunAsync(restoreContext);

                    var success = summaries.All(s => s.Success);

                    var lockFormat = new LockFileFormat();
                    var lockFile   = lockFormat.Read(lockPath1);

                    // Assert
                    Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                    Assert.True(lockFile.Targets.Any(graph => graph.RuntimeIdentifier == "linux-x86"));
                }
            }
        }
        public async Task GetUpdateActionsAsync_WithPackageReferenceProject_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);

                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>());

                PackageSpec packageSpec     = ProjectTestHelpers.GetPackageSpec(projectName, testDirectory);
                var         projectFullPath = packageSpec.RestoreMetadata.ProjectPath;

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


                DependencyGraphSpec projectRestoreInfo = ProjectTestHelpers.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);

                    AddPackageDependency(projectSystemCache, projectNames, packageSpec, packageV1);
                });

                await PerformOperationAsync(async (projectManager) =>
                {
                    IReadOnlyList <ProjectAction> actions = await projectManager.GetUpdateActionsAsync(
                        projectIds,
                        new[] { 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);
                });
            }
        }
            internal PluginResourceProviderPositiveTest(
                string pluginFilePath,
                PluginFileState pluginFileState,
                IEnumerable <PositiveTestExpectation> expectations)
            {
                _expectations   = expectations;
                _pluginFilePath = pluginFilePath;
                _reader         = new Mock <IEnvironmentVariableReader>(MockBehavior.Strict);

                _reader.Setup(x => x.GetEnvironmentVariable(
                                  It.Is <string>(value => value == EnvironmentVariableConstants.PluginPaths)))
                .Returns(pluginFilePath);
                _reader.Setup(x => x.GetEnvironmentVariable(
                                  It.Is <string>(value => value == EnvironmentVariableConstants.DesktopPluginPaths)))
                .Returns((string)null);
                _reader.Setup(x => x.GetEnvironmentVariable(
                                  It.Is <string>(value => value == EnvironmentVariableConstants.CorePluginPaths)))
                .Returns((string)null);
                _reader.Setup(x => x.GetEnvironmentVariable(
                                  It.Is <string>(value => value == EnvironmentVariableConstants.RequestTimeout)))
                .Returns("RequestTimeout");
                _reader.Setup(x => x.GetEnvironmentVariable(
                                  It.Is <string>(value => value == EnvironmentVariableConstants.IdleTimeout)))
                .Returns("IdleTimeout");
                _reader.Setup(x => x.GetEnvironmentVariable(
                                  It.Is <string>(value => value == EnvironmentVariableConstants.HandshakeTimeout)))
                .Returns("HandshakeTimeout");

                _pluginDiscoverer = new Mock <IPluginDiscoverer>(MockBehavior.Strict);

                _pluginDiscoverer.Setup(x => x.Dispose());
                _pluginDiscoverer.Setup(x => x.DiscoverAsync(It.IsAny <CancellationToken>()))
                .ReturnsAsync(new[]
                {
                    new PluginDiscoveryResult(new PluginFile(pluginFilePath, new Lazy <PluginFileState>(() => pluginFileState)))
                });

                _connection = new Mock <IConnection>(MockBehavior.Strict);

                _connection.Setup(x => x.Dispose());
                _connection.SetupGet(x => x.Options)
                .Returns(ConnectionOptions.CreateDefault());

                _connection.SetupGet(x => x.ProtocolVersion)
                .Returns(ProtocolConstants.Version100);

                _connection.Setup(x => x.SendRequestAndReceiveResponseAsync <MonitorNuGetProcessExitRequest, MonitorNuGetProcessExitResponse>(
                                      It.Is <MessageMethod>(m => m == MessageMethod.MonitorNuGetProcessExit),
                                      It.IsNotNull <MonitorNuGetProcessExitRequest>(),
                                      It.IsAny <CancellationToken>()))
                .ReturnsAsync(new MonitorNuGetProcessExitResponse(MessageResponseCode.Success));

                _connection.Setup(x => x.SendRequestAndReceiveResponseAsync <InitializeRequest, InitializeResponse>(
                                      It.Is <MessageMethod>(m => m == MessageMethod.Initialize),
                                      It.IsNotNull <InitializeRequest>(),
                                      It.IsAny <CancellationToken>()))
                .ReturnsAsync(new InitializeResponse(MessageResponseCode.Success));

                foreach (var expectation in expectations)
                {
                    _connection.Setup(x => x.SendRequestAndReceiveResponseAsync <GetOperationClaimsRequest, GetOperationClaimsResponse>(
                                          It.Is <MessageMethod>(m => m == MessageMethod.GetOperationClaims),
                                          It.Is <GetOperationClaimsRequest>(
                                              g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source),
                                          It.IsAny <CancellationToken>()))
                    .ReturnsAsync(new GetOperationClaimsResponse(expectation.OperationClaims.ToArray()));

                    if (expectation.OperationClaims.Any())
                    {
                        _connection.Setup(x => x.SendRequestAndReceiveResponseAsync <SetCredentialsRequest, SetCredentialsResponse>(
                                              It.Is <MessageMethod>(m => m == MessageMethod.SetCredentials),
                                              It.Is <SetCredentialsRequest>(
                                                  g => g.PackageSourceRepository == expectation.SourceRepository.PackageSource.Source),
                                              It.IsAny <CancellationToken>()))
                        .ReturnsAsync(new SetCredentialsResponse(MessageResponseCode.Success));
                    }
                }

                _plugin = new Mock <IPlugin>(MockBehavior.Strict);

                _plugin.Setup(x => x.Dispose());
                _plugin.SetupGet(x => x.Connection)
                .Returns(_connection.Object);
                _plugin.SetupGet(x => x.Id)
                .Returns("id");

                _factory = new Mock <IPluginFactory>(MockBehavior.Strict);

                _factory.Setup(x => x.Dispose());
                _factory.Setup(x => x.GetOrCreateAsync(
                                   It.Is <string>(p => p == pluginFilePath),
                                   It.IsNotNull <IEnumerable <string> >(),
                                   It.IsNotNull <IRequestHandlers>(),
                                   It.IsNotNull <ConnectionOptions>(),
                                   It.IsAny <CancellationToken>()))
                .ReturnsAsync(_plugin.Object);

                _testDirectory = TestDirectory.Create();

                PluginManager = new PluginManager(
                    _reader.Object,
                    new Lazy <IPluginDiscoverer>(() => _pluginDiscoverer.Object),
                    (TimeSpan idleTimeout) => _factory.Object,
                    new Lazy <string>(() => _testDirectory.Path));
                Provider = new PluginResourceProvider(PluginManager);
            }
Exemplo n.º 19
0
        public void NoOpRestoreResult_IsLazy()
        {
            const string lockFileContent = @"{
  ""version"": 1,
  ""targets"": {
    "".NETPlatform,Version=v5.0"": {
      ""System.Runtime/4.0.10-beta-23008"": {
        ""compile"": {
          ""ref/dotnet/System.Runtime.dll"": {}
        }
      }
    }
  },
  ""libraries"": {
    ""System.Runtime/4.0.10-beta-23008"": {
      ""sha512"": ""JkGp8sCzxxRY1GS+p1SEk8WcaT8pu++/5b94ar2i/RaUN/OzkcGP/6OLFUxUf1uar75pUvotpiMawVt1dCEUVA=="",
      ""type"": ""Package"",
      ""files"": [
        ""_rels/.rels"",
        ""System.Runtime.nuspec"",
        ""License.rtf"",
        ""ref/dotnet/System.Runtime.dll"",
        ""ref/net451/_._"",
        ""lib/net451/_._"",
        ""ref/win81/_._"",
        ""lib/win81/_._"",
        ""ref/netcore50/System.Runtime.dll"",
        ""package/services/metadata/core-properties/cdec43993f064447a2d882cbfd022539.psmdcp"",
        ""[Content_Types].xml""
      ]
    }
  },
  ""projectFileDependencyGroups"": {
    """": [
      ""System.Runtime >= 4.0.10-beta-*""
    ],
    "".NETPlatform,Version=v5.0"": []
  }
}
";

            // Arrange
            using (var td = TestDirectory.Create())
            {
                var path = Path.Combine(td, "project.lock.json");
                File.WriteAllText(path, lockFileContent);
                var logger = new TestLogger();
                var result = new NoOpRestoreResult(
                    success: true,
                    lockFilePath: path,
                    new Lazy <LockFile>(() => LockFileUtilities.GetLockFile(path, logger)),
                    cacheFile: new CacheFile("NotSoRandomString"),
                    cacheFilePath: null,
                    projectStyle: ProjectStyle.Unknown,
                    elapsedTime: TimeSpan.MinValue);

                // Act
                var actual = result.LockFile;

                // Assert
                Assert.Equal(1, actual.Libraries.Count);
                Assert.Equal("System.Runtime", actual.Libraries[0].Name);
            }
        }
        public async Task LocalDependencyInfoResource_Basic()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };

                var packageD = new SimpleTestPackageContext()
                {
                    Id      = "d",
                    Version = "1.0.0"
                };

                var packageD2 = new SimpleTestPackageContext()
                {
                    Id      = "d",
                    Version = "2.0.0"
                };

                var packageD3 = new SimpleTestPackageContext()
                {
                    Id      = "d",
                    Version = "0.1.0"
                };

                var packageC = new SimpleTestPackageContext()
                {
                    Id           = "c",
                    Version      = "1.0.0",
                    Dependencies = new List <SimpleTestPackageContext>()
                    {
                        packageD
                    }
                };

                var packageB = new SimpleTestPackageContext()
                {
                    Id           = "b",
                    Version      = "1.0.0",
                    Dependencies = new List <SimpleTestPackageContext>()
                    {
                        packageD2
                    }
                };

                var packageA = new SimpleTestPackageContext()
                {
                    Id           = "a",
                    Version      = "1.0.0",
                    Dependencies = new List <SimpleTestPackageContext>()
                    {
                        packageC, packageB
                    }
                };

                var packageContexts = new SimpleTestPackageContext[]
                {
                    packageA,
                    packageB,
                    packageC,
                    packageD,
                    packageD2,
                    packageD3,
                    packageX
                };

                SimpleTestPackageUtility.CreatePackages(root, packageContexts);

                var source        = Repository.Factory.GetCoreV3(root);
                var localResource = new FindLocalPackagesResourceV2(root);
                var resource      = new LocalDependencyInfoResource(localResource, source);

                // Act
                var resultsA = (await resource.ResolvePackages("a", NuGetFramework.Parse("net46"), NullSourceCacheContext.Instance, testLogger, CancellationToken.None)).ToList();
                var resultsX = (await resource.ResolvePackages("x", NuGetFramework.Parse("net46"), NullSourceCacheContext.Instance, testLogger, CancellationToken.None)).ToList();
                var resultsY = (await resource.ResolvePackages("y", NuGetFramework.Parse("net46"), NullSourceCacheContext.Instance, testLogger, CancellationToken.None)).ToList();

                // Assert
                Assert.Equal(1, resultsA.Count);
                Assert.Equal(packageA.Identity, resultsA[0], PackageIdentity.Comparer);
                Assert.True(resultsA[0].Listed);
                Assert.Contains("a.1.0.0.nupkg", resultsA[0].DownloadUri.LocalPath);
                Assert.Equal(2, resultsA[0].Dependencies.Count());
                Assert.Equal("c", resultsA[0].Dependencies.First().Id);
                Assert.Equal("[1.0.0, )", resultsA[0].Dependencies.First().VersionRange.ToNormalizedString());
                Assert.Equal("b", resultsA[0].Dependencies.Skip(1).First().Id);
                Assert.Equal("[1.0.0, )", resultsA[0].Dependencies.Skip(1).First().VersionRange.ToNormalizedString());

                // no dependencies
                Assert.Equal(1, resultsX.Count);
                Assert.Equal(packageX.Identity, resultsX[0], PackageIdentity.Comparer);
                Assert.True(resultsX[0].Listed);
                Assert.Contains("x.1.0.0.nupkg", resultsX[0].DownloadUri.LocalPath);
                Assert.Equal(0, resultsX[0].Dependencies.Count());

                // not found
                Assert.Equal(0, resultsY.Count);
            }
        }
Exemplo n.º 21
0
        public async Task GetInstalledSatelliteFilesAsync_ReturnsInstalledSatelliteFiles()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var packageIdentity     = new PackageIdentity("A", new NuGetVersion("1.2.3"));
                var packagePathResolver = new PackagePathResolver(testDirectory.Path);
                var packageFileInfo     = await TestPackagesCore.GetRuntimePackageAsync(
                    testDirectory.Path,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString());

                var satellitePackageInfo = await TestPackagesCore.GetSatellitePackageAsync(
                    testDirectory.Path,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString(),
                    language : "fr");

                // Install runtime package
                using (var packageReader = new PackageArchiveReader(File.OpenRead(packageFileInfo.FullName)))
                    using (var packageStream = File.OpenRead(packageFileInfo.FullName))
                    {
                        await PackageExtractor.ExtractPackageAsync(
                            testDirectory.Path,
                            packageStream,
                            packagePathResolver,
                            new PackageExtractionContext(
                                PackageSaveMode.Defaultv2,
                                PackageExtractionBehavior.XmlDocFileSaveMode,
                                clientPolicyContext : null,
                                logger : NullLogger.Instance),
                            CancellationToken.None);
                    }

                // Install satellite package
                using (var packageReader = new PackageArchiveReader(File.OpenRead(satellitePackageInfo.FullName)))
                    using (var packageStream = File.OpenRead(satellitePackageInfo.FullName))
                    {
                        await PackageExtractor.ExtractPackageAsync(
                            testDirectory.Path,
                            packageReader,
                            packageStream,
                            packagePathResolver,
                            new PackageExtractionContext(
                                PackageSaveMode.Defaultv2,
                                PackageExtractionBehavior.XmlDocFileSaveMode,
                                clientPolicyContext : null,
                                logger : NullLogger.Instance),
                            CancellationToken.None);
                    }

                using (var packageReader = new PackageArchiveReader(File.OpenRead(satellitePackageInfo.FullName)))
                {
                    var result = await PackageHelper.GetInstalledSatelliteFilesAsync(
                        packageReader,
                        packagePathResolver,
                        PackageSaveMode.Defaultv3,
                        CancellationToken.None);

                    var runtimePackageDirectory = result.Item1;
                    var satelliteFiles          = result.Item2.ToArray();
                    var packageDirectoryName    = $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}";

                    Assert.Equal(Path.Combine(testDirectory.Path, packageDirectoryName), runtimePackageDirectory);
                    Assert.Equal(1, satelliteFiles.Length);
                    Assert.Equal(Path.Combine(testDirectory.Path, packageDirectoryName, "lib/net45/fr/A.resources.dll"), satelliteFiles[0].FileFullPath);
                }
            }
        }
Exemplo n.º 22
0
 public NuGetUITests(GlobalServiceProvider sp)
 {
     sp.Reset();
     _testDirectory = TestDirectory.Create();
 }
Exemplo n.º 23
0
        public async Task RestoreRunner_BasicRestore_VerifyFailureWritesFilesAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                    ""dependencies"": {
                        ""x"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                spec1 = spec1.EnsureRestoreMetadata();
                spec1.RestoreMetadata.Sources = new List <PackageSource> {
                    new PackageSource(packageSource.FullName)
                };
                spec1.RestoreMetadata.PackagesPath = packagesDir.FullName;
                var dgFile = new DependencyGraphSpec();
                dgFile.AddProject(spec1);
                dgFile.AddRestore("project1");

                var logger   = new TestLogger();
                var lockPath = Path.Combine(project1.FullName, "project.assets.json");

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var packageX = new SimpleTestPackageContext()
                {
                    Id      = "x",
                    Version = "1.0.0"
                };

                packageX.AddFile("build/net45/x.targets");

                var packageY = new SimpleTestPackageContext("y");
                packageX.Dependencies.Add(packageY);

                var yPath = await SimpleTestPackageUtility.CreateFullPackageAsync(packageSource.FullName, packageY);

                await SimpleTestPackageUtility.CreateFullPackageAsync(packageSource.FullName, packageX);

                // y does not exist
                yPath.Delete();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Log = logger,
                        CachingSourceProvider     = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                        {
                            new DependencyGraphSpecRequestProvider(providerCache, dgFile)
                        }
                    };

                    var targetsPath = Path.Combine(project1.FullName, "project1.csproj.nuget.g.targets");
                    var propsPath   = Path.Combine(project1.FullName, "project1.nuget.props");

                    // Act
                    var summaries = await RestoreRunner.RunAsync(restoreContext);

                    var summary = summaries.Single();

                    var targets = TargetsUtility.GetMSBuildPackageImports(targetsPath);

                    // Assert
                    Assert.False(summary.Success);
                    Assert.True(File.Exists(lockPath), lockPath);
                    Assert.True(File.Exists(targetsPath));
                    Assert.False(File.Exists(propsPath));
                    Assert.Equal(1, targets.Count);
                }
            }
        }
Exemplo n.º 24
0
 public PreinstalledRepositoryProviderTests()
 {
     _testDirectory = TestDirectory.Create();
 }
Exemplo n.º 25
0
        public async Task RestoreRunner_BasicRestore_VerifyFailureWritesFiles_NETCoreAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                    ""dependencies"": {
                        ""x"": ""1.0.0""
                    }
                }
              }
            }";

            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);

                var specPath1 = Path.Combine(project1.FullName, "project.json");
                var spec1     = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                spec1.RestoreMetadata = new ProjectRestoreMetadata
                {
                    OutputPath   = Path.Combine(project1.FullName, "obj"),
                    ProjectStyle = ProjectStyle.PackageReference,
                    ProjectName  = "project1",
                    ProjectPath  = Path.Combine(project1.FullName, "project1.csproj")
                };
                spec1.RestoreMetadata.ProjectUniqueName = spec1.RestoreMetadata.ProjectPath;
                spec1.RestoreMetadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45")));
                spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45");
                spec1.FilePath = spec1.RestoreMetadata.ProjectPath;

                var dgSpec = new DependencyGraphSpec();
                dgSpec.AddProject(spec1);
                dgSpec.AddRestore(spec1.RestoreMetadata.ProjectUniqueName);

                var logger     = new TestLogger();
                var assetsPath = Path.Combine(project1.FullName, "obj", "project.assets.json");

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Log = logger,
                        CachingSourceProvider     = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                        {
                            new DependencyGraphSpecRequestProvider(providerCache, dgSpec)
                        }
                    };

                    // Act
                    var summaries = await RestoreRunner.RunAsync(restoreContext);

                    var summary = summaries.Single();

                    // Assert
                    Assert.False(summary.Success);
                    Assert.True(File.Exists(assetsPath), assetsPath);
                    Assert.True(File.Exists(Path.Combine(project1.FullName, "obj", "project1.csproj.nuget.g.props")));
                    Assert.True(File.Exists(Path.Combine(project1.FullName, "obj", "project1.csproj.nuget.g.targets")));
                }
            }
        }
Exemplo n.º 26
0
        public void AddPkg_ArgParsing(string packageOption, string package, string versionOption, string version, string dgFileOption,
                                      string dgFilePath, string projectOption, string project, string frameworkOption, string frameworkString, string sourceOption,
                                      string sourceString, string packageDirectoryOption, string packageDirectory, string noRestoreSwitch, string interactiveSwitch)
        {
            // Arrange
            using (var testDirectory = TestDirectory.Create())
            {
                var projectPath = Path.Combine(testDirectory, project);
                var frameworks  = MSBuildStringUtility.Split(frameworkString);
                var sources     = MSBuildStringUtility.Split(sourceString);
                File.Create(projectPath).Dispose();

                var argList = new List <string>()
                {
                    "add",
                    packageOption,
                    package,
                    versionOption,
                    version,
                    dgFileOption,
                    dgFilePath,
                    projectOption,
                    projectPath
                };

                if (!string.IsNullOrEmpty(frameworkOption))
                {
                    foreach (var framework in frameworks)
                    {
                        argList.Add(frameworkOption);
                        argList.Add(framework);
                    }
                }
                if (!string.IsNullOrEmpty(sourceOption))
                {
                    foreach (var source in sources)
                    {
                        argList.Add(sourceOption);
                        argList.Add(source);
                    }
                }
                if (!string.IsNullOrEmpty(packageDirectoryOption))
                {
                    argList.Add(packageDirectoryOption);
                    argList.Add(packageDirectory);
                }
                if (!string.IsNullOrEmpty(noRestoreSwitch))
                {
                    argList.Add(noRestoreSwitch);
                }
                if (!string.IsNullOrEmpty(interactiveSwitch))
                {
                    argList.Add(interactiveSwitch);
                }

                var logger            = new TestCommandOutputLogger();
                var testApp           = new CommandLineApplication();
                var mockCommandRunner = new Mock <IPackageReferenceCommandRunner>();
                mockCommandRunner
                .Setup(m => m.ExecuteCommand(It.IsAny <PackageReferenceArgs>(), It.IsAny <MSBuildAPIUtility>()))
                .ReturnsAsync(0);

                testApp.Name = "dotnet nuget_test";
                AddPackageReferenceCommand.Register(testApp,
                                                    () => logger,
                                                    () => mockCommandRunner.Object);

                // Act
                var result = testApp.Execute(argList.ToArray());

                XPlatTestUtils.DisposeTemporaryFile(projectPath);

                // Assert
                mockCommandRunner.Verify(m => m.ExecuteCommand(It.Is <PackageReferenceArgs>(p => p.PackageDependency.Id == package &&
                                                                                            p.PackageDependency.VersionRange.OriginalString == version &&
                                                                                            p.ProjectPath == projectPath &&
                                                                                            p.DgFilePath == dgFilePath &&
                                                                                            p.NoRestore == !string.IsNullOrEmpty(noRestoreSwitch) &&
                                                                                            (string.IsNullOrEmpty(frameworkOption) || !string.IsNullOrEmpty(frameworkOption) && p.Frameworks.SequenceEqual(frameworks)) &&
                                                                                            (string.IsNullOrEmpty(sourceOption) || !string.IsNullOrEmpty(sourceOption) && p.Sources.SequenceEqual(MSBuildStringUtility.Split(sourceString))) &&
                                                                                            (string.IsNullOrEmpty(packageDirectoryOption) || !string.IsNullOrEmpty(packageDirectoryOption) && p.PackageDirectory == packageDirectory) && p.Interactive == !string.IsNullOrEmpty(interactiveSwitch)),
                                                               It.IsAny <MSBuildAPIUtility>()));

                Assert.Equal(0, result);
            }
        }
Exemplo n.º 27
0
        public async Task RestoreRunner_BasicRestoreWithConfigFileAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""net45"": {
                }
              }
            }";

            var configFile = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
    <packageSources>
        <add key=""nuget.org"" value=""{0}"" />
    </packageSources>
</configuration>
";

            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();

                File.WriteAllText(Path.Combine(project1.FullName, "project.json"), project1Json);
                File.WriteAllText(Path.Combine(workingDir, "NuGet.Config"), string.Format(configFile, packageSource.FullName));

                var specPath1  = Path.Combine(project1.FullName, "project.json");
                var spec1      = JsonPackageSpecReader.GetPackageSpec(project1Json, "project1", specPath1);
                var configPath = Path.Combine(workingDir, "NuGet.Config");

                var dgFile = new DependencyGraphSpec();
                spec1 = spec1.EnsureRestoreMetadata();
                spec1.RestoreMetadata.ConfigFilePaths = new List <string> {
                    configPath
                };
                spec1.RestoreMetadata.Sources = new List <PackageSource> {
                    new PackageSource(packageSource.FullName)
                };
                spec1.RestoreMetadata.PackagesPath = packagesDir.FullName;

                dgFile.AddProject(spec1);
                dgFile.AddRestore("project1");

                var logger   = new TestLogger();
                var lockPath = Path.Combine(project1.FullName, "project.assets.json");

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = spec1.RestoreMetadata.PackagesPath,
                        ConfigFile           = configPath,
                        Log = logger,
                        CachingSourceProvider     = new CachingSourceProvider(new TestPackageSourceProvider(new List <PackageSource>())),
                        PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>
                        {
                            new DependencyGraphSpecRequestProvider(providerCache, dgFile)
                        }
                    };

                    // Act
                    var summaries = await RestoreRunner.RunAsync(restoreContext);

                    var summary = summaries.Single();

                    // Assert
                    Assert.True(summary.Success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                    Assert.Equal(1, summary.FeedsUsed.Count);
                    Assert.True(File.Exists(lockPath), lockPath);
                }
            }
        }
Exemplo n.º 28
0
        public void GetPackageReferences_WhenDuplicatesOrMetadataSpecified_DuplicatesIgnoredAndMetadataReadCorrectly()
        {
            using (var testDirectory = TestDirectory.Create())
            {
                var project = new MockMSBuildProject(testDirectory)
                {
                    Items = new Dictionary <string, IList <IMSBuildItem> >
                    {
                        ["PackageReference"] = new List <IMSBuildItem>
                        {
                            new MSBuildItem("PackageA", new Dictionary <string, string> {
                                ["Version"] = "1.1.1"
                            }),
                            new MSBuildItem("PackageA", new Dictionary <string, string> {
                                ["Version"] = "2.0.0"
                            }),
                            new MSBuildItem("PackageB", new Dictionary <string, string> {
                                ["Version"] = "1.2.3", ["IsImplicitlyDefined"] = bool.TrueString
                            }),
                            new MSBuildItem("PackageC", new Dictionary <string, string> {
                                ["Version"] = "4.5.6", ["GeneratePathProperty"] = bool.TrueString
                            }),
                            new MSBuildItem("PackageD", new Dictionary <string, string> {
                                ["Version"] = "1.2.3", ["IncludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.Analyzers}"
                            }),
                            new MSBuildItem("PackageE", new Dictionary <string, string> {
                                ["Version"] = "1.2.3", ["PrivateAssets"] = $"{LibraryIncludeFlags.Runtime};{LibraryIncludeFlags.Compile}"
                            }),
                            new MSBuildItem("PackageF", new Dictionary <string, string> {
                                ["Version"] = "1.2.3", ["ExcludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.Analyzers}"
                            }),
                            new MSBuildItem("PackageG", new Dictionary <string, string> {
                                ["Version"] = "1.2.3", ["IncludeAssets"] = $"{LibraryIncludeFlags.Build};{LibraryIncludeFlags.Analyzers};{LibraryIncludeFlags.Compile}", ["ExcludeAssets"] = $"{LibraryIncludeFlags.Analyzers}"
                            }),
                            new MSBuildItem("PackageH", new Dictionary <string, string> {
                                ["Version"] = "1.2.3", ["NoWarn"] = "NU1001;\tNU1006 ; NU3017 "
                            }),
                            new MSBuildItem("PackageI", new Dictionary <string, string> {
                                ["Version"] = null
                            }),
                            new MSBuildItem("PackageJ", new Dictionary <string, string> {
                                ["Version"] = "1.2.4", ["Aliases"] = "Core"
                            }),
                        }
                    }
                };

                var actual = MSBuildStaticGraphRestore.GetPackageReferences(project, false);

                actual.ShouldBeEquivalentTo(new List <LibraryDependency>
                {
                    new LibraryDependency
                    {
                        LibraryRange = new LibraryRange("PackageA", VersionRange.Parse("1.1.1"), LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        AutoReferenced = true,
                        LibraryRange   = new LibraryRange("PackageB", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        GeneratePathProperty = true,
                        LibraryRange         = new LibraryRange("PackageC", VersionRange.Parse("4.5.6"), LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        IncludeType  = LibraryIncludeFlags.Build | LibraryIncludeFlags.Analyzers,
                        LibraryRange = new LibraryRange("PackageD", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        SuppressParent = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.Compile,
                        LibraryRange   = new LibraryRange("PackageE", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        IncludeType  = LibraryIncludeFlags.Runtime | LibraryIncludeFlags.Compile | LibraryIncludeFlags.Native | LibraryIncludeFlags.ContentFiles | LibraryIncludeFlags.BuildTransitive,
                        LibraryRange = new LibraryRange("PackageF", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        IncludeType  = LibraryIncludeFlags.Compile | LibraryIncludeFlags.Build,
                        LibraryRange = new LibraryRange("PackageG", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        LibraryRange = new LibraryRange("PackageH", VersionRange.Parse("1.2.3"), LibraryDependencyTarget.Package),
                        NoWarn       = new List <NuGetLogCode> {
                            NuGetLogCode.NU1001, NuGetLogCode.NU1006, NuGetLogCode.NU3017
                        }
                    },
                    new LibraryDependency
                    {
                        LibraryRange = new LibraryRange("PackageI", VersionRange.All, LibraryDependencyTarget.Package),
                    },
                    new LibraryDependency
                    {
                        LibraryRange = new LibraryRange("PackageJ", VersionRange.Parse("1.2.4"), LibraryDependencyTarget.Package),
                        Aliases      = "Core"
                    }
                });
            }
        }
Exemplo n.º 29
0
        public async Task RestoreRunner_RestoreWithExternalFile_NetCoreOutputAsync()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var targetFrameworkInfo1 = new TargetFrameworkInformation
            {
                FrameworkName = NuGetFramework.Parse("net45")
            };
            var frameworks1 = new[] { targetFrameworkInfo1 };

            var targetFrameworkInfo2 = new TargetFrameworkInformation
            {
                FrameworkName = NuGetFramework.Parse("net45")
            };
            var frameworks2 = new[] { targetFrameworkInfo2 };

            // Create two net45 projects
            var spec1 = new PackageSpec(frameworks1)
            {
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectUniqueName = "project1",
                    ProjectName       = "project1",
                    ProjectStyle      = ProjectStyle.PackageReference
                }
            };

            spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45");

            var spec2 = new PackageSpec(frameworks2)
            {
                RestoreMetadata = new ProjectRestoreMetadata
                {
                    ProjectUniqueName = "project2",
                    ProjectName       = "project2",
                    ProjectStyle      = ProjectStyle.PackageReference
                }
            };

            spec2.RestoreMetadata.OriginalTargetFrameworks.Add("net45");

            var specs = new[] { spec1, spec2 };

            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"));
                var project2      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project2"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();
                project2.Create();
                sources.Add(new PackageSource(packageSource.FullName));

                var projPath1 = Path.Combine(project1.FullName, "project1.csproj");
                var projPath2 = Path.Combine(project2.FullName, "project2.csproj");
                File.WriteAllText(projPath1, string.Empty);
                File.WriteAllText(projPath2, string.Empty);

                spec1.RestoreMetadata.ProjectPath = projPath1;
                spec1.FilePath = projPath1;
                spec1.Name     = "project1";
                spec2.RestoreMetadata.ProjectPath = projPath2;
                spec2.FilePath = projPath1;
                spec2.Name     = "project2";

                var logger   = new TestLogger();
                var objPath1 = Path.Combine(project1.FullName, "obj");
                var objPath2 = Path.Combine(project2.FullName, "obj");

                spec1.RestoreMetadata.OutputPath = objPath1;
                spec2.RestoreMetadata.OutputPath = objPath2;

                spec1.RestoreMetadata.OriginalTargetFrameworks.Add("net45");
                spec2.RestoreMetadata.OriginalTargetFrameworks.Add("net45");

                var lockPath1 = Path.Combine(objPath1, "project.assets.json");
                var lockPath2 = Path.Combine(objPath2, "project.assets.json");

                // Link projects
                spec1.TargetFrameworks.Single().Dependencies.Add(new LibraryDependency()
                {
                    LibraryRange = new LibraryRange()
                    {
                        Name           = "project2",
                        TypeConstraint = LibraryDependencyTarget.ExternalProject
                    }
                });

                spec1.RestoreMetadata.TargetFrameworks.Add(new ProjectRestoreMetadataFrameworkInfo(NuGetFramework.Parse("net45")));
                spec1.RestoreMetadata.TargetFrameworks
                .Single()
                .ProjectReferences
                .Add(new ProjectRestoreReference()
                {
                    ProjectPath       = projPath2,
                    ProjectUniqueName = "project2"
                });

                // Create dg file
                var dgFile = new DependencyGraphSpec();

                foreach (var spec in specs)
                {
                    dgFile.AddRestore(spec.RestoreMetadata.ProjectName);
                    dgFile.AddProject(spec);
                }

                var dgPath = Path.Combine(workingDir, "input.dg");
                dgFile.Save(dgPath);

                var sourceRepos = sources.Select(source => Repository.Factory.GetCoreV3(source.Source)).ToList();

                var providerCache = new RestoreCommandProvidersCache();

                using (var cacheContext = new SourceCacheContext())
                {
                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = packagesDir.FullName,
                        Sources = new List <string>()
                        {
                            packageSource.FullName
                        },
                        Inputs = new List <string>()
                        {
                            dgPath
                        },
                        Log = logger,
                        CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(sources)),
                        RequestProviders      = new List <IRestoreRequestProvider>()
                        {
                            new DependencyGraphFileRequestProvider(providerCache)
                        }
                    };

                    // Act
                    var summaries = await RestoreRunner.RunAsync(restoreContext);

                    var success = summaries.All(s => s.Success);

                    var lockFormat  = new LockFileFormat();
                    var lockFile1   = lockFormat.Read(lockPath1);
                    var project2Lib = lockFile1.Libraries.First();

                    // Assert
                    Assert.True(success, "Failed: " + string.Join(Environment.NewLine, logger.Messages));
                    Assert.True(File.Exists(lockPath1), lockPath1);
                    Assert.True(File.Exists(lockPath2), lockPath2);
                    Assert.Equal("project2", project2Lib.Name);
                }
            }
        }
Exemplo n.º 30
0
        public void DeleteDirectory()
        {
            // Setup
            var fileSystem = new TestFileSystem();
            var directory = new TestDirectory(fileSystem, "\\this\\is\\a\\directory");
            directory.Create();

            // Execute
            directory.Delete();

            // Assert
            Assert.IsFalse(directory.Exists);
        }
        public async Task LocalPackageMetadataResourceTests_VerifyAllFields()
        {
            using (var root = TestDirectory.Create())
            {
                // Arrange
                var testLogger = new TestLogger();

                var nuspec = XDocument.Parse($@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <package>
                        <metadata>
                            <id>a</id>
                            <version>1.0.0-alpha.1.2+5</version>
                            <title>myTitle</title>
                            <authors>a,b,c</authors>
                            <owners>a,b</owners>
                            <description>package description</description>
                            <releaseNotes>notes</releaseNotes>
                            <summary>sum</summary>
                            <language>en-us</language>
                            <projectUrl>http://nuget.org/</projectUrl>
                            <iconUrl>http://nuget.org/nuget.jpg</iconUrl>
                            <licenseUrl>http://nuget.org/license.txt</licenseUrl>
                            <requireLicenseAcceptance>true</requireLicenseAcceptance>
                            <copyright>MIT</copyright>
                            <tags>a b c</tags>
                            <developmentDependency>true</developmentDependency>
                            <dependencies>
                                <group>
                                 <dependency id=""b"" version=""1.0"" />
                                </group>
                                 <group targetFramework=""net461"">
                                </group>
                            </dependencies>
                        </metadata>
                        </package>");

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

                var packageA2 = new SimpleTestPackageContext()
                {
                    Id      = "a",
                    Version = "1.0.0-alpha.1.1"
                };

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

                SimpleTestPackageUtility.CreatePackages(root, packageContexts);

                var localResource = new FindLocalPackagesResourceV2(root);
                var resource      = new LocalPackageMetadataResource(localResource);

                // Act
                var packages = (await resource.GetMetadataAsync(
                                    "A",
                                    includePrerelease: true,
                                    includeUnlisted: false,
                                    log: testLogger,
                                    token: CancellationToken.None))
                               .OrderByDescending(p => p.Identity.Version)
                               .ToList();

                var package = packages.First();

                // Assert
                Assert.Equal(2, packages.Count);
                Assert.Equal("a,b,c", package.Authors);
                Assert.Equal(2, package.DependencySets.Count());
                Assert.Equal("package description", package.Description);
                Assert.Equal(0, package.DownloadCount);
                Assert.Equal(new Uri("http://nuget.org/nuget.jpg"), package.IconUrl);
                Assert.Equal("1.0.0-alpha.1.2+5", package.Identity.Version.ToFullString());
                Assert.Equal(new Uri("http://nuget.org/license.txt"), package.LicenseUrl);
                Assert.Equal("a,b", package.Owners);
                Assert.Equal(new Uri("http://nuget.org/"), package.ProjectUrl);
                Assert.NotNull(package.Published);
                Assert.Null(package.ReportAbuseUrl);
                Assert.True(package.RequireLicenseAcceptance);
                Assert.Equal("sum", package.Summary);
                Assert.Equal("a b c", package.Tags);
                Assert.Equal("myTitle", package.Title);
            }
        }