public async Task DotnetToolTests_ToolPackageWithIncompatibleToolsAssets_FailsAsync()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                string testDirectory    = pathContext.WorkingDirectory;
                var    tfm              = "netcoreapp2.0";
                var    projectName      = "ToolRestoreProject";
                var    workingDirectory = Path.Combine(testDirectory, projectName);
                var    packageSource    = Path.Combine(testDirectory, "packageSource");
                var    rid              = "win-x64";
                var    packageName      = string.Join("ToolPackage-", tfm, rid);
                var    packageVersion   = NuGetVersion.Parse("1.0.0");
                var    packages         = new List <PackageIdentity>()
                {
                    new PackageIdentity(packageName, packageVersion)
                };

                var package = new SimpleTestPackageContext(packageName, packageVersion.OriginalVersion);
                package.Files.Clear();
                package.AddFile($"tools/{tfm}/a.dll");
                package.AddFile($"tools/runtimes/{rid}/ar.dll");
                package.AddFile($"lib/{tfm}/b.dll");
                package.AddFile($"lib/{tfm}/c.dll");
                package.AddFile($"lib/{tfm}/d.dll");
                package.PackageType = PackageType.DotnetTool;
                package.UseDefaultRuntimeAssemblies = false;
                package.PackageTypes.Add(PackageType.DotnetTool);
                await SimpleTestPackageUtility.CreatePackagesAsync(packageSource, package);

                _msbuildFixture.CreateDotnetToolProject(testDirectory, projectName, tfm, rid, packageSource, packages);

                // Act
                var result = _msbuildFixture.RestoreToolProject(workingDirectory, projectName, string.Empty);

                // Assert
                Assert.True(result.Item1 == 1, result.AllOutput);
                Assert.Contains("NU1202", result.AllOutput);
            }
        }
Esempio n. 2
0
        public async Task DotnetTrust_RemoveAction_WrongName_NoChange()
        {
            // Arrange
            var nugetConfigFileName = "NuGet.Config";
            var package             = new SimpleTestPackageContext();

            using (SimpleTestPathContext pathContext = _msbuildFixture.CreateSimpleTestPathContext())
                using (MemoryStream zipStream = await package.CreateAsStreamAsync())
                    using (TrustedTestCert <TestCertificate> trustedTestCert = SigningTestUtility.GenerateTrustedTestCertificate())
                    {
                        var certFingerprint   = SignatureTestUtility.GetFingerprint(trustedTestCert.Source.Cert, HashAlgorithmName.SHA256);
                        var repoServiceIndex  = "https://serviceindex.test/v3/index.json";
                        var signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(trustedTestCert.Source.Cert, package, pathContext.PackageSource, new Uri(repoServiceIndex));

                        var repositoryName      = "nuget";
                        var repositoryWrongName = "nuget11";

                        var config = $@"<?xml version=""1.0"" encoding=""utf-8""?>
                <configuration>
                    <trustedSigners>
                        <repository name = ""{repositoryName}"" serviceIndex=""https://serviceindex.test/v3/index.json"">
                            <certificate fingerprint=""abcdef"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""false""/>
                        </repository>
                    </trustedSigners>
                </configuration>";
                        SettingsTestUtils.CreateConfigurationFile(nugetConfigFileName, pathContext.WorkingDirectory, config);
                        var nugetConfigPath = Path.Combine(pathContext.WorkingDirectory, nugetConfigFileName);

                        // Act
                        CommandRunnerResult resultSync = _msbuildFixture.RunDotnet(
                            pathContext.SolutionRoot,
                            $"nuget trust remove {repositoryWrongName} --configfile {nugetConfigPath}");

                        // Assert
                        resultSync.Success.Should().BeTrue();
                        resultSync.AllOutput.Should().Contain(string.Format(CultureInfo.CurrentCulture, "No trusted signers with the name: '{0}' were found.", repositoryWrongName));
                        SettingsTestUtils.RemoveWhitespace(File.ReadAllText(nugetConfigPath)).Should().Be(SettingsTestUtils.RemoveWhitespace(config));
                    }
        }
        public async void DotnetListPackage_ProjectWithInitialTargets_Succeeds()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(ProjectName, pathContext, "net46");

                var doc = XDocument.Parse(File.ReadAllText(projectA.ProjectPath));

                doc.Root.Add(new XAttribute("InitialTargets", "FirstTarget"));

                doc.Root.Add(new XElement(XName.Get("Target"),
                                          new XAttribute(XName.Get("Name"), "FirstTarget"),
                                          new XElement(XName.Get("Message"),
                                                       new XAttribute(XName.Get("Text"), "I am the first target invoked every time a target is called on this project!"))));

                File.WriteAllText(projectA.ProjectPath, doc.ToString());

                var packageX = XPlatTestUtils.CreatePackage();

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                var addResult = _fixture.RunDotnet(Directory.GetParent(projectA.ProjectPath).FullName,
                                                   $"add {projectA.ProjectPath} package packageX --version 1.0.0 --no-restore");
                Assert.True(addResult.Success);

                var restoreResult = _fixture.RunDotnet(Directory.GetParent(projectA.ProjectPath).FullName,
                                                       $"restore {projectA.ProjectName}.csproj");
                Assert.True(restoreResult.Success);

                var listResult = _fixture.RunDotnet(Directory.GetParent(projectA.ProjectPath).FullName,
                                                    $"list {projectA.ProjectPath} package");

                Assert.True(ContainsIgnoringSpaces(listResult.AllOutput, "packageX1.0.01.0.0"));
            }
        }
        public async Task LocalPackageFileCache_GetFilesTwiceVerifySameInstance()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var cache        = new LocalPackageFileCache();
                var pathResolver = new VersionFolderPathResolver(pathContext.PackageSource);

                var identity = new PackageIdentity("X", NuGetVersion.Parse("1.0.0"));
                var path     = pathResolver.GetInstallPath(identity.Id, identity.Version);

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    pathContext.PackageSource,
                    identity);

                var filesA = cache.GetOrAddFiles(path);
                var filesB = cache.GetOrAddFiles(path);

                // Verify both file lists are the exact same instance
                Assert.Same(filesA.Value, filesB.Value);
                filesA.Value.Should().NotBeEmpty();
            }
        }
