Пример #1
0
        public async Task RestoreResult_WritesSkipCommitToMinimal()
        {
            // Arrange
            using (var td = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var path   = Path.Combine(td, "project.lock.json");
                var logger = new TestLogger();
                var result = new RestoreResult(
                    success: true,
                    restoreGraphs: null,
                    compatibilityCheckResults: null,
                    lockFile: new LockFile(),
                    previousLockFile: new LockFile(), // same lock file
                    lockFilePath: path,
                    msbuild: new MSBuildRestoreResult("project", td, true),
                    toolRestoreResults: Enumerable.Empty <ToolRestoreResult>());

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

                // Assert
                Assert.Contains(
                    $"Lock file has not changed. Skipping lock file write. Path: {path}",
                    logger.MinimalMessages);
                Assert.False(File.Exists(path), $"The lock file should not have been written: {path}");
                Assert.Equal(1, logger.Messages.Count);
            }
        }
Пример #2
0
        public async Task LocalMetadataResourceTests_GetLatestVersion()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packages = new[]
                {
                    new TestLocalPackageInfo("a", "1.0.0"),
                    new TestLocalPackageInfo("A", "1.0.0-alpha.1.2.3+a.b"),
                    new TestLocalPackageInfo("b", "2.0.0"),
                    new TestLocalPackageInfo("B", "2.0.1+githash.0faef"),
                    new TestLocalPackageInfo("b", "2.0.2-alpha.1.2.3+githash.0faef")
                };

                var localResource = new TestFindLocalPackagesResource(packages);
                var resource      = new LocalMetadataResource(localResource);

                // Act
                var result = await resource.GetLatestVersion(
                    "b",
                    includePrerelease : false,
                    includeUnlisted : false,
                    log : testLogger,
                    token : CancellationToken.None);

                // Assert
                Assert.Equal("2.0.1+githash.0faef", result.ToFullString());
            }
        }
        public void PackageFolderReader_NuspecCountNested()
        {
            // Arrange
            using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder())
                using (var stream = new MemoryStream())
                {
                    using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
                    {
                        zip.AddEntry("lib/net45/a.dll", new byte[0]);
                        zip.AddEntry("package.nuspec", new byte[5]);
                        zip.AddEntry("content/package.nuspec", new byte[0]);
                    }

                    stream.Seek(0, SeekOrigin.Begin);

                    var zipFile = new ZipArchive(stream, ZipArchiveMode.Read);

                    zipFile.ExtractAll(workingDir);

                    var folderReader = new PackageFolderReader(workingDir);

                    // Act
                    using (var nuspec = folderReader.GetNuspec())
                    {
                        // Assert
                        Assert.NotNull(nuspec);
                        Assert.Equal(5, nuspec.Length);
                    }
                }
        }
Пример #4
0
        public async Task PushCommand_AbsolutePathSource()
        {
            using (TestDirectory workingDir = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange (create a test package)
                DirectoryInfo packagePushDest = new DirectoryInfo(Path.Combine(workingDir, "packagePushDest"));
                packagePushDest.Create();

                List <PackageSource> packageSources = new List <PackageSource>();
                packageSources.Add(new PackageSource(packagePushDest.FullName));

                FileInfo packageInfo = SimpleTestPackageUtility.CreateFullPackage(workingDir, "test", "1.0.0");

                // Act
                await PushRunner.Run(
                    Settings.LoadDefaultSettings(null, null, null),
                    new TestPackageSourceProvider(packageSources),
                    packageInfo.FullName,
                    packagePushDest.FullName,
                    null,  // api key
                    null,  // symbols source
                    null,  // symbols api key
                    0,     // timeout
                    false, // disable buffering
                    false, // no symbols
                    new TestLogger());

                // Assert
                string destFile = Path.Combine(packagePushDest.FullName, packageInfo.Name);
                Assert.Equal(true, File.Exists(destFile));
            }
        }
Пример #5
0
        public async Task LocalMetadataResourceTests_ExistsById()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packages = new[]
                {
                    new TestLocalPackageInfo("a", "1.0.0"),
                    new TestLocalPackageInfo("a", "1.0.0-alpha.1.2.3+a.b"),
                    new TestLocalPackageInfo("b", "2.0.0"),
                    new TestLocalPackageInfo("b", "2.0.1+githash.0faef")
                };

                var localResource = new TestFindLocalPackagesResource(packages);
                var resource      = new LocalMetadataResource(localResource);

                // Act
                var a = await resource.Exists("A", testLogger, CancellationToken.None);

                var b = await resource.Exists("b", testLogger, CancellationToken.None);

                var c = await resource.Exists("c", testLogger, CancellationToken.None);

                // Assert
                Assert.True(a);
                Assert.True(b);
                Assert.False(c);
            }
        }
