public void DependenciesStringWithTargetFrameworks() { // Arrange var servicePackage = new DataServicePackage(); // Act servicePackage.Dependencies = "A:1.3:net40|B:[2.4, 5.0):sl5|C|D::winrt45|E:1.0"; List<PackageDependencySet> dependencySets = ((IPackage)servicePackage).DependencySets.ToList(); // Assert Assert.Equal(4, dependencySets.Count); Assert.Equal(1, dependencySets[0].Dependencies.Count); Assert.Equal(new FrameworkName(".NETFramework, Version=4.0"), dependencySets[0].TargetFramework); Assert.Equal("A", dependencySets[0].Dependencies.ElementAt(0).Id); Assert.Equal("A", dependencySets[0].Dependencies.ElementAt(0).Id); Assert.Equal(1, dependencySets[1].Dependencies.Count); Assert.Equal(new FrameworkName("Silverlight, Version=5.0"), dependencySets[1].TargetFramework); Assert.Equal("B", dependencySets[1].Dependencies.ElementAt(0).Id); Assert.Equal(2, dependencySets[2].Dependencies.Count); Assert.Null(dependencySets[2].TargetFramework); Assert.Equal("C", dependencySets[2].Dependencies.ElementAt(0).Id); Assert.Null(dependencySets[2].Dependencies.ElementAt(0).VersionSpec); Assert.Equal("E", dependencySets[2].Dependencies.ElementAt(1).Id); Assert.NotNull(dependencySets[2].Dependencies.ElementAt(1).VersionSpec); Assert.Equal(1, dependencySets[3].Dependencies.Count); Assert.Equal(new FrameworkName(".NETCore, Version=4.5"), dependencySets[3].TargetFramework); Assert.Equal("D", dependencySets[3].Dependencies.ElementAt(0).Id); Assert.Null(dependencySets[3].Dependencies.ElementAt(0).VersionSpec); }
public void EnsurePackageDownloadsThePackageIfItIsNotCachedInMemoryOnInMachineCache() { // Arrange var zipPackage = PackageUtility.CreatePackage("A", "1.2"); var uri = new Uri("http://nuget.org"); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>())) .Returns(zipPackage) .Verifiable(); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); var mockRepository = new MockPackageRepository(); var context = new Mock<IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny<object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "NEWHASH", Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, Context = context.Object }; // Act servicePackage.EnsurePackage(mockRepository); // Assert context.Verify(); packageDownloader.Verify(); Assert.True(mockRepository.Exists(zipPackage)); }
public void NullDependenciesStringReturnsEmptyDependenciesCollection() { // Arrange var servicePackage = new DataServicePackage(); // Assert Assert.False(((IPackage)servicePackage).DependencySets.Any()); }
/// <summary> /// Checks whether an IPackage exists within a PackageManager. By default, will use the UseSideBySide settings of the DefaultPackagePathProvider the PackageManager is instantiated with. /// If passed in TRUE for exhaustive, will check both with and without UseSideBySide set. /// </summary> /// <param name="packageManager"></param> /// <param name="packageId"> </param> /// <param name="version"> </param> /// <param name="exhaustive"></param> /// <returns></returns> public static bool IsPackageInstalled(this PackageManager packageManager, string packageId, SemanticVersion version, bool exhaustive = false) { IPackage package = new DataServicePackage { Version = version.ToString(), Id = packageId }; return packageManager.IsPackageInstalled(package, exhaustive); }
public void EmptyDependenciesStringReturnsEmptyDependenciesCollection() { // Arrange var servicePackage = new DataServicePackage(); // Act servicePackage.Dependencies = ""; // Assert Assert.IsFalse(((IPackage)servicePackage).Dependencies.Any()); }
public void DownloadAndVerifyThrowsIfPackageHashIsNull() { // Arrange var servicePackage = new DataServicePackage { Id = "A", Version = "1.2" }; // Act & Asert ExceptionAssert.Throws<InvalidOperationException>(() => servicePackage.DownloadAndVerifyPackage(new MockPackageRepository()), "Failed to download package correctly. The contents of the package could not be verified."); }
public void ShouldUpdateReturnsTrueIfOldHashAndPackageHashAreDifferent() { // Arrange var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "NEWHASH" }; // Act bool shouldUpdate = servicePackage.ShouldUpdatePackage(new MockPackageRepository()); // Assert Assert.IsTrue(shouldUpdate); }
public void CanResolveFromLocalRepository() { var console = new Mock<ILogger>().Object; var resolver = new PackageResolutionManager(console, true, new MemoryBasedPackageCache(console)); var remoteRepository = Utilities.GetFactory().CreateRepository("SingleAggregate"); var localRepository = new MockPackageRepository(); var package = new DataServicePackage() { Id = "Assembly.Common", Version = "1.0" }; var test = resolver.FindPackageInAllLocalSources(localRepository, remoteRepository, package, false, false); Assert.AreEqual("Assembly.Common", test.Id); }
public void ShouldUpdateReturnsTrueIfPackageNotInRepository() { // Arrange var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "HASH", OldHash = "HASH" }; // Act bool shouldUpdate = servicePackage.ShouldUpdatePackage(new MockPackageRepository()); // Assert Assert.IsTrue(shouldUpdate); }
private static void Backup(string nugetServerUrl, DataServicePackage package, string packageBackupfolder, bool whatIf) { var serverUrl = string.Format("{0}/api/v2/package/{1}/{2}", nugetServerUrl, package.Id, package.Version); var uri = new Uri(serverUrl); logger.Info(string.Format("Downloading package {0} to folder {1} from url {2}", package.Id, packageBackupfolder, uri)); if (!whatIf) { var downloader = new PlexPackageDownloader(uri, packageBackupfolder); downloader.Download(package); } else { logger.Info("skipping as whatif is true"); } }
public void CreatePluginManifest_Owners_NotAvailable() { // When the package.Owners field is null, we should fallback to Authors for setting the organization. // Arrange DataServicePackage testPackage = CreateTestDataServicePackage(); testPackage.Owners = null; testPackage.Authors = "Foo,Bar,Test"; // Act PluginManifest actualPluginManifest = AnalyzerPluginGenerator.CreatePluginManifest(testPackage); // Assert actualPluginManifest.Should().NotBeNull(); actualPluginManifest.Organization.Should().Be(testPackage.Authors); }
public void CreatePluginManifest_TitleMissing() { // When no title is available, ID should be used as a fallback, removing the dot separators for legibility. // Arrange DataServicePackage testPackage = CreateTestDataServicePackage(); testPackage.Title = null; testPackage.Id = "Foo.Bar.Test"; // Act PluginManifest actualPluginManifest = AnalyzerPluginGenerator.CreatePluginManifest(testPackage); // Assert actualPluginManifest.Should().NotBeNull(); actualPluginManifest.Name.Should().Be("Foo Bar Test"); }
public void CanResolveFromLocalRepository() { var console = new Mock <ILogger>().Object; var resolver = new PackageResolutionManager(console, true, new MemoryBasedPackageCache(console)); var remoteRepository = Utilities.GetFactory().CreateRepository("SingleAggregate"); var localRepository = new MockPackageRepository(); var package = new DataServicePackage() { Id = "Assembly.Common", Version = "1.0" }; var test = resolver.FindPackageInAllLocalSources(localRepository, remoteRepository, package, false, false); Assert.AreEqual("Assembly.Common", test.Id); }
public void CreatePluginManifest_FriendlyLicenseName_NotAvailable() { // When a short licensename is not assigned by NuGet.org, we should try to use the license URL instead. // Arrange DataServicePackage testPackage = CreateTestDataServicePackage(); testPackage.LicenseNames = null; testPackage.LicenseUrl = new Uri("http://foo.bar"); // Act PluginManifest actualPluginManifest = AnalyzerPluginGenerator.CreatePluginManifest(testPackage); // Assert actualPluginManifest.Should().NotBeNull(); actualPluginManifest.License.Should().Be(testPackage.LicenseUrl.ToString()); }
public void EnsurePackageStorePackageInMemoryIfMachineCacheIsNotAvailable() { // Arrange var uri = new Uri("http://nuget.org"); var mockRepository = new Mock <MockPackageRepository>().As <IPackageCacheRepository>(); mockRepository.Setup(s => s.InvokeOnPackage(It.IsAny <string>(), It.IsAny <SemanticVersion>(), It.IsAny <Action <Stream> >())).Returns(false); var packageDownloader = new Mock <PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny <IPackageMetadata>(), It.IsAny <Stream>())) .Callback(new Action <Uri, IPackageMetadata, Stream>( (url, metadata, stream) => PackageUtility.CreateSimplePackageStream("A", "1.2").CopyTo(stream))) .Verifiable(); var hashProvider = new Mock <IHashProvider>(MockBehavior.Strict); byte[] hash1 = new byte[] { 1, 2, 3, 4 }; hashProvider.Setup(h => h.CalculateHash(It.IsAny <Stream>())).Returns <Stream>((stream) => hash1); var context = new Mock <IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny <object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = Convert.ToBase64String(hash1), Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, Context = context.Object }; // Act servicePackage.EnsurePackage(mockRepository.Object); // Assert context.Verify(); packageDownloader.Verify(); var foundPackage = servicePackage._package; Assert.NotNull(foundPackage); Assert.True(foundPackage is ZipPackage); }
public void CreatePluginManifest_FriendlyLicenseName_Available() { // When available, a short licensename assigned by NuGet.org should be used. // The license url is a fallback only. // Arrange DataServicePackage testPackage = CreateTestDataServicePackage(); testPackage.LicenseNames = "Foo Bar License"; testPackage.LicenseUrl = new Uri("http://foo.bar"); // Act PluginManifest actualPluginManifest = AnalyzerPluginGenerator.CreatePluginManifest(testPackage); // Assert actualPluginManifest.Should().NotBeNull(); actualPluginManifest.License.Should().Be(testPackage.LicenseNames); }
public bool CanDetermineVersionlessPackageIsInstalled(string id, string onDiskVersion, string packageVersion, bool installedUsingMultipleVersion, bool currentlyAllowMultipleVersions, bool exhaustive) { var mfs = new Mock <MockFileSystem>() { CallBase = true }; mfs.Setup(m => m.Root).Returns(@"c:\packages"); var installPathResolver = new DefaultPackagePathResolver(mfs.Object, installedUsingMultipleVersion); var currentPathResolver = new DefaultPackagePathResolver(mfs.Object, currentlyAllowMultipleVersions); var testPackage = new DataServicePackage() { Version = packageVersion, Id = id }; var filePackage = new DataServicePackage() { Version = onDiskVersion, Id = id }; IPackage zipPackage = null; if (!string.IsNullOrEmpty(onDiskVersion)) { string baseLocation = installPathResolver.GetInstallPath(filePackage); string fileName = installPathResolver.GetPackageFileName(filePackage.Id, SemanticVersion.Parse(filePackage.Version)); string filePath = Path.Combine(baseLocation, fileName); zipPackage = PackageUtility.GetZipPackage(filePackage.Id, filePackage.Version); mfs.Setup(m => m.FileExists(filePath)).Returns(true); mfs.Setup(m => m.OpenFile(filePath)).Returns(zipPackage.GetStream()); mfs.Object.AddFile(filePath, zipPackage.GetStream()); } var pm = new PackageManager(new MockPackageRepository(), currentPathResolver, mfs.Object); var exists = pm.IsPackageInstalled(testPackage, exhaustive: exhaustive); //var test = testPackage.IsPackageInstalled(allowMultipleVersions, pm, mfs.Object); return(exists); }
public void ShouldUpdateReturnsTrueIfRepositoryPackageHashIsDifferentFromPackageHash() { // Arrange var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "HASH", OldHash = "HASH" }; var repository = new MockPackageRepository { PackageUtility.CreatePackage("A", "1.2") }; // Act bool shouldUpdate = servicePackage.ShouldUpdatePackage(repository); // Assert Assert.IsTrue(shouldUpdate); }
public void DependenciesStringWithExtraSpaces() { // Arrange var servicePackage = new DataServicePackage(); // Act servicePackage.Dependencies = " A : 1.3 | B : [2.4, 5.0) "; List <PackageDependency> dependencies = ((IPackage)servicePackage).Dependencies.ToList(); // Assert Assert.AreEqual(2, dependencies.Count); Assert.AreEqual("A", dependencies[0].Id); Assert.IsTrue(dependencies[0].VersionSpec.IsMinInclusive); Assert.AreEqual(new Version("1.3"), dependencies[0].VersionSpec.MinVersion); Assert.AreEqual("B", dependencies[1].Id); Assert.IsTrue(dependencies[1].VersionSpec.IsMinInclusive); Assert.AreEqual(new Version("2.4"), dependencies[1].VersionSpec.MinVersion); Assert.IsFalse(dependencies[1].VersionSpec.IsMaxInclusive); Assert.AreEqual(new Version("5.0"), dependencies[1].VersionSpec.MaxVersion); }
public void DependenciesStringWithExtraSpaces() { // Arrange var servicePackage = new DataServicePackage(); // Act servicePackage.Dependencies = " A : 1.3 | B : [2.4, 5.0) "; List<PackageDependency> dependencies = ((IPackage)servicePackage).Dependencies.ToList(); // Assert Assert.AreEqual(2, dependencies.Count); Assert.AreEqual("A", dependencies[0].Id); Assert.IsTrue(dependencies[0].VersionSpec.IsMinInclusive); Assert.AreEqual(new Version("1.3"), dependencies[0].VersionSpec.MinVersion); Assert.AreEqual("B", dependencies[1].Id); Assert.IsTrue(dependencies[1].VersionSpec.IsMinInclusive); Assert.AreEqual(new Version("2.4"), dependencies[1].VersionSpec.MinVersion); Assert.IsFalse(dependencies[1].VersionSpec.IsMaxInclusive); Assert.AreEqual(new Version("5.0"), dependencies[1].VersionSpec.MaxVersion); }
public void EnsurePackageDownloadsUsesInMemoryCachedInstanceOnceDownloaded() { // Arrange var zipPackage = PackageUtility.CreatePackage("A", "1.2"); var uri = new Uri("http://nuget.org"); var mockRepository = new MockPackageCacheRepository(true); var packageDownloader = new Mock <PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny <IPackageMetadata>(), It.IsAny <Stream>())) .Callback(() => mockRepository.AddPackage(zipPackage)) .Verifiable(); var hashProvider = new Mock <IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny <Stream>())).Returns <Stream>((stream) => new byte[] { 1, 2, 3, 4 }); var context = new Mock <IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny <object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = Convert.ToBase64String(new byte[] { 1, 2, 3, 4 }), Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, Context = context.Object }; // Act servicePackage.EnsurePackage(mockRepository); servicePackage.EnsurePackage(mockRepository); servicePackage.EnsurePackage(mockRepository); // Assert Assert.Equal(zipPackage, servicePackage._package); context.Verify(s => s.GetReadStreamUri(It.IsAny <object>()), Times.Once()); packageDownloader.Verify(d => d.DownloadPackage(uri, It.IsAny <IPackageMetadata>(), It.IsAny <Stream>()), Times.Once()); Assert.True(mockRepository.Exists(zipPackage)); }
public void GetPackageDependenciesRecursive(DataServicePackage package, HashSet <DataServicePackage> dependencies) { dependencies.Add(package); var packagesToReslove = new List <DataServicePackage>(); foreach (var packageDependencySet in package.DependencySets) { foreach (var dependency in packageDependencySet.Dependencies) { var dependecyPackage = (DataServicePackage)_repo.ResolveDependency(dependency, true, true); if (dependecyPackage != null && !dependencies.Contains(dependecyPackage)) { packagesToReslove.Add(dependecyPackage); } } } foreach (var p in packagesToReslove) { GetPackageDependenciesRecursive(p, dependencies); } }
public string ResolvesFromCacheFirst(string id, string version, string spec, string cacheVersion, bool isLatest) { //Setup the package and versionspec for the cache var cachePackage = new DataServicePackage() { Id = id, Version = cacheVersion }; var versionSpec = spec == null ? null : VersionUtility.ParseVersionSpec(spec); //Add to appropriate cache we want to test based on whether we have a versionspec or not. var console = new Mock<ILogger>().Object; var cache = new MemoryBasedPackageCache(console); if (versionSpec == null) cache.AddCacheEntryByIsLatest(cachePackage); else cache.AddCacheEntryByConstraint(cachePackage, versionSpec); //Repository does not have these versions, so any call to it will fail... var resolver = new PackageResolutionManager(console, isLatest, cache); var remoteRepository = Utilities.GetFactory().CreateRepository("SingleAggregate"); var result = resolver.ResolveLatestInstallablePackage(remoteRepository, new PackageReference(id, SemanticVersion.Parse(version), versionSpec)); //Null result when we call ResolveLastestInstallablePackage when PackageResolutionManager not using Latest return result == null ? "" : result.Version.ToString(); }
private async Task<LucenePackage> DownloadDataServicePackage(DataServicePackage dataPackage, CancellationToken cancellationToken) { var parent = PathResolver.GetInstallPath(dataPackage); var path = Path.Combine(parent, PathResolver.GetPackageFileName(dataPackage)); if (!Directory.Exists(parent)) { Directory.CreateDirectory(parent); } var client = CreateHttpClient(); var assembly = typeof (LucenePackageRepository).Assembly; client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(assembly.GetName().Name, assembly.GetName().Version.ToString())); client.DefaultRequestHeaders.Add(RepositoryOperationNames.OperationHeaderName, RepositoryOperationNames.Mirror); Stream stream; using (cancellationToken.Register(client.CancelPendingRequests)) { stream = await client.GetStreamAsync(dataPackage.DownloadUrl); } cancellationToken.ThrowIfCancellationRequested(); var fileStream = OpenFileWriteStream(path); using (fileStream) { using (stream) { await stream.CopyToAsync(fileStream, 4096, cancellationToken); } } var lucenePackage = LoadFromFileSystem(path); lucenePackage.OriginUrl = dataPackage.DownloadUrl; lucenePackage.IsMirrored = true; return lucenePackage; }
public bool CanDetermineVersionlessPackageIsInstalled(string id, string onDiskVersion, string packageVersion, bool installedUsingMultipleVersion, bool currentlyAllowMultipleVersions, bool exhaustive) { var mfs = new Mock<MockFileSystem>() { CallBase = true }; mfs.Setup(m => m.Root).Returns(@"c:\packages"); var installPathResolver = new DefaultPackagePathResolver(mfs.Object, installedUsingMultipleVersion); var currentPathResolver = new DefaultPackagePathResolver(mfs.Object, currentlyAllowMultipleVersions); var testPackage = new DataServicePackage() { Version = packageVersion, Id = id }; var filePackage = new DataServicePackage() { Version = onDiskVersion, Id = id }; IPackage zipPackage = null; if (!string.IsNullOrEmpty(onDiskVersion)) { string baseLocation = installPathResolver.GetInstallPath(filePackage); string fileName = installPathResolver.GetPackageFileName(filePackage.Id, SemanticVersion.Parse(filePackage.Version)); string filePath = Path.Combine(baseLocation, fileName); zipPackage = PackageUtility.GetZipPackage(filePackage.Id, filePackage.Version); mfs.Setup(m => m.FileExists(filePath)).Returns(true); mfs.Setup(m => m.OpenFile(filePath)).Returns(zipPackage.GetStream()); mfs.Object.AddFile(filePath, zipPackage.GetStream()); } var pm = new PackageManager(new MockPackageRepository(), currentPathResolver, mfs.Object); var exists = pm.IsPackageInstalled(testPackage,exhaustive: exhaustive); //var test = testPackage.IsPackageInstalled(allowMultipleVersions, pm, mfs.Object); return exists; }
public void CreatePluginManifest_AllProperties() { // All properties present, all properties expected. // Arrange DataServicePackage testPackage = CreateTestDataServicePackage(); testPackage.Description = "Test Description"; testPackage.Authors = "TestAuthor1,TestAuthor2"; testPackage.ProjectUrl = new Uri("http://test.project.url"); testPackage.Id = "Test.Id"; testPackage.Title = "Test Title"; testPackage.Owners = "TestOwner1,TestOwner2"; testPackage.Version = "1.1.1-RC5"; testPackage.LicenseUrl = new Uri("http://test.license.url"); testPackage.LicenseNames = "Test License1;Test License2"; // Act PluginManifest actualPluginManifest = AnalyzerPluginGenerator.CreatePluginManifest(testPackage); // Assert actualPluginManifest.Should().NotBeNull(); actualPluginManifest.Description.Should().Be(testPackage.Description); actualPluginManifest.Developers.Should().Be(testPackage.Authors); actualPluginManifest.Homepage.Should().Be(testPackage.ProjectUrl.ToString()); actualPluginManifest.Key.Should().Be(PluginKeyUtilities.GetValidKey(testPackage.Id)); actualPluginManifest.Name.Should().Be(testPackage.Title); actualPluginManifest.Organization.Should().Be(testPackage.Owners); actualPluginManifest.Version.Should().Be(testPackage.Version); actualPluginManifest.TermsConditionsUrl.Should().Be(testPackage.LicenseUrl.ToString()); actualPluginManifest.License.Should().Be(testPackage.LicenseNames); }
static void Main(string[] args) { Properties.Settings.Default.Upgrade(); string chocoRepo = string.Empty; string localRepo = string.Empty; bool downloadUpdates = false; if (args.Count() < 2) { localRepo = Properties.Settings.Default.LocalRepo; chocoRepo = Properties.Settings.Default.ChocoRepo; // No parameters provides, so check the config - and if there are none there prompt the user interactively. if (string.IsNullOrEmpty(Properties.Settings.Default.LocalRepo) || string.IsNullOrEmpty(Properties.Settings.Default.ChocoRepo)) { Console.WriteLine("No settings found, please specify your repository locations"); Console.Write("Chocolatey Repository [{0}] (Press enter to keep): ", chocoRepo); string respone = Console.ReadLine(); if (!string.IsNullOrEmpty(respone)) { chocoRepo = respone; } Console.Write("Local Repository [{0}] (Press enter to keep): ", localRepo); respone = Console.ReadLine(); if (!string.IsNullOrEmpty(respone)) { localRepo = respone; } } Properties.Settings.Default.ChocoRepo = chocoRepo; Properties.Settings.Default.LocalRepo = localRepo; Properties.Settings.Default.Save(); if (args.Count() == 1) { downloadUpdates = bool.Parse(args[0]); } } else { // Parse the command line for the two repository values if (args.Count() > 2) { Console.WriteLine("Syntax:"); Console.WriteLine(" ChocoCompare.exe <chocolatey repository> <local repository>"); Console.WriteLine(" -OR-"); Console.WriteLine(" ChocoCompare.exe <download updates true/false>"); Console.WriteLine(" -OR-"); Console.WriteLine(" ChocoCompare.exe"); Console.WriteLine(); Console.WriteLine("Exit Codes above 10 are errors, exit code 1 indicates updates available"); Environment.Exit(10); } if (args.Count() == 2) { chocoRepo = args[0]; localRepo = args[1]; } } // Validate configuration if (string.IsNullOrEmpty(chocoRepo)) { Console.WriteLine("Error: Chocolatey repository must be specified and can not be left blank"); Environment.Exit(11); } if (string.IsNullOrEmpty(localRepo)) { Console.WriteLine("Error: Local repository must be specified and can not be left blank"); Environment.Exit(12); } IPackageRepository pubRepo = PackageRepositoryFactory.Default.CreateRepository(chocoRepo); IPackageRepository choRepo = PackageRepositoryFactory.Default.CreateRepository(localRepo); var localPackages = choRepo.GetPackages(); List <IPackage> packagesToUpdate = new List <IPackage>(); var packagesGroup = from localp in localPackages group localp by localp.Id into packageIdGroup select packageIdGroup; foreach (var grouping in packagesGroup) { // Get the latest version of this package. IPackage p = grouping.OrderByDescending(s => s.Version).First(); string packageName = p.Title; if (string.IsNullOrEmpty(packageName)) { packageName = p.GetFullName(); } Console.Write("Checking package {0}; local version is {1}", packageName, p.Version); var package = pubRepo.FindPackage(p.Id); if (package != null) { Console.Write("; remote version is {0}", package.Version); if (package.Version > p.Version) { ConsoleColor originalColour = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine(); Console.Write("Update available for {0} to {1}", packageName, package.Version); Console.ForegroundColor = originalColour; packagesToUpdate.Add(package); } } Console.WriteLine(); } Console.WriteLine("Finished checking packages; there are {0} packages to update.", packagesToUpdate.Count); if (downloadUpdates) { string tempFolder = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "ChocoCompare"); System.IO.Directory.CreateDirectory(tempFolder); Console.WriteLine(); ConsoleColor originalColour = Console.ForegroundColor; Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Downloading updates to temp folder: {0}", tempFolder); Console.ForegroundColor = originalColour; foreach (IPackage package in packagesToUpdate) { DataServicePackage pkg = package as DataServicePackage; if (pkg != null) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("Package: {0}", pkg.Title); Console.ForegroundColor = originalColour; // Download the package to a temporary location first using (WebClient client = new WebClient()) { Console.WriteLine("Downloading to {0}", System.IO.Path.Combine(tempFolder, pkg.Id + "." + pkg.Version + ".nupkg")); client.DownloadFile(pkg.DownloadUrl, System.IO.Path.Combine(tempFolder, pkg.Id + "." + pkg.Version + ".nupkg")); } } } // All downloaded, so go back over and copy them to the package folder Console.WriteLine(); Console.WriteLine("Copying files to the local package repository: {0}", localRepo); Console.WriteLine(); foreach (IPackage package in packagesToUpdate) { DataServicePackage pkg = package as DataServicePackage; if (pkg != null) { Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Package: {0}", pkg.Title); Console.ForegroundColor = originalColour; System.IO.File.Move(System.IO.Path.Combine(tempFolder, pkg.Id + "." + pkg.Version + ".nupkg"), System.IO.Path.Combine(localRepo, pkg.Id + "." + pkg.Version + ".nupkg")); } } } if (System.Diagnostics.Debugger.IsAttached) { Console.WriteLine("Press enter to exit"); Console.ReadLine(); } if (packagesToUpdate.Count == 0) { Environment.Exit(0); } Environment.Exit(1); }
public static void BackupAndDelete(IPackageRepository repo, string nugetServerUrl, DataServicePackage package, string packageBackupfolder, bool whatIf) { try { Backup(nugetServerUrl, package, packageBackupfolder, whatIf); } catch (Exception ex) { throw new Exception(string.Format("Backup of package {0} version {1} failed. skipping delete", package.Id, package.Version), ex); } Delete(repo, package, whatIf); }
public void FindPackageMethodChecksAllComparableVersions(string packageVersion) { // Arrange var client = new Mock<IHttpClient>(); var context = new Mock<IDataServiceContext>(); var repository = new Mock<DataServicePackageRepository>(client.Object) { CallBase = true }; repository.Object.Context = context.Object; var packages = new DataServicePackage[] { new DataServicePackage { Id = "A", Version = "2.0.0" }, new DataServicePackage { Id = "B", Version = "1.0.0" } }; var query = new Mock<IDataServiceQuery<DataServicePackage>>(); query.Setup(q => q.AsQueryable()).Returns(packages.AsQueryable()); context.Setup(c => c.CreateQuery<DataServicePackage>(It.IsAny<string>())).Returns(query.Object); // Act IPackage foundPackage = repository.Object.FindPackage("A", new SemanticVersion(packageVersion)); // Assert Assert.Equal(packages[0], foundPackage); }
public void EnsurePackageDownloadsUsesInMemoryCachedInstanceOnceDownloaded() { // Arrange var zipPackage = PackageUtility.CreatePackage("A", "1.2"); var uri = new Uri("http://nuget.org"); var mockRepository = new MockPackageCacheRepository(); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(() => mockRepository.AddPackage(zipPackage)) .Verifiable(); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); var context = new Mock<IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny<object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "NEWHASH", Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, Context = context.Object }; // Act servicePackage.EnsurePackage(mockRepository); servicePackage.EnsurePackage(mockRepository); servicePackage.EnsurePackage(mockRepository); // Assert Assert.Equal(zipPackage, servicePackage._package); context.Verify(s => s.GetReadStreamUri(It.IsAny<object>()), Times.Once()); packageDownloader.Verify(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>()), Times.Once()); Assert.True(mockRepository.Exists(zipPackage)); }
public void MinClientVersionReturnsNullValue() { // Arrange var package = new DataServicePackage(); // Act Version minClientVersion = (package as IPackageMetadata).MinClientVersion; // Assert Assert.Null(minClientVersion); }
public void EnsurePackageDownloadsPackageIfCacheIsInvalid() { // Arrange byte[] hashBytes1 = new byte[] { 1, 2, 3, 4 }; byte[] hashBytes2 = new byte[] { 3, 4, 5, 6 }; string hash1 = Convert.ToBase64String(hashBytes1); string hash2 = Convert.ToBase64String(hashBytes2); MemoryStream stream1 = new MemoryStream(new byte[] { 1 }); MemoryStream stream2 = new MemoryStream(new byte[] { 2 }); var mockPackage = new Mock<IPackage>(MockBehavior.Strict) { CallBase = true }; mockPackage.Setup(m => m.Id).Returns("A"); mockPackage.Setup(m => m.Listed).Returns(true); mockPackage.Setup(m => m.Version).Returns(new SemanticVersion("1.0")); mockPackage.Setup(m => m.GetStream()).Returns(stream1); var zipPackage1 = mockPackage.Object; var mockPackage2 = new Mock<IPackage>(MockBehavior.Strict) { CallBase = true }; mockPackage2.Setup(m => m.Id).Returns("A"); mockPackage2.Setup(m => m.Listed).Returns(true); mockPackage2.Setup(m => m.Version).Returns(new SemanticVersion("1.2")); mockPackage2.Setup(m => m.GetStream()).Returns(stream2); var zipPackage2 = mockPackage2.Object; var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny<Stream>())).Returns<Stream>((stream) => { if (stream == stream1) { return hashBytes1; } else if (stream == stream2) { return hashBytes2; } return null; }); var mockRepository = new Mock<IPackageCacheRepository>(MockBehavior.Strict); var lookup = mockRepository.As<IPackageLookup>(); lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); lookup.Setup(s => s.Exists("A", new SemanticVersion("1.2"))) .Returns(true); var uri = new Uri("http://nuget.org"); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(() => { lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage2); }) .Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = hash1, PackageHashAlgorithm = "SHA512", HashProvider = hashProvider.Object, Downloader = packageDownloader.Object, DownloadUrl = uri }; mockRepository.Setup(s => s.InvokeOnPackage("A", new SemanticVersion("1.2"), It.IsAny<Action<Stream>>())) .Callback(() => { using (var stream = new MemoryStream()) { packageDownloader.Object.DownloadPackage(servicePackage.DownloadUrl, servicePackage, stream); } }) .Returns(true); // Act 1 servicePackage.EnsurePackage(mockRepository.Object); // Assert 1 Assert.Equal(zipPackage1, servicePackage._package); // Act 2 servicePackage.PackageHash = hash2; servicePackage.EnsurePackage(mockRepository.Object); // Assert 2 Assert.Equal(zipPackage2, servicePackage._package); packageDownloader.Verify(); }
public void EnsurePackageDownloadsUsesInMemoryCachedInstanceOnceDownloaded() { // Arrange var zipPackage = PackageUtility.CreatePackage("A", "1.2"); var uri = new Uri("http://nuget.org"); var mockRepository = new MockPackageCacheRepository(true); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(() => mockRepository.AddPackage(zipPackage)) .Verifiable(); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny<Stream>())).Returns<Stream>((stream) => new byte[] { 1, 2, 3, 4 }); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = Convert.ToBase64String(new byte[] { 1, 2, 3, 4 }), Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, DownloadUrl = uri }; // Act servicePackage.EnsurePackage(mockRepository); servicePackage.EnsurePackage(mockRepository); servicePackage.EnsurePackage(mockRepository); // Assert Assert.Equal(zipPackage, servicePackage._package); packageDownloader.Verify(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>()), Times.Once()); Assert.True(mockRepository.Exists(zipPackage)); }
public void EnsurePackageStorePackageInMemoryIfMachineCacheIsNotAvailable() { // Arrange var uri = new Uri("http://nuget.org"); var mockRepository = new Mock<MockPackageRepository>().As<IPackageCacheRepository>(); mockRepository.Setup(s => s.InvokeOnPackage(It.IsAny<string>(), It.IsAny<SemanticVersion>(), It.IsAny<Action<Stream>>())).Returns(false); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(new Action<Uri, IPackageMetadata, Stream>( (url, metadata, stream) => PackageUtility.CreateSimplePackageStream("A", "1.2").CopyTo(stream))) .Verifiable(); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); byte[] hash1 = new byte[] { 1, 2, 3, 4 }; hashProvider.Setup(h => h.CalculateHash(It.IsAny<Stream>())).Returns<Stream>((stream) => hash1); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = Convert.ToBase64String(hash1), Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, DownloadUrl = uri }; // Act servicePackage.EnsurePackage(mockRepository.Object); // Assert packageDownloader.Verify(); var foundPackage = servicePackage._package; Assert.NotNull(foundPackage); Assert.True(foundPackage is ZipPackage); }
public void WillNotUseODataIfPackageLocal() { var console = new Mock<ILogger>().Object; var resolver = new PackageResolutionManager(console, true, new MemoryBasedPackageCache(console)); var odata = new Mock<DataServicePackageRepository>(new Uri(@"http://nuget.org")); var list = new List<IPackage>() { new DataServicePackage() { Id = "Assembly.Common", Version = "3.0" } }; odata.Setup(o => o.GetPackages()).Returns(list.AsQueryable()); var remoteRepository = new AggregateRepository(new List<IPackageRepository>() { Utilities.GetFactory().CreateRepository("SingleAggregate"), odata.Object }); var localRepository = new MockPackageRepository(); var package = new DataServicePackage() { Id = "Assembly.Common", Version = "3.0" }; Assert.AreEqual(true,remoteRepository.GetPackages().Contains(package)); var local = resolver.FindPackageInAllLocalSources(localRepository, remoteRepository, package, false, false); Assert.AreEqual(null, local); }
public void EnsurePackageDownloadUpdatesIdAndVersion() { // Arrange var zipPackage = PackageUtility.CreatePackage("Abc", "1.0"); var uri = new Uri("http://nuget.org"); var mockRepository = new MockPackageCacheRepository(true); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(() => mockRepository.AddPackage(zipPackage)) .Verifiable(); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny<Stream>())).Returns<Stream>((stream) => new byte[] { 1, 2, 3, 4 }); var servicePackage = new DataServicePackage { Id = "abc", Version = "1.0.0", PackageHash = Convert.ToBase64String(new byte[] { 1, 2, 3, 4 }), Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, DownloadUrl = uri }; // Act servicePackage.EnsurePackage(mockRepository); // Assert // servicePackage should have been updated to match zipPackage Assert.Equal("Abc", servicePackage.Id); Assert.Equal("1.0", servicePackage.Version); }
public void ShouldUpdateReturnsTrueIfPackageNotInRepository() { // Arrange var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "HASH", OldHash = "HASH" }; // Act bool shouldUpdate = servicePackage.ShouldUpdatePackage(new MockPackageRepository()); // Assert Assert.True(shouldUpdate); }
public void ShouldUpdateReturnsTrueIfRepositoryThrows() { // Arrange var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "HASH", OldHash = "HASH" }; var repository = new Mock<MockPackageRepository>(); repository.Setup(m => m.GetPackages()).Throws(new Exception()); // Act bool shouldUpdate = servicePackage.ShouldUpdatePackage(repository.Object); // Assert Assert.True(shouldUpdate); }
public void EnsurePackageDownloadsFailsIfHashIsIncorrect() { // Arrange byte[] hashBytes1 = new byte[] { 1, 2, 3, 4 }; string hash1 = Convert.ToBase64String(hashBytes1); MemoryStream stream1 = new MemoryStream(new byte[] { 1 }); var mockPackage = new Mock<IPackage>(MockBehavior.Strict) { CallBase = true }; mockPackage.Setup(m => m.Id).Returns("A"); mockPackage.Setup(m => m.Listed).Returns(true); mockPackage.Setup(m => m.Version).Returns(new SemanticVersion("1.0")); mockPackage.Setup(m => m.GetStream()).Returns(stream1); var zipPackage1 = mockPackage.Object; var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny<Stream>())).Returns<Stream>((stream) => hashBytes1); var mockRepository = new Mock<IPackageCacheRepository>(MockBehavior.Strict); var lookup = mockRepository.As<IPackageLookup>(); lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); lookup.Setup(s => s.Exists("A", new SemanticVersion("1.2"))) .Returns(true); var uri = new Uri("http://nuget.org"); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(() => { lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); }) .Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "IMPOSSIBLEHASH", PackageHashAlgorithm = "SHA512", HashProvider = hashProvider.Object, Downloader = packageDownloader.Object, DownloadUrl = uri }; mockRepository.Setup(s => s.InvokeOnPackage("A", new SemanticVersion("1.2"), It.IsAny<Action<Stream>>())) .Callback(() => { using (var stream = new MemoryStream()) { packageDownloader.Object.DownloadPackage(servicePackage.DownloadUrl, servicePackage, stream); } }) .Returns(true); // Act & Assert Assert.Throws(typeof(InvalidOperationException), () => servicePackage.EnsurePackage(mockRepository.Object)); }
public void EnsurePackageStorePackageInMemoryIfMachineCacheIsNotAvailable() { // Arrange var zipPackage = PackageUtility.CreatePackage("A", "1.2"); var uri = new Uri("http://nuget.org"); var mockRepository = new Mock<MockPackageRepository>().As<IPackageCacheRepository>(); mockRepository.Setup(s => s.CreatePackageStream(It.IsAny<string>(), It.IsAny<SemanticVersion>())).Returns((Stream)null); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(new Action<Uri, IPackageMetadata, Stream>( (url, metadata, stream) => PackageUtility.CreateSimplePackageStream("A", "1.2").CopyTo(stream))) .Verifiable(); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); var context = new Mock<IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny<object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "NEWHASH", Downloader = packageDownloader.Object, HashProvider = hashProvider.Object, Context = context.Object }; // Act servicePackage.EnsurePackage(mockRepository.Object); // Assert context.Verify(); packageDownloader.Verify(); var foundPackage = servicePackage._package; Assert.NotNull(foundPackage); Assert.True(foundPackage is ZipPackage); }
public void EnsurePackageDownloadsPackageIfCacheIsInvalid() { // Arrange byte[] hashBytes1 = new byte[] { 1, 2, 3, 4 }; byte[] hashBytes2 = new byte[] { 3, 4, 5, 6 }; string hash1 = Convert.ToBase64String(hashBytes1); string hash2 = Convert.ToBase64String(hashBytes2); var zipPackage1 = PackageUtility.CreatePackage("A", "1.2"); var zipPackage2 = PackageUtility.CreatePackage("B", "1.2"); var hashProvider = new Mock <IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny <Stream>())).Returns(hashBytes1); var mockRepository = new Mock <IPackageCacheRepository>(MockBehavior.Strict); var lookup = mockRepository.As <IPackageLookup>(); lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); lookup.Setup(s => s.Exists("A", new SemanticVersion("1.2"))) .Returns(true); mockRepository.Setup(s => s.CreatePackageStream("A", new SemanticVersion("1.2"))) .Returns(new MemoryStream()); var uri = new Uri("http://nuget.org"); var packageDownloader = new Mock <PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny <IPackageMetadata>(), It.IsAny <Stream>())) .Callback(() => { lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage2); }) .Verifiable(); var context = new Mock <IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny <object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = hash1, PackageHashAlgorithm = "SHA512", HashProvider = hashProvider.Object, Downloader = packageDownloader.Object, Context = context.Object }; // Act 1 servicePackage.EnsurePackage(mockRepository.Object); // Assert 1 Assert.Equal(zipPackage1, servicePackage._package); context.Verify(c => c.GetReadStreamUri(It.IsAny <object>()), Times.Never()); // Act 2 servicePackage.PackageHash = hash2; servicePackage.EnsurePackage(mockRepository.Object); // Assert 2 Assert.Equal(zipPackage2, servicePackage._package); context.Verify(); packageDownloader.Verify(); }
public void EnsurePackageDownloadsUsesMachineCacheIfAvailable() { // Arrange var hashBytes = new byte[] { 1, 2, 3, 4 }; var hash = Convert.ToBase64String(hashBytes); var zipPackage = PackageUtility.CreatePackage("A", "1.2"); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny<Stream>())).Returns(hashBytes); var mockRepository = new MockPackageCacheRepository(); mockRepository.Add(zipPackage); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = hash, HashProvider = hashProvider.Object, }; // Act servicePackage.EnsurePackage(mockRepository); // Assert Assert.Equal(zipPackage, servicePackage._package); }
public /* for test */ static PluginManifest CreatePluginManifest(IPackage package) { // The manifest properties supported by SonarQube are documented at // http://docs.sonarqube.org/display/DEV/Build+plugin PluginManifest pluginDefn = new PluginManifest(); pluginDefn.Description = GetValidManifestString(package.Description); pluginDefn.Developers = GetValidManifestString(ListToString(package.Authors)); pluginDefn.Homepage = GetValidManifestString(package.ProjectUrl?.ToString()); pluginDefn.Key = PluginKeyUtilities.GetValidKey(package.Id); if (!String.IsNullOrWhiteSpace(package.Title)) { pluginDefn.Name = GetValidManifestString(package.Title); } else { // Process the package ID to replace dot separators with spaces for use as a fallback pluginDefn.Name = GetValidManifestString(package.Id.Replace(".", " ")); } // Fall back to using the authors if owners is empty string organisation; if (package.Owners.Any()) { organisation = ListToString(package.Owners); } else { organisation = ListToString(package.Authors); } pluginDefn.Organization = GetValidManifestString(organisation); pluginDefn.Version = GetValidManifestString(package.Version?.ToNormalizedString()); // The TermsConditionsUrl is only displayed in the "Update Center - Available" page // i.e. for plugins that are available through the public Update Center. // If the property has a value then the link will be displayed with a checkbox // for acceptance. // It is not used when plugins are directly dropped into the extensions\plugins // folder of the SonarQube server. pluginDefn.TermsConditionsUrl = GetValidManifestString(package.LicenseUrl?.ToString()); // Packages from the NuGet website may have friendly short licensenames heuristically assigned, but this requires a downcast DataServicePackage dataServicePackage = package as DataServicePackage; if (!String.IsNullOrWhiteSpace(dataServicePackage?.LicenseNames)) { pluginDefn.License = GetValidManifestString(dataServicePackage.LicenseNames); } else { // Fallback - use a raw URL. Not as nice-looking in the UI, but acceptable. pluginDefn.License = pluginDefn.TermsConditionsUrl; } return(pluginDefn); }
public void EnsurePackageDownloadsPackageIfCacheIsInvalid() { // Arrange byte[] hashBytes1 = new byte[] { 1, 2, 3, 4 }; byte[] hashBytes2 = new byte[] { 3, 4, 5, 6 }; string hash1 = Convert.ToBase64String(hashBytes1); string hash2 = Convert.ToBase64String(hashBytes2); var zipPackage1 = PackageUtility.CreatePackage("A", "1.2"); var zipPackage2 = PackageUtility.CreatePackage("B", "1.2"); var hashProvider = new Mock<IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny<Stream>())).Returns(hashBytes1); var mockRepository = new Mock<IPackageCacheRepository>(MockBehavior.Strict); var lookup = mockRepository.As<IPackageLookup>(); lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); lookup.Setup(s => s.Exists("A", new SemanticVersion("1.2"))) .Returns(true); mockRepository.Setup(s => s.CreatePackageStream("A", new SemanticVersion("1.2"))) .Returns(new MemoryStream()); var uri = new Uri("http://nuget.org"); var packageDownloader = new Mock<PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny<IPackageMetadata>(), It.IsAny<Stream>())) .Callback(() => { lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage2); }) .Verifiable(); var context = new Mock<IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny<object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = hash1, PackageHashAlgorithm = "SHA512", HashProvider = hashProvider.Object, Downloader = packageDownloader.Object, Context = context.Object }; // Act 1 servicePackage.EnsurePackage(mockRepository.Object); // Assert 1 Assert.Equal(zipPackage1, servicePackage._package); context.Verify(c => c.GetReadStreamUri(It.IsAny<object>()), Times.Never()); // Act 2 servicePackage.PackageHash = hash2; servicePackage.EnsurePackage(mockRepository.Object); // Assert 2 Assert.Equal(zipPackage2, servicePackage._package); context.Verify(); packageDownloader.Verify(); }
public void EnsurePackageDownloadsPackageIfCacheIsInvalid() { // Arrange byte[] hashBytes1 = new byte[] { 1, 2, 3, 4 }; byte[] hashBytes2 = new byte[] { 3, 4, 5, 6 }; string hash1 = Convert.ToBase64String(hashBytes1); string hash2 = Convert.ToBase64String(hashBytes2); MemoryStream stream1 = new MemoryStream(new byte[] { 1 }); MemoryStream stream2 = new MemoryStream(new byte[] { 2 }); var mockPackage = new Mock <IPackage>(MockBehavior.Strict) { CallBase = true }; mockPackage.Setup(m => m.Id).Returns("A"); mockPackage.Setup(m => m.Listed).Returns(true); mockPackage.Setup(m => m.Version).Returns(new SemanticVersion("1.0")); mockPackage.Setup(m => m.GetStream()).Returns(stream1); var zipPackage1 = mockPackage.Object; var mockPackage2 = new Mock <IPackage>(MockBehavior.Strict) { CallBase = true }; mockPackage2.Setup(m => m.Id).Returns("A"); mockPackage2.Setup(m => m.Listed).Returns(true); mockPackage2.Setup(m => m.Version).Returns(new SemanticVersion("1.2")); mockPackage2.Setup(m => m.GetStream()).Returns(stream2); var zipPackage2 = mockPackage2.Object; var hashProvider = new Mock <IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny <Stream>())).Returns <Stream>((stream) => { if (stream == stream1) { return(hashBytes1); } else if (stream == stream2) { return(hashBytes2); } return(null); }); var mockRepository = new Mock <IPackageCacheRepository>(MockBehavior.Strict); var lookup = mockRepository.As <IPackageLookup>(); lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); lookup.Setup(s => s.Exists("A", new SemanticVersion("1.2"))) .Returns(true); var uri = new Uri("http://nuget.org"); var packageDownloader = new Mock <PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny <IPackageMetadata>(), It.IsAny <Stream>())) .Callback(() => { lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage2); }) .Verifiable(); var context = new Mock <IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny <object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = hash1, PackageHashAlgorithm = "SHA512", HashProvider = hashProvider.Object, Downloader = packageDownloader.Object, Context = context.Object }; mockRepository.Setup(s => s.InvokeOnPackage("A", new SemanticVersion("1.2"), It.IsAny <Action <Stream> >())) .Callback(() => { using (var stream = new MemoryStream()) { packageDownloader.Object.DownloadPackage(servicePackage.DownloadUrl, servicePackage, stream); } }) .Returns(true); // Act 1 servicePackage.EnsurePackage(mockRepository.Object); // Assert 1 Assert.Equal(zipPackage1, servicePackage._package); context.Verify(c => c.GetReadStreamUri(It.IsAny <object>()), Times.Never()); // Act 2 servicePackage.PackageHash = hash2; servicePackage.EnsurePackage(mockRepository.Object); // Assert 2 Assert.Equal(zipPackage2, servicePackage._package); context.Verify(); packageDownloader.Verify(); }
public void MinClientVersionReturnsParsedValue() { // Arrange var package = new DataServicePackage { MinClientVersion = "2.4.0.1" }; // Act Version minClientVersion = (package as IPackageMetadata).MinClientVersion; // Assert Assert.Equal("2.4.0.1", minClientVersion.ToString()); }
public void EnsurePackageDownloadsFailsIfHashIsIncorrect() { // Arrange byte[] hashBytes1 = new byte[] { 1, 2, 3, 4 }; string hash1 = Convert.ToBase64String(hashBytes1); MemoryStream stream1 = new MemoryStream(new byte[] { 1 }); var mockPackage = new Mock <IPackage>(MockBehavior.Strict) { CallBase = true }; mockPackage.Setup(m => m.Id).Returns("A"); mockPackage.Setup(m => m.Listed).Returns(true); mockPackage.Setup(m => m.Version).Returns(new SemanticVersion("1.0")); mockPackage.Setup(m => m.GetStream()).Returns(stream1); var zipPackage1 = mockPackage.Object; var hashProvider = new Mock <IHashProvider>(MockBehavior.Strict); hashProvider.Setup(h => h.CalculateHash(It.IsAny <Stream>())).Returns <Stream>((stream) => hashBytes1); var mockRepository = new Mock <IPackageCacheRepository>(MockBehavior.Strict); var lookup = mockRepository.As <IPackageLookup>(); lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); lookup.Setup(s => s.Exists("A", new SemanticVersion("1.2"))) .Returns(true); var uri = new Uri("http://nuget.org"); var packageDownloader = new Mock <PackageDownloader>(); packageDownloader.Setup(d => d.DownloadPackage(uri, It.IsAny <IPackageMetadata>(), It.IsAny <Stream>())) .Callback(() => { lookup.Setup(s => s.FindPackage("A", new SemanticVersion("1.2"))) .Returns(zipPackage1); }) .Verifiable(); var context = new Mock <IDataServiceContext>(); context.Setup(c => c.GetReadStreamUri(It.IsAny <object>())).Returns(uri).Verifiable(); var servicePackage = new DataServicePackage { Id = "A", Version = "1.2", PackageHash = "IMPOSSIBLEHASH", PackageHashAlgorithm = "SHA512", HashProvider = hashProvider.Object, Downloader = packageDownloader.Object, Context = context.Object }; mockRepository.Setup(s => s.InvokeOnPackage("A", new SemanticVersion("1.2"), It.IsAny <Action <Stream> >())) .Callback(() => { using (var stream = new MemoryStream()) { packageDownloader.Object.DownloadPackage(servicePackage.DownloadUrl, servicePackage, stream); } }) .Returns(true); // Act & Assert Assert.Throws(typeof(InvalidOperationException), () => servicePackage.EnsurePackage(mockRepository.Object)); }
private async Task<IFastZipPackage> DownloadDataServicePackage(DataServicePackage dataPackage, CancellationToken cancellationToken) { var assembly = typeof(LucenePackageRepository).Assembly; using (var client = CreateHttpClient()) { client.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue(assembly.GetName().Name, assembly.GetName().Version.ToString())); client.DefaultRequestHeaders.Add(RepositoryOperationNames.OperationHeaderName, RepositoryOperationNames.Mirror); Stream stream; using (cancellationToken.Register(client.CancelPendingRequests)) { stream = await client.GetStreamAsync(dataPackage.DownloadUrl); } cancellationToken.ThrowIfCancellationRequested(); using (var hashingStream = CreateStreamForStagingPackage()) { await stream.CopyToAsync(hashingStream, 4096, cancellationToken); return LoadStagedPackage(hashingStream); } } }
/// <summary> /// Searches package sources given name and version information /// /// Package information must be returned using <c>request.YieldPackage(...)</c> function. /// </summary> /// <param name="name">a name or partial name of the package(s) requested</param> /// <param name="requiredVersion">A specific version of the package. Null or empty if the user did not specify</param> /// <param name="minimumVersion">A minimum version of the package. Null or empty if the user did not specify</param> /// <param name="maximumVersion">A maximum version of the package. Null or empty if the user did not specify</param> /// <param name="id">if this is greater than zero (and the number should have been generated using <c>StartFind(...)</c>, the core is calling this multiple times to do a batch search request. The operation can be delayed until <c>CompleteFind(...)</c> is called</param> /// <param name="request">An object passed in from the CORE that contains functions that can be used to interact with the CORE and HOST</param> public void FindPackage(string name, string requiredVersion, string minimumVersion, string maximumVersion, int id, Request request) { request.Debug("Calling '{0}::FindPackage' '{1}','{2}','{3}','{4}'", PackageProviderName, requiredVersion, minimumVersion, maximumVersion, id); List <PackageSource> sources; var providerPackageSources = ProviderStorage.GetPackageSources(request); if (request.PackageSources != null && request.PackageSources.Any()) { sources = new List <PackageSource>(); foreach (var userRequestedSource in request.PackageSources) { if (providerPackageSources.ContainsKey(userRequestedSource)) { sources.Add(providerPackageSources[userRequestedSource]); } } } else { sources = providerPackageSources.Select(i => i.Value).ToList(); } var searchTerm = ReplacePowerShellWildcards(name); // Wildcard pattern matching configuration. const WildcardOptions wildcardOptions = WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase; var wildcardPattern = new WildcardPattern(String.IsNullOrEmpty(name) ? "*" : name, wildcardOptions); if (request.IsCanceled) { return; } foreach (var packageSource in sources.AsNotNull()) { var repo = RepositoryFactory.CreateV3(packageSource.Location); var search = repo.GetResource <UISearchResource>(); for (int i = 0; true; i += SearchPageSize) { List <UISearchMetadata> results; try { var task = search.Search(searchTerm, new SearchFilter(), i, SearchPageSize, CancellationToken.None); task.Wait(); results = task.Result.ToList(); } catch (NullReferenceException) { // usually means the source was incorrect, skip to the next source break; } foreach (var result in results.AsNotNull()) { if (!wildcardPattern.IsMatch(result.Identity.Id)) { continue; } var package = new DataServicePackage() { Id = result.Identity.Id, Version = result.Identity.Version.ToString(), Summary = result.Summary, Authors = result.LatestPackageMetadata.Authors, Title = result.Title, IconUrl = result.IconUrl, Owners = result.LatestPackageMetadata.Owners, Description = result.LatestPackageMetadata.Description, Tags = result.LatestPackageMetadata.Tags, LicenseUrl = result.LatestPackageMetadata.LicenseUrl, ProjectUrl = result.LatestPackageMetadata.ProjectUrl, Published = result.LatestPackageMetadata.Published, ReportAbuseUrl = result.LatestPackageMetadata.ReportAbuseUrl }; var fastPath = packageSource.MakeFastPath(result.Identity.Id, result.Identity.Version.ToString()); var packageItem = new PackageItem() { Id = result.Identity.Id, Version = result.Identity.Version.ToString(), FastPath = fastPath, Package = package, IsPackageFile = false, PackageSource = packageSource, FullPath = String.Empty }; // YieldPackage returns false when operation was cancelled if (!request.YieldPackage(packageItem, name)) { return; } } if (!results.Any()) { break; } } } }