Esempio n. 5
0
        public async Task DotnetTrust_RepositoryAction_TryAddSameRepository_Fails()
        {
            // Arrange
            var nugetConfigFileName = "NuGet.Config";
            var package             = new SimpleTestPackageContext();

            using (SimpleTestPathContext pathContext = _msbuildFixture.CreateSimpleTestPathContext())
                using (MemoryStream zipStream = await package.CreateAsStreamAsync())
                    using (TrustedTestCert <TestCertificate> trustedTestCert = SigningTestUtility.GenerateTrustedTestCertificate())
                    {
                        var certFingerprint   = SignatureTestUtility.GetFingerprint(trustedTestCert.Source.Cert, HashAlgorithmName.SHA256);
                        var repoServiceIndex  = "https://serviceindex.test/v3/index.json";
                        var signedPackagePath = await SignedArchiveTestUtility.RepositorySignPackageAsync(trustedTestCert.Source.Cert, package, pathContext.PackageSource, new Uri(repoServiceIndex));

                        var config = $@"<?xml version=""1.0"" encoding=""utf-8""?>
                <configuration>
                </configuration>";
                        SettingsTestUtils.CreateConfigurationFile(nugetConfigFileName, pathContext.WorkingDirectory, config);
                        var nugetConfigPath = Path.Combine(pathContext.WorkingDirectory, nugetConfigFileName);

                        // Act
                        CommandRunnerResult resultAdd = _msbuildFixture.RunDotnet(
                            pathContext.SolutionRoot,
                            $"nuget trust repository nuget {signedPackagePath} --configfile {nugetConfigPath}");

                        // Assert
                        resultAdd.Success.Should().BeTrue();

                        // Try to add same repository again
                        resultAdd = _msbuildFixture.RunDotnet(
                            pathContext.SolutionRoot,
                            $"nuget trust repository nuget {signedPackagePath} --configfile {nugetConfigPath}", ignoreExitCode: true);

                        // Main assert
                        resultAdd.Success.Should().BeFalse();
                        resultAdd.AllOutput.Should().Contain("error: A trusted signer 'nuget' already exists.");
                        resultAdd.AllOutput.Should().NotContain("--help");
                    }
        }
Esempio n. 6
0
        public async void AddPkg_UnconditionalAddAsUpdate_Succcess(string userInputVersionOld, string userInputVersionNew)
        {
            // Arrange

            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, "net46; netcoreapp1.0");
                var packageX = XPlatTestUtils.CreatePackage();

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX);

                var packageArgs   = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id, userInputVersionOld, projectA);
                var commandRunner = new AddPackageReferenceCommandRunner();
                var msBuild       = MsBuild;

                // Create a package ref with the old version
                var result = commandRunner.ExecuteCommand(packageArgs, msBuild)
                             .Result;
                var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;

                packageArgs   = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id, userInputVersionNew, projectA);
                commandRunner = new AddPackageReferenceCommandRunner();

                // Act
                // Create a package ref with the new version
                result = commandRunner.ExecuteCommand(packageArgs, msBuild)
                         .Result;
                projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;

                // Assert
                // Verify that the only package reference is with the new version
                Assert.Equal(0, result);
                Assert.True(XPlatTestUtils.ValidateReference(projectXmlRoot, packageX.Id, userInputVersionNew));
            }
        }