Пример #6
0
        public void ConfigDefaultsAreProperlyReadFromConfigDefaultsFile()
        {
            //Arrange
            var name1 = "Contoso Package Source";
            var name2 = "My Test Package Source";
            var feed1 = "http://contoso.com/packages/";
            var feed2 = "http://wwww.somerandomURL.com/";

            using (var nugetConfigFileFolder = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var nugetConfigFile     = "NuGetDefaults.config";
                var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, nugetConfigFile);

                var enabledReplacement = @"<add key='" + name1 + "' value='" + feed1 + "' />";

                enabledReplacement = enabledReplacement + @"<add key='" + name2 + "' value='" + feed2 + "' />";
                var disabledReplacement = string.Empty;
                var defaultPushSource   = "<add key='DefaultPushSource' value='" + feed2 + "' />";
                File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement, defaultPushSource));

                //Act
                ConfigurationDefaults       configDefaults = new ConfigurationDefaults(nugetConfigFileFolder, nugetConfigFile);
                IEnumerable <PackageSource> defaultSourcesFromConfigFile = configDefaults.DefaultPackageSources;
                string packageRestore    = configDefaults.DefaultPackageRestoreConsent;
                string packagePushSource = configDefaults.DefaultPushSource;

                //Assert
                VerifyPackageSource(defaultSourcesFromConfigFile, 2, new string[] { name1, name2 }, new string[] { feed1, feed2 });
                Assert.Equal(feed2, packagePushSource);
                Assert.Equal("true", packageRestore.ToLowerInvariant());
            }
        }
Пример #7
0
        public void UWPRestore_ReadLockFileRoundTrip()
        {
            using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var expectedStream = GetResource("NuGet.Commands.FuncTest.compiler.resources.uwpBlankAppV2.json");

                JObject json   = null;
                var     format = new LockFileFormat();

                using (var reader = new StreamReader(expectedStream))
                {
                    json = JObject.Parse(reader.ReadToEnd());
                }

                var path = Path.Combine(workingDir, "project.lock.json");

                // Act
                var lockFile = format.Parse(json.ToString(), path);

                format.Write(path, lockFile);
                var jsonOutput = JObject.Parse(File.ReadAllText(path));

                // Assert
                Assert.Equal(json.ToString(), jsonOutput.ToString());
            }
        }
Пример #8
0
        public async Task InstallationCompatibility_WithInvalidProjectActions_Fails()
        {
            // Arrange
            using (var userPackageFolder = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var tc = new TestContext(userPackageFolder);

                await SimpleTestPackageUtility.CreateFolderFeedV3(
                    userPackageFolder,
                    PackageSaveMode.Defaultv3,
                    new[]
                {
                    new SimpleTestPackageContext(tc.PackageIdentityA)
                    {
                        PackageTypes = { tc.InvalidPackageType }
                    }
                });

                // Act & Assert
                var ex = Assert.Throws <PackagingException>(() =>
                                                            tc.Target.EnsurePackageCompatibility(
                                                                tc.ProjectKProject,
                                                                tc.NuGetPathContext.Object,
                                                                new NuGetProjectAction[]
                {
                    NuGetProjectAction.CreateInstallProjectAction(tc.PackageIdentityA, tc.SourceRepository)
                },
                                                                tc.GetRestoreResult(new[] { tc.PackageIdentityA })));

                Assert.Equal(
                    "Package 'PackageA 1.0.0' has a package type 'Invalid 1.2' that is not supported by project 'TestProjectKNuGetProject'.",
                    ex.Message);
            }
        }