Esempio n. 7
0
        public static List <SimpleTestProjectContext> CreateProjectsFromSpecs(SimpleTestPathContext pathContext, params PackageSpec[] specs)
        {
            var projects = new List <SimpleTestProjectContext>();

            foreach (var spec in specs)
            {
                var project = new SimpleTestProjectContext(spec.Name, ProjectStyle.PackageReference, pathContext.SolutionRoot);

                // Set proj properties
                spec.FilePath = project.ProjectPath;
                spec.RestoreMetadata.OutputPath  = project.OutputPath;
                spec.RestoreMetadata.ProjectPath = project.ProjectPath;

                projects.Add(project);
            }

            var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot, projects.ToArray());

            solution.Create(pathContext.SolutionRoot);

            return(projects);
        }
        public async Task MsbuildRestore_WithCPPCliVcxproj_WithNativeDependency_Succeeds()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set-up packages
                var packageX = new SimpleTestPackageContext("x", "1.0.0");
                packageX.AddFile("build/native/x.targets");
                packageX.AddFile("lib/native/x.dll");
                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    pathContext.PackageSource,
                    packageX);

                // Set up project
                var solution  = new SimpleTestSolutionContext(pathContext.SolutionRoot);
                var framework = NuGetFramework.Parse("net5.0-windows7.0");
                var projectA  = SimpleTestProjectContext.CreateNETCore("projectName", pathContext.SolutionRoot, framework);
                projectA.Properties.Add("CLRSupport", "NetCore");
                //update path to vcxproj
                projectA.ProjectPath = Path.Combine(Path.GetDirectoryName(projectA.ProjectPath), projectA.ProjectName + ".vcxproj");
                projectA.AddPackageToAllFrameworks(packageX);
                solution.Projects.Add(projectA);
                solution.Create(pathContext.SolutionRoot);
                // Act
                var result = _msbuildFixture.RunMsBuild(pathContext.WorkingDirectory, $"/t:restore {pathContext.SolutionRoot}");

                // Assert
                result.Success.Should().BeTrue(because: result.AllOutput);
                File.Exists(projectA.AssetsFileOutputPath).Should().BeTrue(because: result.AllOutput);
                File.Exists(projectA.TargetsOutput).Should().BeTrue(because: result.AllOutput);
                File.Exists(projectA.PropsOutput).Should().BeTrue(because: result.AllOutput);

                var targetsSection = projectA.AssetsFile.Targets.First(e => string.IsNullOrEmpty(e.RuntimeIdentifier));
                targetsSection.Libraries.Should().Contain(e => e.Name.Equals("x"), because: string.Join(",", targetsSection.Libraries));
                var lockFileTargetLibrary = targetsSection.Libraries.First(e => e.Name.Equals("x"));
                lockFileTargetLibrary.CompileTimeAssemblies.Should().Contain("lib/native/x.dll");
                lockFileTargetLibrary.Build.Should().Contain("build/native/x.targets");
            }
        }
        public void UpdatePackageFromPMC(ProjectTemplate projectTemplate)
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                // Arrange
                EnsureVisualStudioHost();
                var solutionService = VisualStudio.Get <SolutionService>();

                solutionService.CreateEmptySolution("TestSolution", pathContext.SolutionRoot);
                var project = solutionService.AddProject(ProjectLanguage.CSharp, projectTemplate, ProjectTargetFramework.V46, "TestProject");
                project.Build();

                var packageName     = "TestPackage";
                var packageVersion1 = "1.0.0";
                var packageVersion2 = "2.0.0";
                Utils.CreatePackageInSource(pathContext.PackageSource, packageName, packageVersion1);
                Utils.CreatePackageInSource(pathContext.PackageSource, packageName, packageVersion2);

                var nugetTestService = GetNuGetTestService();
                Assert.True(nugetTestService.EnsurePackageManagerConsoleIsOpen());

                var nugetConsole = nugetTestService.GetPackageManagerConsole(project.UniqueName);

                Assert.True(nugetConsole.InstallPackageFromPMC(packageName, packageVersion1));
                Assert.True(Utils.IsPackageInstalled(nugetConsole, project.FullPath, packageName, packageVersion1));
                project.Build();

                Assert.True(nugetConsole.UpdatePackageFromPMC(packageName, packageVersion2));
                Assert.True(Utils.IsPackageInstalled(nugetConsole, project.FullPath, packageName, packageVersion2));
                Assert.False(Utils.IsPackageInstalled(nugetConsole, project.FullPath, packageName, packageVersion1));
                project.Build();

                Assert.True(VisualStudio.HasNoErrorsInErrorList());
                Assert.True(VisualStudio.HasNoErrorsInOutputWindows());

                nugetConsole.Clear();
                solutionService.Save();
            }
        }
Esempio n. 10
0
        public async Task Verify_AuthorSignedPackage_WithAuthorItemTrustedCertificate_Succeeds(string allowUntrustedRoot, bool verifyCertificateFingerprint)
        {
            // Arrange
            TrustedTestCert <TestCertificate> cert = _testFixture.TrustedTestCertificateChain.Leaf;

            using (var pathContext = new SimpleTestPathContext())
            {
                var    nupkg         = new SimpleTestPackageContext("A", "1.0.0");
                string testDirectory = pathContext.WorkingDirectory;
                await SimpleTestPackageUtility.CreatePackagesAsync(testDirectory, nupkg);

                //Act
                string certificateFingerprintString = SignatureTestUtility.GetFingerprint(cert.Source.Cert, HashAlgorithmName.SHA256);
                string signedPackagePath            = await SignedArchiveTestUtility.AuthorSignPackageAsync(cert.Source.Cert, nupkg, testDirectory);

                // Arrange
                string trustedSignersSectionContent = $@"
    <trustedSigners>
        <author name=""signed"">
            <certificate fingerprint=""{certificateFingerprintString}"" hashAlgorithm=""SHA256"" allowUntrustedRoot=""{allowUntrustedRoot}"" />
        </author>
    </trustedSigners>
";
                SimpleTestSettingsContext.AddSectionIntoNuGetConfig(testDirectory, trustedSignersSectionContent, "configuration");
                string fingerprint = verifyCertificateFingerprint ? $"-CertificateFingerprint {certificateFingerprintString};def" : string.Empty;

                // Act
                CommandRunnerResult verifyResult = CommandRunner.Run(
                    _nugetExePath,
                    testDirectory,
                    $"verify {signedPackagePath} -Signatures {fingerprint}",
                    waitForExit: true);

                // Assert
                // For certificate with trusted root setting allowUntrustedRoot to true/false doesn't matter
                verifyResult.Success.Should().BeTrue(because: verifyResult.AllOutput);
                verifyResult.AllOutput.Should().Contain(_noTimestamperWarningCode);
            }
        }