Пример #9
0
        public void DeleteCommand_DeleteFromFileSystemSourceUnixStyle()
        {
            var nugetexe = Util.GetNuGetExePath();

            using (var windowsSource = TestFileSystemUtility.CreateRandomTestFolder())
            {
                string source = ((string)windowsSource).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);

                // Arrange
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", windowsSource);
                Assert.True(File.Exists(packageFileName));

                // Act
                string[] args = new string[] {
                    "delete",
                    "testPackage1",
                    "1.1.0",
                    "-Source",
                    source,
                    "-NonInteractive"
                };

                var r = CommandRunner.Run(
                    nugetexe,
                    Directory.GetCurrentDirectory(),
                    $"delete testPackage1 1.1.0 -Source {source} -NonInteractive",
                    waitForExit: true);

                // Assert
                Assert.Equal(0, r.Item1);
                Assert.False(File.Exists(packageFileName));
            }
        }
Пример #10
0
        private async Task <IEnumerable <NuGetProjectAction> > PacManCleanInstall(SourceRepositoryProvider sourceRepositoryProvider, PackageIdentity target)
        {
            // Arrange
            using (var testSolutionManager = new TestSolutionManager(true))
                using (var randomPackagesConfigFolderPath = TestFileSystemUtility.CreateRandomTestFolder())
                {
                    var testSettings          = new Configuration.NullSettings();
                    var token                 = CancellationToken.None;
                    var deleteOnRestartManger = new TestDeleteOnRestartManager();
                    var nuGetPackageManager   = new NuGetPackageManager(
                        sourceRepositoryProvider,
                        testSettings,
                        testSolutionManager,
                        deleteOnRestartManger);
                    var packagesFolderPath = PackagesFolderPathUtility.GetPackagesFolderPath(testSolutionManager, testSettings);

                    var randomPackagesConfigPath = Path.Combine(randomPackagesConfigFolderPath, "packages.config");

                    var projectTargetFramework    = NuGetFramework.Parse("net45");
                    var msBuildNuGetProjectSystem = new TestMSBuildNuGetProjectSystem(projectTargetFramework, new TestNuGetProjectContext());
                    var msBuildNuGetProject       = new MSBuildNuGetProject(msBuildNuGetProjectSystem, packagesFolderPath, randomPackagesConfigFolderPath);

                    // Act
                    var nugetProjectActions = await nuGetPackageManager.PreviewInstallPackageAsync(msBuildNuGetProject, target,
                                                                                                   new ResolutionContext(), new TestNuGetProjectContext(), sourceRepositoryProvider.GetRepositories().First(), null, token);

                    return(nugetProjectActions);
                }
        }
Пример #11
0
        public void XProjUtility_DependencyNotFound()
        {
            // Arrange
            using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var json1 = @"{
                          ""dependencies"": {
                                ""project2"": ""1.0.0""
                                }
                            },
                            ""frameworks"": {
                                ""net46"": {}
                            }
                        }";

                var proj1Folder = Path.Combine(workingDir, "project1");
                Directory.CreateDirectory(proj1Folder);

                var path1 = Path.Combine(proj1Folder, "project.json");
                File.WriteAllText(path1, json1);
                var xproj1 = Path.Combine(proj1Folder, "project1.xproj");
                File.WriteAllText(xproj1, string.Empty);

                // Act
                var references = XProjUtility.GetProjectReferences(xproj1);

                // Assert
                Assert.Equal(0, references.Count());
            }
        }
Пример #12
0
        public void ListCommand_ShowLicenseUrlWithDetailedVerbosity()
        {
            // Arrange
            var nugetexe = Util.GetNuGetExePath();

            using (var repositoryPath = TestFileSystemUtility.CreateRandomTestFolder())
            {
                Util.CreateTestPackage("testPackage1", "1.1.0", repositoryPath, new Uri("http://kaka"));

                string[] args = new string[] { "list", "-Source", repositoryPath, "-verbosity", "detailed" };

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

                // Assert
                Assert.Equal(0, r.Item1);
                var      output = r.Item2;
                string[] lines  = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                Assert.Equal(5, lines.Length);
                Assert.Equal("testPackage1", lines[1]);
                Assert.Equal(" 1.1.0", lines[2]);
                Assert.Equal(" desc of testPackage1 1.1.0", lines[3]);
                Assert.Equal(" License url: http://kaka", lines[4]);
            }
        }
Пример #13
0
        public void ListCommand_WithUserSpecifiedSource()
        {
            // Arrange
            var nugetexe = Util.GetNuGetExePath();

            using (var repositoryPath = TestFileSystemUtility.CreateRandomTestFolder())
            {
                Util.CreateTestPackage("testPackage1", "1.1.0", repositoryPath);
                Util.CreateTestPackage("testPackage2", "2.0.0", repositoryPath);

                string[] args = new string[] { "list", "-Source", repositoryPath };

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

                // Assert
                Assert.Equal(0, result.Item1);
                var output = result.Item2;
                Assert.Equal("testPackage1 1.1.0\r\ntestPackage2 2.0.0\r\n", output);
            }
        }
        public async Task LocalDownloadResource_PackageIsReturnedUnzippedFolder()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

                var id = new PackageIdentity("a", NuGetVersion.Parse("1.0.0"));
                SimpleTestPackageUtility.CreateFolderFeedUnzip(root, id);

                var localResource = new FindLocalPackagesResourceUnzipped(root);
                var resource      = new LocalDownloadResource(localResource);

                // Act
                var result = await resource.GetDownloadResourceResultAsync(
                    id,
                    NullSettings.Instance,
                    testLogger,
                    CancellationToken.None);

                using (var reader = result.PackageReader)
                    using (var stream = result.PackageStream)
                    {
                        // Assert
                        Assert.Equal(DownloadResourceResultStatus.Available, result.Status);
                        Assert.Equal("a", reader.GetIdentity().Id);
                        Assert.Equal("1.0.0", reader.GetIdentity().Version.ToFullString());
                        Assert.True(stream.CanSeek);
                        Assert.True(reader is PackageFolderReader);
                    }
            }
        }
Пример #15
0
        public async Task LocalAutoCompleteResource_IdStartsWithFilter()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packages = new[]
                {
                    new TestLocalPackageInfo("aaa", "1.0.0"),
                    new TestLocalPackageInfo("aab", "1.0.0-alpha.1.2.3+a.b"),
                    new TestLocalPackageInfo("acc", "2.0.0")
                };

                var localResource = new TestFindLocalPackagesResource(packages);
                var resource      = new LocalAutoCompleteResource(localResource);

                // Act
                var ids = (await resource.IdStartsWith("aa", includePrerelease: true, log: testLogger, token: CancellationToken.None)).ToList();

                // Assert
                Assert.Equal(2, ids.Count);
                Assert.Equal("aaa", ids[0]);
                Assert.Equal("aab", ids[1]);
            }
        }
Пример #16
0
        public void DeleteCommand_DeleteReadOnlyFromV2FileSystemSource()
        {
            var nugetexe = Util.GetNuGetExePath();

            using (var source = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", source);
                Assert.True(File.Exists(packageFileName));
                File.SetAttributes(packageFileName,
                                   File.GetAttributes(packageFileName) | FileAttributes.ReadOnly);
                // Act
                string[] args = new string[] {
                    "delete", "testPackage1", "1.1.0",
                    "-Source", source, "-NonInteractive"
                };
                var r = CommandRunner.Run(
                    nugetexe,
                    Directory.GetCurrentDirectory(),
                    String.Join(" ", args),
                    waitForExit: true);

                // Assert
                Assert.Equal(0, r.Item1);
                Assert.False(File.Exists(packageFileName));
            }
        }
Пример #17
0
        public void GetDefaultPackageSourcesReturnsValidPackageSources()
        {
            // Arrange
            using (var mockBaseDirectory = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var configurationDefaultsContent = @"
<configuration>
    <packageSources>
        <add key='Contoso Package Source' value='http://contoso.com/packages/' />
        <add key='NuGet Official Feed' value='http://www.nuget.org/api/v2/' />
    </packageSources>
    <disabledPackageSources>
        <add key='NuGet Official Feed' value='true' />
    </disabledPackageSources>
</configuration>";
                // Act & Assert
                ConfigurationDefaults ConfigurationDefaults = GetConfigurationDefaults(configurationDefaultsContent, mockBaseDirectory);

                Assert.NotNull(ConfigurationDefaults.DefaultPackageSources);

                List <PackageSource> defaultPackageSources = ConfigurationDefaults.DefaultPackageSources.ToList();

                Assert.Equal(defaultPackageSources.Count, 2);

                Assert.Equal(defaultPackageSources[0].Name, "Contoso Package Source");
                Assert.True(defaultPackageSources[0].IsEnabled);
                Assert.True(defaultPackageSources[0].IsOfficial);

                Assert.Equal(defaultPackageSources[1].Name, "NuGet Official Feed");
                Assert.False(defaultPackageSources[1].IsEnabled);
                Assert.True(defaultPackageSources[1].IsOfficial);
            }
        }