Esempio n. 11
0
        public void RestoreUAP_NoPackageReferences_VerifyRestoreStyleIsUsed()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var projectA = SimpleTestProjectContext.CreateLegacyPackageReference(
                    "a",
                    pathContext.SolutionRoot,
                    NuGetFramework.AnyFramework);

                projectA.Properties.Add("TargetPlatformIdentifier", "UAP");
                projectA.Properties.Add("TargetPlatformVersion", "10.0.14393.0");
                projectA.Properties.Add("TargetPlatformMinVersion", "10.0.10586.0");
                projectA.Properties.Add("RestoreProjectStyle", "PackageReference");

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

                // Act
                var r = RestoreSolution(pathContext);

                var dgPath = Path.Combine(pathContext.WorkingDirectory, "out.dg");
                var dgSpec = DependencyGraphSpec.Load(dgPath);

                var propsXML  = XDocument.Load(projectA.PropsOutput);
                var styleNode = propsXML.Root.Elements().First().Elements(XName.Get("NuGetProjectStyle", "http://schemas.microsoft.com/developer/msbuild/2003")).FirstOrDefault();

                var projectSpec = dgSpec.Projects.Single();

                // Assert
                Assert.Equal(ProjectStyle.PackageReference, projectSpec.RestoreMetadata.ProjectStyle);
                Assert.Equal("PackageReference", styleNode.Value);
                Assert.Equal(NuGetFramework.Parse("UAP10.0.10586.0"), projectSpec.TargetFrameworks.Single().FrameworkName);
            }
        }
        public MsbuildIntegrationTestFixture()
        {
            string testAssemblyPath = Path.GetFullPath(Assembly.GetExecutingAssembly().Location);

            _cliDirectory = TestDotnetCLiUtility.CopyAndPatchLatestDotnetCli(testAssemblyPath);
            var dotnetExecutableName = RuntimeEnvironmentHelper.IsWindows ? "dotnet.exe" : "dotnet";

            TestDotnetCli = Path.Combine(_cliDirectory, dotnetExecutableName);

            var sdkPath = Directory.EnumerateDirectories(Path.Combine(_cliDirectory, "sdk"))
                          .Where(d => !string.Equals(Path.GetFileName(d), "NuGetFallbackFolder", StringComparison.OrdinalIgnoreCase))
                          .Single();

            SdkDirectory    = new DirectoryInfo(sdkPath);
            MsBuildSdksPath = Path.Combine(sdkPath, "Sdks");

            _templateDirectory = new SimpleTestPathContext();
            TestDotnetCLiUtility.WriteGlobalJson(_templateDirectory.WorkingDirectory);

            // some project templates use implicit packages. For example, class libraries targeting netstandard2.0
            // will have an implicit package reference for NETStandard.Library, and its dependencies.
            // .NET Core SDK 3.0 and later no longer ship these packages in a NuGetFallbackFolder. Therefore, we need
            // to be able to download these packages. We'll download it once into the template cache's global packages
            // folder, and then use that as a local source for individual tests, to minimise network access.
            var addSourceArgs = new AddSourceArgs()
            {
                Configfile = _templateDirectory.NuGetConfig,
                Name       = "nuget.org",
                Source     = "https://api.nuget.org/v3/index.json"
            };

            AddSourceRunner.Run(addSourceArgs, () => NullLogger.Instance);

            _processEnvVars.Add("MSBuildSDKsPath", MsBuildSdksPath);
            _processEnvVars.Add("UseSharedCompilation", "false");
            _processEnvVars.Add("DOTNET_MULTILEVEL_LOOKUP", "0");
            _processEnvVars.Add("MSBUILDDISABLENODEREUSE ", "true");
        }
        public void ListCommand_InvalidInput_V2_NonExistent(string invalidInput)
        {
            // Arrange
            var nugetexe = Util.GetNuGetExePath();

            // Act
            using (var pathContext = new SimpleTestPathContext())
            {
                var args   = "list test -Source " + invalidInput;
                var result = CommandRunner.Run(
                    nugetexe,
                    pathContext.SolutionRoot,
                    args,
                    waitForExit: true);

                // Assert
                Assert.True(
                    result.Item1 != 0,
                    "The run did not fail as desired. Simply got this output:" + result.Item2);

                Assert.Contains($"Unable to load the service index for source {invalidInput}.", result.Item3);
            }
        }
Esempio n. 14
0
        public static SimpleTestProjectContext CreateProject(string projectName,
                                                             SimpleTestPathContext pathContext,
                                                             SimpleTestPackageContext package,
                                                             string projectFrameworks,
                                                             string packageFramework = null)
        {
            var project = SimpleTestProjectContext.CreateNETCoreWithSDK(
                projectName: projectName,
                solutionRoot: pathContext.SolutionRoot,
                isToolingVersion15: true,
                frameworks: MSBuildStringUtility.Split(projectFrameworks));

            if (packageFramework == null)
            {
                project.AddPackageToAllFrameworks(package);
            }
            else
            {
                project.AddPackageToFramework(packageFramework, package);
            }
            project.Save();
            return(project);
        }