Пример #18
0
        public void DeleteCommand_DeleteFromV3FileSystemSource()
        {
            var nugetexe = Util.GetNuGetExePath();

            using (var source = TestFileSystemUtility.CreateRandomTestFolder())
            {
                //drop dummy artifacts to make it a V3
                var dummyPackageName     = "foo";
                var version              = "1.0.0";
                var packageFolder        = Directory.CreateDirectory(Path.Combine(source.Path, dummyPackageName));
                var packageVersionFolder = Directory.CreateDirectory(Path.Combine(packageFolder.FullName, "1.0.0"));
                File.WriteAllText(Path.Combine(packageVersionFolder.FullName, dummyPackageName + ".nuspec"), "dummy text");
                Assert.True(Directory.Exists(packageVersionFolder.FullName));
                // Act
                string[] args = new string[] {
                    "delete", "foo", version,
                    "-Source", source, "-NonInteractive"
                };
                var r = CommandRunner.Run(
                    nugetexe,
                    Directory.GetCurrentDirectory(),
                    String.Join(" ", args),
                    waitForExit: true);

                // Assert
                Assert.Equal(0, r.Item1);
                //The specific version folder should be gone.
                Assert.False(Directory.Exists(packageVersionFolder.FullName));
            }
        }
Пример #19
0
        public void CreateConfigurationDefaultsThrowsWhenXmlIsInvalid()
        {
            //Arrange
            var name1 = "Contoso Package Source";
            var name2 = "My Test Package Source";
            var feed1 = "http://contoso.com/packages/";
            var feed2 = "http://wwww.somerandomURL.com/";

            using (var nugetConfigFileFolder = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var nugetConfigFile     = "NuGetDefaults.config";
                var nugetConfigFilePath = Path.Combine(nugetConfigFileFolder, nugetConfigFile);

                var enabledReplacement = @"<add key='" + name1 + "' value='" + feed1;

                enabledReplacement = enabledReplacement + @"<add key='" + name2 + "' value='" + feed2;
                var disabledReplacement = string.Empty;
                var defaultPushSource   = "<add key='DefaultPushSource' value='" + feed2 + "' />";
                File.WriteAllText(nugetConfigFilePath, CreateNuGetConfigContent(enabledReplacement, disabledReplacement, defaultPushSource));

                Assert.Throws <NuGetConfigurationException>(() =>
                {
                    ConfigurationDefaults configDefaults = new ConfigurationDefaults(nugetConfigFileFolder, nugetConfigFile);
                });
            }
        }
Пример #20
0
        public void FallbackPackagePathResolver_MissingPackageWithFallbacks()
        {
            // Arrange
            using (var mockBaseDirectory = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var userFolder      = Path.Combine(mockBaseDirectory, "global");
                var fallbackFolders = new List <string>()
                {
                    Path.Combine(mockBaseDirectory, "fallback1"),
                    Path.Combine(mockBaseDirectory, "fallback2"),
                };

                Directory.CreateDirectory(userFolder);

                foreach (var fallback in fallbackFolders)
                {
                    Directory.CreateDirectory(fallback);
                }

                var resolver = new FallbackPackagePathResolver(userFolder, fallbackFolders);

                // Act
                var path = resolver.GetPackageDirectory("a", "1.0.0");

                // Assert
                Assert.Null(path);
            }
        }
Пример #21
0
        public async Task TestUninstallLastPackage()
        {
            // Arrange
            using (var randomTestFolder = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var targetFramework            = NuGetFramework.Parse("net45");
                var metadata                   = GetTestMetadata(targetFramework);
                var packagesConfigNuGetProject = new PackagesConfigNuGetProject(randomTestFolder, metadata);
                var packageIdentity            = new PackageIdentity("A", new NuGetVersion("1.0.0"));
                var testNuGetProjectContext    = new TestNuGetProjectContext();
                var token = CancellationToken.None;
                MakeFileReadOnly(randomTestFolder);

                // Act
                await packagesConfigNuGetProject.InstallPackageAsync(packageIdentity, GetDownloadResourceResult(), testNuGetProjectContext, token);

                MakeFileReadOnly(randomTestFolder);

                // Assert
                var installedPackagesList = (await packagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
                Assert.Equal(1, installedPackagesList.Count);
                Assert.Equal(packageIdentity, installedPackagesList[0].PackageIdentity);
                Assert.Equal(targetFramework, installedPackagesList[0].TargetFramework);

                // Main Act
                await packagesConfigNuGetProject.UninstallPackageAsync(packageIdentity, testNuGetProjectContext, token);

                // Main Assert
                installedPackagesList = (await packagesConfigNuGetProject.GetInstalledPackagesAsync(token)).ToList();
                Assert.Equal(0, installedPackagesList.Count);
            }
        }
        public async Task LocalPackageMetadataResourceTests_GetMetadataNoMatch()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packageContexts = new SimpleTestPackageContext[]
                {
                };

                SimpleTestPackageUtility.CreatePackages(root, packageContexts);

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

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

                // Assert
                Assert.Equal(0, results.Count);
            }
        }
Пример #23
0
        public async Task TestFolderNuGetProjectInstall()
        {
            // Arrange

            var packageIdentity = new PackageIdentity("packageA", new NuGetVersion("1.0.0"));

            using (var randomTestSourcePath = TestFileSystemUtility.CreateRandomTestFolder())
                using (var randomTestDestinationPath = TestFileSystemUtility.CreateRandomTestFolder())
                {
                    var packageFileInfo         = TestPackagesGroupedByFolder.GetLegacyTestPackage(randomTestSourcePath, packageIdentity.Id, packageIdentity.Version.ToNormalizedString());
                    var folderNuGetProject      = new FolderNuGetProject(randomTestDestinationPath);
                    var packagePathResolver     = new PackagePathResolver(randomTestDestinationPath);
                    var packageInstallPath      = packagePathResolver.GetInstallPath(packageIdentity);
                    var nupkgFilePath           = Path.Combine(packageInstallPath, packagePathResolver.GetPackageFileName(packageIdentity));
                    var testNuGetProjectContext = new TestNuGetProjectContext();
                    var token = CancellationToken.None;
                    using (var packageStream = GetDownloadResourceResult(packageFileInfo))
                    {
                        // Act
                        await folderNuGetProject.InstallPackageAsync(packageIdentity, packageStream, testNuGetProjectContext, token);
                    }

                    // Assert
                    Assert.True(File.Exists(nupkgFilePath));
                    Assert.True(File.Exists(Path.Combine(packageInstallPath, "lib/test.dll")));
                    using (var packageStream = File.OpenRead(nupkgFilePath))
                    {
                        var zipArchive = new ZipArchive(packageStream);
                        Assert.Equal(5, zipArchive.Entries.Count);
                    }
                }
        }
Пример #24
0
        public async Task LocalDependencyInfoResource_IdNotFound()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

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

                var packageContexts = new SimpleTestPackageContext[]
                {
                    packageX
                };

                SimpleTestPackageUtility.CreatePackages(root, packageContexts);

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

                // Act
                var resultsY = (await resource.ResolvePackages("y", NuGetFramework.Parse("net46"), testLogger, CancellationToken.None)).ToList();

                // Assert
                Assert.Equal(0, resultsY.Count);
            }
        }
Пример #25
0
        public async Task LocalMetadataResourceTests_GetVersions_Distinct()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packages = new[]
                {
                    new TestLocalPackageInfo("a", "1.0.0"),
                    new TestLocalPackageInfo("A", "1.0.0.0"),
                    new TestLocalPackageInfo("b", "2.0.0"),
                    new TestLocalPackageInfo("b", "2.0.0+githash.0faef")
                };

                var localResource = new TestFindLocalPackagesResource(packages);
                var resource      = new LocalMetadataResource(localResource);

                // Act
                var resultA = (await resource.GetVersions("a", testLogger, CancellationToken.None))
                              .OrderBy(v => v)
                              .ToList();

                var resultB = (await resource.GetVersions("b", testLogger, CancellationToken.None))
                              .OrderBy(v => v)
                              .ToList();

                // Assert
                Assert.Equal(1, resultA.Count);
                Assert.Equal(1, resultB.Count);
            }
        }
        public async Task LocalPackageSearchResource_RelativePathIsRejected()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger    = new TestLogger();
                var source        = Path.Combine("..", "packages");
                var localResource = new FindLocalPackagesResourceV2(source);
                var resource      = new LocalPackageSearchResource(localResource);

                var filter = new SearchFilter()
                {
                    IncludePrerelease = true
                };

                // Act & Assert
                var actual = await Assert.ThrowsAsync <InvalidOperationException>(
                    () => resource.SearchAsync(
                        "mypackage",
                        filter,
                        skip: 0,
                        take: 30,
                        log: testLogger,
                        token: CancellationToken.None));

                Assert.Equal(
                    $"The path '{source}' for the selected source could not be resolved.",
                    actual.Message);
            }
        }