Esempio n. 15
0
        public async Task DotnetSign_SignPackageWithTrustedCertificate_SucceedsAsync()
        {
            // Arrange
            using (SimpleTestPathContext pathContext = _msbuildFixture.CreateSimpleTestPathContext())
            {
                await SimpleTestPackageUtility.CreatePackagesAsync(
                    pathContext.PackageSource,
                    new SimpleTestPackageContext("PackageA", "1.0.0"));

                string packageFilePath = Path.Combine(pathContext.PackageSource, "PackageA.1.0.0.nupkg");
                IX509StoreCertificate storeCertificate = _signFixture.DefaultCertificate;

                // Act
                CommandRunnerResult result = _msbuildFixture.RunDotnet(
                    pathContext.PackageSource,
                    GetDefaultArgs(packageFilePath, storeCertificate),
                    ignoreExitCode: true);

                // Assert
                result.Success.Should().BeTrue(because: result.AllOutput);
                result.AllOutput.Should().Contain(_noTimestamperWarningCode);
            }
        }
        public void Resolve_WhenPackageExists_ReturnsSucceededSdkResult()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var sdkReference = new SdkReference(PackageA, VersionOnePointZero, minimumVersion: null);
                var package      = new SimpleTestPackageContext(sdkReference.Name, sdkReference.Version);
                package.AddFile("Sdk/Sdk.props", "<Project />");
                package.AddFile("Sdk/Sdk.targets", "<Project />");
                SimpleTestPackageUtility.CreateFolderFeedV3Async(pathContext.PackageSource, PackageSaveMode.Defaultv3, package).Wait();
                var sdkResolverContext = new MockSdkResolverContext(pathContext.WorkingDirectory);
                var sdkResultFactory   = new MockSdkResultFactory();
                var sdkResolver        = new NuGetSdkResolver();

                MockSdkResult result = sdkResolver.Resolve(sdkReference, sdkResolverContext, sdkResultFactory) as MockSdkResult;

                result.Should().NotBeNull();
                result.Success.Should().BeTrue();
                result.Path.Should().Be(Path.Combine(pathContext.UserPackagesFolder, sdkReference.Name.ToLowerInvariant(), sdkReference.Version, "Sdk"));
                result.Version.Should().Be(sdkReference.Version);
                result.Errors.Should().BeEmpty();
                result.Warnings.Should().BeEmpty();
            }
        }
        public void ResponseFileMultipleArgs()
        {
            using (var workingDirectory = new SimpleTestPathContext().WorkingDirectory)
            {
                // Arrange
                var testArgs            = new string[] { "/arg1", "/arg2", "@responseFile1.rsp", "/arg3" };
                var responseFilePath    = "responseFile1.rsp";
                var responseFileArg1    = "/responseFileArg1";
                var responseFileArg2    = "/responseFileArg2";
                var responseFileContent = string.Format("{0} {1}", responseFileArg1, responseFileArg2);
                CreateResponseFile(responseFilePath, responseFileContent);

                // Act
                var parsedArgs = ParseArgs(testArgs);

                // Assert
                Assert.Equal(testArgs[0], parsedArgs[0]);
                Assert.Equal(testArgs[1], parsedArgs[1]);
                Assert.Equal(responseFileArg1, parsedArgs[2]);
                Assert.Equal(responseFileArg2, parsedArgs[3]);
                Assert.Equal(testArgs[3], parsedArgs[4]);
            }
        }
Esempio n. 18
0
        private static CommandRunnerResult RestoreSolution(SimpleTestPathContext pathContext, int exitCode = 0)
        {
            var nugetexe = Util.GetNuGetExePath();

            string[] args = new string[] {
                "restore",
                pathContext.SolutionRoot,
                "-Verbosity",
                "detailed"
            };

            // Act
            var r = CommandRunner.Run(
                nugetexe,
                pathContext.WorkingDirectory.Path,
                string.Join(" ", args),
                waitForExit: true);

            // Assert
            Assert.True(exitCode == r.ExitCode, r.Errors + "\n\n" + r.Output);

            return(r);
        }
        public async Task LocalPackageFileCache_GetNuspecTwiceVerifySameInstance()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var cache        = new LocalPackageFileCache();
                var pathResolver = new VersionFolderPathResolver(pathContext.PackageSource);

                var identity = new PackageIdentity("X", NuGetVersion.Parse("1.0.0"));

                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    pathContext.PackageSource,
                    identity);

                var nuspec   = pathResolver.GetManifestFilePath(identity.Id, identity.Version);
                var expanded = pathResolver.GetInstallPath(identity.Id, identity.Version);

                var result1 = cache.GetOrAddNuspec(nuspec, expanded);
                var result2 = cache.GetOrAddNuspec(nuspec, expanded);

                Assert.Same(result1.Value, result2.Value);
                result1.Value.GetIdentity().Should().Be(identity);
            }
        }
Esempio n. 20
0
        public void MockServer_RestorePRVerifySessionId()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var nugetexe = Util.GetNuGetExePath();

                var packageA = new FileInfo(Util.CreateTestPackage("a", "1.0.0", pathContext.PackageSource));
                var packageB = new FileInfo(Util.CreateTestPackage("b", "1.0.0", pathContext.PackageSource));

                var project = SimpleTestProjectContext.CreateNETCore("proj", pathContext.SolutionRoot, NuGetFramework.Parse("net46"));

                project.AddPackageToAllFrameworks(new SimpleTestPackageContext("a", "1.0.0"));
                project.AddPackageToAllFrameworks(new SimpleTestPackageContext("b", "1.0.0"));

                project.Save();

                var ids = new List <string>();

                using (var server = Util.CreateMockServer(new[] { packageA, packageB }))
                {
                    server.RequestObserver = context =>
                    {
                        ids.Add(context.Request.Headers.Get(ProtocolConstants.SessionId));
                    };

                    server.Start();

                    var result = Util.Restore(pathContext, project.ProjectPath, 0, "-Source", server.Uri + "nuget");

                    result.Success.Should().BeTrue();

                    ids.Distinct().Count().Should().Be(1, "all requests should be in the same session");
                    ids.All(s => !string.IsNullOrEmpty(s) && Guid.TryParse(s, out var r)).Should().BeTrue("the values should guids");
                }
            }
        }