Пример #27
0
        public void PackageFolderReader_NuspecCountNone()
        {
            // Arrange
            using (var workingDir = TestFileSystemUtility.CreateRandomTestFolder())
                using (var stream = new MemoryStream())
                {
                    using (var zip = new ZipArchive(stream, ZipArchiveMode.Create, leaveOpen: true))
                    {
                        zip.AddEntry("lib/net45/a.dll", new byte[0]);
                    }

                    stream.Seek(0, SeekOrigin.Begin);

                    var zipFile = new ZipArchive(stream, ZipArchiveMode.Read);

                    zipFile.ExtractAll(workingDir);

                    var reader = new PackageFolderReader(workingDir);

                    var threwPackagingException = false;

                    // Act
                    try
                    {
                        var nuspec = reader.GetNuspec();
                    }
                    catch (PackagingException)
                    {
                        threwPackagingException = true;
                    }

                    // Assert
                    Assert.True(threwPackagingException);
                }
        }
Пример #28
0
        public async Task LocalAutoCompleteResource_VersionStartsWithFilterExactMatch()
        {
            using (var root = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var testLogger = new TestLogger();

                var packages = new[]
                {
                    new TestLocalPackageInfo("packageA", "1.0.0"),
                    new TestLocalPackageInfo("packagea", "1.1.0-alpha.1.2.3+a.b"),
                    new TestLocalPackageInfo("packageB", "2.0.0")
                };

                var localResource = new TestFindLocalPackagesResource(packages);
                var resource      = new LocalAutoCompleteResource(localResource);

                // Act
                var versions = (await resource.VersionStartsWith("packageA", "1.1.0-alpha.1.2.3+a.b", includePrerelease: true, log: testLogger, token: CancellationToken.None)).ToList();

                // Assert
                Assert.Equal(1, versions.Count);
                Assert.Equal("1.1.0-alpha.1.2.3+a.b", versions[0].ToFullString());
            }
        }
Пример #29
0
        public void SetApiKey_DefaultSource()
        {
            using (var testFolder = TestFileSystemUtility.CreateRandomTestFolder())
            {
                var configFile = Path.Combine(testFolder, "nuget.config");
                Util.CreateFile(configFile, "<configuration/>");

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

                // Act
                var result = CommandRunner.Run(
                    NuGetExePath,
                    testFolder,
                    $"setApiKey {testApiKey} -ConfigFile {configFile}",
                    waitForExit: true);

                // Assert
                Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                Assert.Contains($"The API Key '{testApiKey}' was saved for the NuGet gallery (https://www.nuget.org) and the symbol server (https://nuget.smbsrc.net/)", result.Item2);

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

                var actualApiKey = SettingsUtility.GetDecryptedValue(settings, ConfigurationConstants.ApiKeys, NuGetConstants.DefaultGalleryServerUrl);
                Assert.NotNull(actualApiKey);
                Assert.Equal(testApiKey, actualApiKey);
            }
        }
Пример #30
0
        public async Task PackagePreFetcher_NoInstallActionsInput()
        {
            using (var packagesFolderDir = TestFileSystemUtility.CreateRandomTestFolder())
            {
                // Arrange
                var actions        = new List <NuGetProjectAction>();
                var packagesFolder = new FolderNuGetProject(packagesFolderDir);
                var testSettings   = new Configuration.NullSettings();
                var logger         = new TestLogger();

                var target  = new PackageIdentity("packageA", NuGetVersion.Parse("1.0.0"));
                var target2 = new PackageIdentity("packageB", NuGetVersion.Parse("1.0.0"));

                actions.Add(NuGetProjectAction.CreateUninstallProjectAction(target));
                actions.Add(NuGetProjectAction.CreateUninstallProjectAction(target2));

                // Act
                var result = await PackagePreFetcher.GetPackagesAsync(
                    actions,
                    packagesFolder,
                    testSettings,
                    logger,
                    CancellationToken.None);

                // Assert
                Assert.Equal(0, result.Count);
            }
        }