Esempio n. 21
0
        public void GivenAnUnknownPackageVerifyError()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                // Set up solution, project, and packages
                var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);

                var projectA = SimpleTestProjectContext.CreateNETCore(
                    "a",
                    pathContext.SolutionRoot,
                    NuGetFramework.Parse("NETStandard1.5"));

                var packageB = new SimpleTestPackageContext("b", "9.0.0");

                projectA.AddPackageToAllFrameworks(packageB);

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

                // Act
                var r           = Util.Restore(pathContext, projectA.ProjectPath, expectedExitCode: 1);
                var output      = r.Item2 + " " + r.Item3;
                var reader      = new LockFileFormat();
                var lockFileObj = reader.Read(projectA.AssetsFileOutputPath);

                // Assert
                Assert.NotNull(lockFileObj);
                Assert.Equal(1, lockFileObj.LogMessages.Count());
                Assert.Contains("Unable to find package b. No packages exist with this id in source(s): source",
                                lockFileObj.LogMessages.First().Message,
                                StringComparison.OrdinalIgnoreCase);
                Assert.Contains("Unable to find package b. No packages exist with this id in source(s): source",
                                output,
                                StringComparison.OrdinalIgnoreCase);
            }
        }
        public async void DotnetListPackage_Transitive()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var projectA = XPlatTestUtils.CreateProject(ProjectName, pathContext, "net46");

                var packageX = XPlatTestUtils.CreatePackage();
                var packageY = XPlatTestUtils.CreatePackage(packageId: "packageY");
                packageX.Dependencies.Add(packageY);

                // Generate Package
                await SimpleTestPackageUtility.CreateFolderFeedV3Async(
                    pathContext.PackageSource,
                    PackageSaveMode.Defaultv3,
                    packageX,
                    packageY);


                var addResult = _fixture.RunDotnet(Directory.GetParent(projectA.ProjectPath).FullName,
                                                   $"add {projectA.ProjectPath} package packageX --no-restore");
                Assert.True(addResult.Success);

                var restoreResult = _fixture.RunDotnet(Directory.GetParent(projectA.ProjectPath).FullName,
                                                       $"restore {projectA.ProjectName}.csproj");
                Assert.True(restoreResult.Success);

                var listResult = _fixture.RunDotnet(Directory.GetParent(projectA.ProjectPath).FullName,
                                                    $"list {projectA.ProjectPath} package");

                Assert.False(ContainsIgnoringSpaces(listResult.AllOutput, "packageY"));

                listResult = _fixture.RunDotnet(Directory.GetParent(projectA.ProjectPath).FullName,
                                                $"list {projectA.ProjectPath} package --include-transitive");

                Assert.True(ContainsIgnoringSpaces(listResult.AllOutput, "packageY"));
            }
        }
Esempio n. 23
0
        public async void AddPkg_UnconditionalAddWithPackageDirectory_Success()
        {
            // Arrange

            using (var tempGlobalPackagesDirectory = TestDirectory.Create())
                using (var pathContext = new SimpleTestPathContext())
                {
                    var projectA = XPlatTestUtils.CreateProject(projectName, pathContext, "net46");
                    var packageX = XPlatTestUtils.CreatePackage();

                    // Generate Package
                    await SimpleTestPackageUtility.CreateFolderFeedV3(
                        pathContext.PackageSource,
                        PackageSaveMode.Defaultv3,
                        packageX);

                    var packageArgs = XPlatTestUtils.GetPackageReferenceArgs(packageX.Id,
                                                                             packageX.Version,
                                                                             projectA,
                                                                             packageDirectory: tempGlobalPackagesDirectory.Path);
                    var commandRunner = new AddPackageReferenceCommandRunner();

                    // Act
                    var result = commandRunner.ExecuteCommand(packageArgs, MsBuild)
                                 .Result;
                    var projectXmlRoot = XPlatTestUtils.LoadCSProj(projectA.ProjectPath).Root;
                    var itemGroup      = XPlatTestUtils.GetItemGroupForAllFrameworks(projectXmlRoot);

                    // Assert
                    Assert.Equal(0, result);
                    Assert.NotNull(itemGroup);
                    Assert.True(XPlatTestUtils.ValidateReference(itemGroup, packageX.Id, packageX.Version));

                    // Since user provided packge directory, assert if package is present
                    Assert.True(XPlatTestUtils.ValidatePackageDownload(tempGlobalPackagesDirectory.Path, packageX));
                }
        }
Esempio n. 24
0
        public void MockServer_RestorePCVerifySessionId()
        {
            // Arrange
            using (var pathContext = new SimpleTestPathContext())
            {
                var nugetexe = Util.GetNuGetExePath();

                var packageA = new FileInfo(Util.CreateTestPackage("a", "1.0.0", pathContext.PackageSource));
                var packageB = new FileInfo(Util.CreateTestPackage("b", "1.0.0", pathContext.PackageSource));

                Util.CreateFile(pathContext.SolutionRoot, "packages.config",
                                @"<packages>
  <package id=""a"" version=""1.0.0"" targetFramework=""net45"" />
  <package id=""b"" version=""1.0.0"" targetFramework=""net45"" />
</packages>");

                var ids = new List <string>();

                using (var server = Util.CreateMockServer(new[] { packageA, packageB }))
                {
                    server.RequestObserver = context =>
                    {
                        ids.Add(context.Request.Headers.Get(ProtocolConstants.SessionId));
                    };

                    server.Start();

                    var result = Util.Restore(pathContext, Path.Combine(pathContext.SolutionRoot, "packages.config"), 0, "-Source", server.Uri + "nuget");

                    result.Success.Should().BeTrue();

                    // Not all ids will be in the same session, this is due to how cache contexts are shared for packages.config
                    ids.Distinct().Count().Should().BeLessThan(ids.Count(), "Verify some requests share the same cache context and session id.");
                    ids.All(s => !string.IsNullOrEmpty(s) && Guid.TryParse(s, out var r)).Should().BeTrue("the values should guids");
                }
            }
        }
Esempio n. 25
0
        public async Task Restore_WithHttpSource_Warns()
        {
            // Arrange
            using var pathContext = new SimpleTestPathContext();
            // Set up solution, project, and packages
            var solution = new SimpleTestSolutionContext(pathContext.SolutionRoot);
            var packageA = new SimpleTestPackageContext("a", "1.0.0");
            await SimpleTestPackageUtility.CreateFolderFeedV3Async(pathContext.PackageSource, packageA);

            pathContext.Settings.AddSource("http-feed", "http://api.source/index.json");
            pathContext.Settings.AddSource("https-feed", "https://api.source/index.json");

            var net461   = NuGetFramework.Parse("net461");
            var projectA = new SimpleTestProjectContext(
                "a",
                ProjectStyle.PackagesConfig,
                pathContext.SolutionRoot);

            projectA.Frameworks.Add(new SimpleTestProjectFrameworkContext(net461));
            var projectAPackages = Path.Combine(pathContext.SolutionRoot, "packages");

            Util.CreateFile(Path.GetDirectoryName(projectA.ProjectPath), "packages.config",
                            @"<packages>
  <package id=""A"" version=""1.0.0"" targetFramework=""net461"" />
</packages>");

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

            // Act
            var result = RunRestore(pathContext, _successExitCode);

            // Assert
            result.Success.Should().BeTrue();
            Assert.Contains($"Added package 'A.1.0.0' to folder '{projectAPackages}'", result.Output);
            Assert.Contains("You are running the 'restore' operation with an 'http' source, 'http://api.source/index.json'. Support for 'http' sources will be removed in a future version.", result.Output);
        }
Esempio n. 26
0
        public MsbuildIntegrationTestFixture()
        {
            _cliDirectory = CopyLatestCliForPack();
            var dotnetExecutableName = RuntimeEnvironmentHelper.IsWindows ? "dotnet.exe" : "dotnet";

            TestDotnetCli = Path.Combine(_cliDirectory, dotnetExecutableName);

            var sdkPath = Directory.EnumerateDirectories(Path.Combine(_cliDirectory, "sdk")).Single();

#if NETCOREAPP5_0
            // TODO - remove when shipping. See https://github.com/NuGet/Home/issues/8952
            PatchSDKWithCryptographyDlls(sdkPath);
#endif

            MsBuildSdksPath = Path.Combine(sdkPath, "Sdks");

            _templateDirectory = new SimpleTestPathContext();
            WriteGlobalJson(_templateDirectory.WorkingDirectory);

            // some project templates use implicit packages. For example, class libraries targeting netstandard2.0
            // will have an implicit package reference for NETStandard.Library, and its dependencies.
            // .NET Core SDK 3.0 and later no longer ship these packages in a NuGetFallbackFolder. Therefore, we need
            // to be able to download these packages. We'll download it once into the template cache's global packages
            // folder, and then use that as a local source for individual tests, to minimise network access.
            var addSourceArgs = new AddSourceArgs()
            {
                Configfile = _templateDirectory.NuGetConfig,
                Name       = "nuget.org",
                Source     = "https://api.nuget.org/v3/index.json"
            };
            AddSourceRunner.Run(addSourceArgs, () => NullLogger.Instance);

            _processEnvVars.Add("MSBuildSDKsPath", MsBuildSdksPath);
            _processEnvVars.Add("UseSharedCompilation", "false");
            _processEnvVars.Add("DOTNET_MULTILEVEL_LOOKUP", "0");
            _processEnvVars.Add("MSBUILDDISABLENODEREUSE ", "true");
        }
Esempio n. 27
0
        public static CommandRunnerResult RunCommand(SimpleTestPathContext pathContext, string nugetExe, int expectedExitCode = 0, params string[] arguments)
        {
            // Store the dg file for debugging
            var dgPath  = Path.Combine(pathContext.WorkingDirectory, "out.dg");
            var envVars = new Dictionary <string, string>()
            {
                { "NUGET_PERSIST_DG", "true" },
                { "NUGET_PERSIST_DG_PATH", dgPath },
                { "NUGET_HTTP_CACHE_PATH", pathContext.HttpCacheFolder }
            };

            // Act
            var r = CommandRunner.Run(
                nugetExe,
                pathContext.WorkingDirectory.Path,
                string.Join(" ", arguments),
                waitForExit: true,
                environmentVariables: envVars);

            // Assert
            Assert.True(expectedExitCode == r.ExitCode, r.Errors + "\n\n" + r.Output);

            return(r);
        }
Esempio n. 28
0
        public void SetApiKey_WithSpecifiedSource_SetApiKeyBySourceKey(string serverUri)
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                // Add source into NuGet.Config file
                SimpleTestSettingsContext settings = pathContext.Settings;
                var    packageSourcesSection       = SimpleTestSettingsContext.GetOrAddSection(settings.XML, ConfigurationConstants.PackageSources);
                string sourceKey = serverUri.Contains("random") ? "random" : serverUri.Contains("contos") ? "contoso" : "nuget.org";
                SimpleTestSettingsContext.AddEntry(packageSourcesSection, sourceKey, serverUri);
                settings.Save();

                var testApiKey = Guid.NewGuid().ToString();

                // Act
                var result = CommandRunner.Run(
                    NuGetExePath,
                    pathContext.WorkingDirectory,
                    $"setApiKey {testApiKey} -Source {sourceKey} -ConfigFile {settings.ConfigPath}",
                    waitForExit: true);

                var iSettings = Configuration.Settings.LoadDefaultSettings(
                    Path.GetDirectoryName(settings.ConfigPath),
                    Path.GetFileName(settings.ConfigPath),
                    null);

                // Assert
                Assert.True(0 == result.ExitCode, $"{result.Output} {result.Errors}");
                Assert.Contains($"The API Key '{testApiKey}' was saved for '{serverUri}'", result.Output);
                Assert.DoesNotContain($"symbol", result.Output);

                var actualApiKey = SettingsUtility.GetDecryptedValueForAddItem(iSettings, ConfigurationConstants.ApiKeys, serverUri);
                Assert.Equal(testApiKey, actualApiKey);
                XElement apiKeySection = SimpleTestSettingsContext.GetOrAddSection(XmlUtility.Load(settings.ConfigPath), ConfigurationConstants.ApiKeys);
                Assert.Equal(1, apiKeySection.Elements().Count());
            }
        }
Esempio n. 29
0
        public void TestVerbosityQuiet_DoesNotShowInfoMessages()
        {
            using (var pathContext = new SimpleTestPathContext())
            {
                var workingPath = pathContext.WorkingDirectory;
                var settings    = pathContext.Settings;

                // Arrange
                var args = new string[]
                {
                    "nuget",
                    "add",
                    "source",
                    "https://source.test",
                    "--name",
                    "test_source",
                    "--verbosity",
                    "Quiet",
                    "--configfile",
                    settings.ConfigPath
                };

                // Act
                var result = _fixture.RunDotnet(workingPath, string.Join(" ", args), ignoreExitCode: true);

                // Assert
                Assert.True(result.ExitCode == 0);
                // Ensure that no messages are shown with Verbosity as Quiet
                Assert.Equal(string.Empty, result.Output);
                var loadedSettings        = Settings.LoadDefaultSettings(root: workingPath, configFileName: null, machineWideSettings: null);
                var packageSourcesSection = loadedSettings.GetSection("packageSources");
                var sourceItem            = packageSourcesSection?.GetFirstItemWithAttribute <SourceItem>("key", "test_source");

                Assert.Equal("https://source.test", sourceItem.GetValueAsPath());
            }
        }
Esempio n. 30
0
        public async Task InstallPackageFromAnotherProcessVerifyCacheIsClearedAsync()
        {
            // Arrange
            var logger = new TestLogger();

            using (var cacheContext = new SourceCacheContext())
                using (var pathContext = new SimpleTestPathContext())
                {
                    var tfi = new List <TargetFrameworkInformation>
                    {
                        new TargetFrameworkInformation()
                        {
                            FrameworkName = NuGetFramework.Parse("net462")
                        }
                    };

                    var spec = NETCoreRestoreTestUtility.GetProject(projectName: "projectA", framework: "net46");
                    spec.Dependencies.Add(new LibraryDependency()
                    {
                        LibraryRange = new LibraryRange("a", VersionRange.Parse("1.0.0"), LibraryDependencyTarget.Package)
                    });

                    var project = NETCoreRestoreTestUtility.CreateProjectsFromSpecs(pathContext, spec).Single();

                    var packageA = new SimpleTestPackageContext("a");
                    await SimpleTestPackageUtility.CreatePackagesAsync(pathContext.PackageSource, packageA);

                    // Create dg file
                    var dgFile = new DependencyGraphSpec();
                    dgFile.AddProject(spec);
                    dgFile.AddRestore(spec.RestoreMetadata.ProjectUniqueName);

                    dgFile.Save(Path.Combine(pathContext.WorkingDirectory, "out.dg"));

                    var providerCache = new RestoreCommandProvidersCache();
                    var sources       = new List <string>()
                    {
                        pathContext.PackageSource
                    };

                    var restoreContext = new RestoreArgs()
                    {
                        CacheContext         = cacheContext,
                        DisableParallel      = true,
                        GlobalPackagesFolder = pathContext.UserPackagesFolder,
                        Sources = sources,
                        Log     = logger,
                        CachingSourceProvider = new CachingSourceProvider(new TestPackageSourceProvider(new List <PackageSource>()
                        {
                            new PackageSource(pathContext.PackageSource)
                        })),
                        PreLoadedRequestProviders = new List <IPreLoadedRestoreRequestProvider>()
                        {
                            new DependencyGraphSpecRequestProvider(providerCache, dgFile)
                        }
                    };

                    var request   = (await RestoreRunner.GetRequests(restoreContext)).Single();
                    var providers = providerCache.GetOrCreate(pathContext.UserPackagesFolder, sources, new List <SourceRepository>(), cacheContext, logger, false);
                    var command   = new RestoreCommand(request.Request);

                    // Add to cache before install on all providers
                    var globalPackages = providers.GlobalPackages;
                    var packages       = globalPackages.FindPackagesById("a");
                    packages.Should().BeEmpty("has not been installed yet");

                    foreach (var local in providers.LocalProviders)
                    {
                        await local.GetDependenciesAsync(new LibraryIdentity("a", NuGetVersion.Parse("1.0.0"), LibraryType.Package), NuGetFramework.Parse("net46"), cacheContext, logger, CancellationToken.None);
                    }

                    // Install the package without updating the cache
                    await SimpleTestPackageUtility.CreateFolderFeedV3Async(pathContext.UserPackagesFolder, PackageSaveMode.Defaultv3, packageA);

                    // Run restore using an incorrect cache
                    var result = await command.ExecuteAsync();

                    // Verify a is in the output assets file
                    result.Success.Should().BeTrue();
                    result.LockFile.GetLibrary("a", new NuGetVersion(1, 0, 0)).Should().NotBeNull();
                }
        }