Пример #1
0
        public NuGetPackageSearchServiceTests(GlobalServiceProvider globalServiceProvider)
            : base(globalServiceProvider)
        {
            _installedPackages  = new List <IPackageReferenceContextInfo>();
            _transitivePackages = new List <ITransitivePackageReferenceContextInfo>();
            _projects           = new List <IProjectContextInfo>
            {
                new ProjectContextInfo(
                    Guid.NewGuid().ToString(),
                    ProjectModel.ProjectStyle.PackageReference,
                    NuGetProjectKind.PackageReference)
            };
            var testFeedUrl = "https://testsource.test/v3/index.json";
            var query       = "https://api-v2v3search-0.nuget.org/query";
            var responses   = new Dictionary <string, string>
            {
                { testFeedUrl, ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.index.json", GetType()) },
                { query + "?q=nuget&skip=0&take=26&prerelease=true&semVerLevel=2.0.0", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.nugetSearchPage1.json", GetType()) },
                { query + "?q=nuget&skip=25&take=26&prerelease=true&semVerLevel=2.0.0", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.nugetSearchPage2.json", GetType()) },
                { query + "?q=&skip=0&take=26&prerelease=true&semVerLevel=2.0.0", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.blankSearchPage.json", GetType()) },
                { "https://api.nuget.org/v3/registration3-gz-semver2/nuget.core/index.json", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.nugetCoreIndex.json", GetType()) },
                { "https://api.nuget.org/v3/registration3-gz-semver2/microsoft.extensions.logging.abstractions/index.json", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.loggingAbstractions.json", GetType()) }
            };

            _componentModel = new Mock <IComponentModel>();
            var expService = new NuGetExperimentationService(new TestEnvironmentVariableReader(new Dictionary <string, string>()), new TestVisualStudioExperimentalService(_experimentationFlags), new Lazy <IOutputConsoleProvider>(() => new TestOutputConsoleProvider()));

            _componentModel.Setup(x => x.GetService <INuGetExperimentationService>()).Returns(expService);

            globalServiceProvider.AddService(typeof(SComponentModel), _componentModel.Object);

            _sourceRepository = StaticHttpHandler.CreateSource(testFeedUrl, Repository.Provider.GetCoreV3(), responses);
        }
        public async Task MetaDataResourceGetLatestVersions()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(
                serviceAddress + "FindPackagesById()?id='WindowsAzure.Storage'&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageFindPackagesById.xml", GetType()));
            responses.Add(
                serviceAddress + "FindPackagesById()?id='xunit'&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);

            var metadataResource = await repo.GetResourceAsync <MetadataResource>();

            var packageIdList = new List <string>()
            {
                "WindowsAzure.Storage", "xunit"
            };

            // Act
            var versions = (await metadataResource.GetLatestVersions(packageIdList, true, false, NullSourceCacheContext.Instance, NullLogger.Instance, CancellationToken.None)).ToList();

            // Assert
            Assert.Equal("WindowsAzure.Storage", versions[1].Key);
            Assert.Equal("6.2.2-preview", versions[1].Value.ToNormalizedString());
            Assert.Equal("xunit", versions[0].Key);
            Assert.Equal("2.2.0-beta1-build3239", versions[0].Value.ToNormalizedString());
        }
        public async Task DownloadResourceFromIdentityInvalidId()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "Packages(Id='xunit',Version='1.0.0-notfound')", string.Empty);
            responses.Add(serviceAddress + "FindPackagesById()?id='xunit'&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses,
                                                      ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.500Error.xml", GetType()));

            var downloadResource = await repo.GetResourceAsync <DownloadResource>();

            // Act
            using (var packagesFolder = TestDirectory.Create())
                using (var sourceCacheContext = new SourceCacheContext())
                    using (var actual = await downloadResource.GetDownloadResourceResultAsync(
                               new PackageIdentity("xunit", new NuGetVersion("1.0.0-notfound")),
                               new PackageDownloadContext(sourceCacheContext),
                               packagesFolder,
                               NullLogger.Instance,
                               CancellationToken.None))
                    {
                        // Assert
                        Assert.NotNull(actual);
                        Assert.Equal(DownloadResourceResultStatus.NotFound, actual.Status);
                    }
        }
        /// <summary>
        /// 通用解包方法 需保证bytes数组完整性
        /// </summary>
        public object StartUnPack(ref byte[] bytes, ref ProtocolEventType type)
        {
            if (bytes.Length <= 12)
            {
                return(null);
            }
            int dataCount = ProtocolUtility.UnPackInt(ref bytes);                         //数据长度

            type = (ProtocolEventType)ProtocolUtility.UnPackInt(ref bytes);               //事件类型
            ProtocolNo protoNo        = (ProtocolNo)ProtocolUtility.UnPackInt(ref bytes); //协议号
            object     protocolObject = null;

            protocolObjectDict.TryGetValue(protoNo, out protocolObject);
            if (protocolObject != null)
            {
                List <object> list             = GetProtocolUnPackMemberListByProtocolNo(protoNo);
                List <object> unPackObjectList = new List <object>();
                //递归通用解析(即遇到是类结构的成员会继续解析该类成员),所有的数据会被会解析出来并放入List<object>第三个参数
                CommonUnPack(ref bytes, list, ref unPackObjectList);
                //多线程时要加锁!这个缓存的protocolObject协议对象仅仅是为了拷贝 only for copy!when multiple thread, it must be locked!
                ((ProtocolData)protocolObject).SetData(unPackObjectList);
                //深拷贝方式 deepCopy method(way)
                return(((ProtocolData)protocolObject).Clone());
            }
            else
            {
                throw new Exception("protocolNo" + protoNo + ",not exist protocolObject in protocolObjectDict!");
            }
        }
Пример #5
0
        public void InEditorAssetsProtocolHandlerVerification()
        {
            // Unit tests are run in the editor (or visual studio which reports itself to be editor)
            string editorTestPath = ProtocolUtility.ResolvePath(@"assets://some/Asset.fbx");

            Assert.IsTrue(editorTestPath.StartsWith("file://" + Application.dataPath));
        }
        public async Task MetaDataResourceIdentityExistInvalidIdentity()
        {
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "Packages(Id='xunit',Version='1.0.0-notfound')", string.Empty);
            responses.Add(
                serviceAddress + "FindPackagesById()?id='xunit'&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses,
                                                      ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.500Error.xml", GetType()));

            var metadataResource = await repo.GetResourceAsync <MetadataResource>();

            var package = new PackageIdentity("xunit", new NuGetVersion("1.0.0-notfound"));

            // Act
            var exist = await metadataResource.Exists(package, NullSourceCacheContext.Instance, NullLogger.Instance, CancellationToken.None);

            // Assert
            Assert.False(exist);
        }
        public async Task DependencyInfo_RetrieveExactVersion_NotFound()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "Packages(Id='xunit',Version='1.0.0-notfound')", string.Empty);
            responses.Add(serviceAddress + "FindPackagesById()?id='xunit'&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses,
                                                      ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.500Error.xml", GetType()));

            var dependencyInfoResource = await repo.GetResourceAsync <DependencyInfoResource>();

            var package = new PackageIdentity("xunit", NuGetVersion.Parse("1.0.0-notfound"));

            // Act
            var result = await dependencyInfoResource.ResolvePackage(package, NuGetFramework.Parse("net45"), NullSourceCacheContext.Instance, Common.NullLogger.Instance, CancellationToken.None);

            // Assert
            Assert.Null(result);
        }
        public async Task RawSearchResource_VerifyReadSyncIsNotUsed()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(
                serviceAddress + "?q=azure%20b&skip=0&take=1&prerelease=false" +
                "&supportedFramework=.NETFramework,Version=v4.5&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.V3Search.json", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var httpSource = new TestHttpSource(new PackageSource(serviceAddress), responses);

            // throw if sync .Read is used
            httpSource.StreamWrapper = (stream) => new NoSyncReadStream(stream);

            var searchResource = new RawSearchResourceV3(httpSource, new Uri[] { new Uri(serviceAddress) });

            var searchFilter = new SearchFilter(includePrerelease: false)
            {
                SupportedFrameworks = new string[] { ".NETFramework,Version=v4.5" }
            };

            // Act
            var packages = await searchResource.Search("azure b", searchFilter, 0, 1, NullLogger.Instance, CancellationToken.None);

            var packagesArray = packages.ToArray();

            // Assert
            // Verify that the url matches the one in the response dictionary
            // Verify no failures from Sync Read
            Assert.True(packagesArray.Length > 0);
        }
Пример #9
0
        public async Task PackageSearchResourceV3_UsesReferenceCache()
        {
            // Arrange
            var responses = new Dictionary <string, string>();

            responses.Add("https://api-v3search-0.nuget.org/query?q=entityframework&skip=0&take=2&prerelease=false&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.SearchV3WithDuplicateBesidesVersion.json", GetType()));
            responses.Add("http://testsource.com/v3/index.json", JsonData.IndexWithoutFlatContainer);

            var repo = StaticHttpHandler.CreateSource("http://testsource.com/v3/index.json", Repository.Provider.GetCoreV3(), responses);

            var resource = await repo.GetResourceAsync <PackageSearchResource>();

            // Act
            var packages = (IEnumerable <PackageSearchMetadataBuilder.ClonedPackageSearchMetadata>) await resource.SearchAsync(
                "entityframework",
                new SearchFilter(false),
                skip : 0,
                take : 2,
                log : NullLogger.Instance,
                cancellationToken : CancellationToken.None);

            var first  = packages.ElementAt(0);
            var second = packages.ElementAt(1);

            // Assert
            MetadataReferenceCacheTestUtility.AssertPackagesHaveSameReferences(first, second);
        }
Пример #10
0
        public async Task PackageSearchResourceV3_GetMetadataAsync_VersionsDownloadCount()
        {
            // Arrange
            long largerThanIntMax = (long)int.MaxValue + 10;
            var  responses        = new Dictionary <string, string>();

            responses.Add("https://api-v3search-0.nuget.org/query?q=entityframework&skip=0&take=1&prerelease=false&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.EntityFrameworkSearch.json", GetType()));
            responses.Add("http://testsource.com/v3/index.json", JsonData.IndexWithoutFlatContainer);

            var repo = StaticHttpHandler.CreateSource("http://testsource.com/v3/index.json", Repository.Provider.GetCoreV3(), responses);

            var resource = await repo.GetResourceAsync <PackageSearchResource>();

            // Act
            var packages = await resource.SearchAsync(
                "entityframework",
                new SearchFilter(false),
                skip : 0,
                take : 1,
                log : NullLogger.Instance,
                cancellationToken : CancellationToken.None);

            var package = packages.SingleOrDefault();

            var versions = (await package.GetVersionsAsync()).ToList();

            // Assert
            Assert.Equal(28390569, package.DownloadCount);
            Assert.Equal(14, versions.Count());
            Assert.Equal(64099, versions[0].DownloadCount);
            // Make sure NuGet can handle package download count larger than int.MaxValue
            // EntityFrameworkSearch.json has a 2nd version with download count that is too large for an int32
            Assert.Equal(largerThanIntMax, versions[1].DownloadCount);
        }
Пример #11
0
        public async Task PackageSearchResourceV3_GetMetadataAsync()
        {
            // Arrange
            var responses = new Dictionary <string, string>();

            responses.Add("https://api-v3search-0.nuget.org/query?q=entityframework&skip=0&take=1&prerelease=false&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.EntityFrameworkSearch.json", GetType()));
            responses.Add("http://testsource.com/v3/index.json", JsonData.IndexWithoutFlatContainer);

            var repo = StaticHttpHandler.CreateSource("http://testsource.com/v3/index.json", Repository.Provider.GetCoreV3(), responses);

            var resource = await repo.GetResourceAsync <PackageSearchResource>();

            // Act
            var packages = await resource.SearchAsync(
                "entityframework",
                new SearchFilter(false),
                skip : 0,
                take : 1,
                log : NullLogger.Instance,
                cancellationToken : CancellationToken.None);

            var package = packages.SingleOrDefault();

            // Assert
            Assert.NotNull(package);
            Assert.Equal("Microsoft", package.Authors);
            Assert.Equal("Entity Framework is Microsoft's recommended data access technology for new applications.", package.Description);
            Assert.Equal(package.Description, package.Summary);
            Assert.Equal("EntityFramework", package.Title);
            Assert.Equal(string.Join(", ", "Microsoft", "EF", "Database", "Data", "O/RM", "ADO.NET"), package.Tags);
            Assert.True(package.PrefixReserved);
        }
Пример #12
0
        public async Task RawSearchResource_CancelledToken_ThrowsOperationCancelledException()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(
                serviceAddress + "?q=azure%20b&skip=0&take=1&prerelease=false" +
                "&supportedFramework=.NETFramework,Version=v4.5&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.V3Search.json", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var httpSource = new TestHttpSource(new PackageSource(serviceAddress), responses);

            httpSource.StreamWrapper = (stream) => new NoSyncReadStream(stream);

            var searchResource = new RawSearchResourceV3(httpSource, new Uri[] { new Uri(serviceAddress) });

            var searchFilter = new SearchFilter(includePrerelease: false)
            {
                SupportedFrameworks = new string[] { ".NETFramework,Version=v4.5" }
            };

            var tokenSource = new CancellationTokenSource();

            tokenSource.Cancel();

            // Act/Assert
            await Assert.ThrowsAsync <TaskCanceledException> (() =>
                                                              searchResource.Search("Sentry", searchFilter, 0, 1, NullLogger.Instance, tokenSource.Token));
        }
        public async Task PackageMetadataResource_PackageIdentity_NotFound()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "FindPackagesById()?id='WindowsAzure.Storage'&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.NotFoundFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress + "Packages(Id='WindowsAzure.Storage',Version='0.0.0')",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.NotFoundFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);

            var packageMetadataResource = await repo.GetResourceAsync <PackageMetadataResource>();

            var packageIdentity = new PackageIdentity("WindowsAzure.Storage", new NuGetVersion("0.0.0"));

            // Act
            var metadata = await packageMetadataResource.GetMetadataAsync(packageIdentity, NullSourceCacheContext.Instance, NullLogger.Instance, CancellationToken.None);

            // Assert
            Assert.Null(metadata);
        }
        public async Task DependencyInfoResourceV2Feed_GetDependencyInfoByPackageIdentity()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "Packages(Id='WindowsAzure.Storage',Version='4.3.2-preview')",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageGetPackages.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);

            var dependencyInfoResource = await repo.GetResourceAsync <DependencyInfoResource>();

            var packageIdentity = new PackageIdentity("WindowsAzure.Storage", new NuGetVersion("4.3.2-preview"));

            // Act
            var dependencyInfo = await dependencyInfoResource.ResolvePackage(packageIdentity,
                                                                             NuGetFramework.Parse("aspnetcore50"),
                                                                             NullSourceCacheContext.Instance,
                                                                             NullLogger.Instance,
                                                                             CancellationToken.None);

            // Assert
            Assert.Equal(43, dependencyInfo.Dependencies.Count());
        }
        public async Task DependencyInfo_RetrieveExactVersion()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "Packages(Id='xunit',Version='2.1.0-beta1-build2945')",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.Xunit.2.1.0-beta1-build2945GetPackages.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);

            var dependencyInfoResource = await repo.GetResourceAsync <DependencyInfoResource>();

            var package = new PackageIdentity("xunit", NuGetVersion.Parse("2.1.0-beta1-build2945"));
            var dep1    = new PackageIdentity("xunit.core", NuGetVersion.Parse("2.1.0-beta1-build2945"));
            var dep2    = new PackageIdentity("xunit.assert", NuGetVersion.Parse("2.1.0-beta1-build2945"));

            // Act
            var result = await dependencyInfoResource.ResolvePackage(package, NuGetFramework.Parse("net45"), NullSourceCacheContext.Instance, Common.NullLogger.Instance, CancellationToken.None);

            // Assert
            Assert.Equal(package, result, PackageIdentity.Comparer);
            Assert.Equal(2, result.Dependencies.Count());
            Assert.Equal("[2.1.0-beta1-build2945, 2.1.0-beta1-build2945]", result.Dependencies.Single(dep => dep.Id == "xunit.core").VersionRange.ToNormalizedString());
            Assert.Equal("[2.1.0-beta1-build2945, 2.1.0-beta1-build2945]", result.Dependencies.Single(dep => dep.Id == "xunit.assert").VersionRange.ToNormalizedString());
        }
        public async Task GetAllVersionsAsync_NoErrorsOnNoContent()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "FindPackagesById()?id='a'", "204");

            var repo   = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);
            var logger = new TestLogger();

            using (var cacheContext = new SourceCacheContext())
            {
                var resource = await repo.GetResourceAsync <FindPackageByIdResource>();

                // Act
                var versions = await resource.GetAllVersionsAsync(
                    "a",
                    cacheContext,
                    logger,
                    CancellationToken.None);

                // Assert
                // Verify no items returned, and no exceptions were thrown above
                Assert.Equal(0, versions.Count());
            }
        }
        public async Task DependencyInfoResourceV2Feed_GetDependencyInfoById()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "FindPackagesById()?id='WindowsAzure.Storage'&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);

            var dependencyInfoResource = await repo.GetResourceAsync <DependencyInfoResource>();

            // Act
            var dependencyInfoList = await dependencyInfoResource.ResolvePackages("WindowsAzure.Storage",
                                                                                  NuGetFramework.Parse("aspnetcore50"),
                                                                                  NullSourceCacheContext.Instance,
                                                                                  NullLogger.Instance,
                                                                                  CancellationToken.None);

            // Assert
            Assert.Equal(47, dependencyInfoList.Count());
        }
Пример #18
0
        public async Task PackageSearchResourceV2Feed_Search100()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(
                serviceAddress + "Search()?$filter=IsLatestVersion&searchTerm='azure'&targetFramework='net40-client'" +
                "&includePrerelease=false&$skip=0&$top=100&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.AzureSearch100.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);

            var packageSearchResource = await repo.GetResourceAsync <PackageSearchResource>();

            var searchFilter = new SearchFilter(includePrerelease: false)
            {
                SupportedFrameworks = new string[] { "net40-Client" }
            };

            // Act
            var searchResult = await packageSearchResource.SearchAsync("azure", searchFilter, 0, 100, NullLogger.Instance, CancellationToken.None);

            // Assert
            Assert.Equal(100, searchResult.Count());
        }
        public async Task DependencyInfo_RetrieveDependencies()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress();

            var responses = new Dictionary <string, string>();

            responses.Add(serviceAddress + "FindPackagesById()?id='xunit'&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);

            var repo = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);

            var dependencyInfoResource = await repo.GetResourceAsync <DependencyInfoResource>();

            var package = new PackageIdentity("xunit", NuGetVersion.Parse("2.1.0-beta1-build2945"));

            // filter to keep this test consistent
            var filterRange = new VersionRange(NuGetVersion.Parse("2.0.0-rc4-build2924"), true, NuGetVersion.Parse("2.1.0-beta1-build2945"), true);

            // Act
            var results = await dependencyInfoResource.ResolvePackages("xunit", NuGetFramework.Parse("net45"), NullSourceCacheContext.Instance, Common.NullLogger.Instance, CancellationToken.None);

            var filtered = results.Where(result => filterRange.Satisfies(result.Version));

            var target = filtered.Single(p => PackageIdentity.Comparer.Equals(p, package));

            // Assert
            Assert.Equal(3, filtered.Count());
            Assert.Equal(2, target.Dependencies.Count());
            Assert.Equal("[2.1.0-beta1-build2945, 2.1.0-beta1-build2945]", target.Dependencies.Single(dep => dep.Id == "xunit.core").VersionRange.ToNormalizedString());
            Assert.Equal("[2.1.0-beta1-build2945, 2.1.0-beta1-build2945]", target.Dependencies.Single(dep => dep.Id == "xunit.assert").VersionRange.ToNormalizedString());
        }
Пример #20
0
 /// <summary>
 /// 通用打包方法
 /// </summary>
 /// <param name="bytes"></param>
 /// <param name="objectList"></param>
 private void CommonPack(ref byte[] bytes, List <object> objectList)
 {
     foreach (var o in objectList)
     {
         if (o is int || o is DataID)
         {
             ProtocolUtility.PacketInt(ref bytes, (int)o);
         }
         else if (o is float)
         {
             ProtocolUtility.PacketFloat(ref bytes, (float)o);
         }
         else if (o is double)
         {
             ProtocolUtility.PacketDouble(ref bytes, (double)o);
         }
         else if (o is bool)
         {
             ProtocolUtility.PacketBool(ref bytes, (bool)o);
         }
         else if (o is string)
         {
             ProtocolUtility.PacketString(ref bytes, (string)o);
         }
         else if (o.GetType().BaseType == typeof(ClassBase))
         {
             CommonPack(ref bytes, ((ClassBase)o).objectList);
         }
         else
         {
             Debug.LogError("发送了一个未经处理的类型!" + o.GetType());
         }
     }
 }
Пример #21
0
    /// <summary>
    /// 通用解包方法 需保证bytes数组完整性
    /// </summary>
    public object StartUnPack(ref byte[] bytes, ref ProtocolEventType type)
    {
        if (bytes.Length <= 12)
        {
            return(null);
        }
        int dataCount = ProtocolUtility.UnPackInt(ref bytes);                         //数据长度

        type = (ProtocolEventType)ProtocolUtility.UnPackInt(ref bytes);               //事件类型
        ProtocolNo protoNo        = (ProtocolNo)ProtocolUtility.UnPackInt(ref bytes); //协议号
        object     protocolObject = null;

        protocolObjectDict.TryGetValue(protoNo, out protocolObject);
        if (protocolObject != null)
        {
            List <object> list             = GetProtocolUnPackMemberListByProtocolNo(protoNo); //协议解包类结构如:{int,string,class}
            List <object> unPackObjectList = new List <object>();
            CommonUnPack(ref bytes, list, ref unPackObjectList);                               //开始递归解包
            ((ProtocolData)protocolObject).SetData(unPackObjectList);
            return(((ProtocolData)protocolObject).Clone());
        }
        else
        {
            Debug.LogError("protocolNo" + protoNo + ",not exist protocolObject in protocolObjectDict!");
            return(null);
        }
    }
Пример #22
0
        public async Task PackageSearchResourceV3_GetMetadataAsync_NotFound()
        {
            // Arrange
            var responses = new Dictionary <string, string>();

            responses.Add("https://api-v3search-0.nuget.org/query?q=yabbadabbadoo&skip=0&take=1&prerelease=false&semVerLevel=2.0.0",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.EmptySearchResponse.json", GetType()));
            responses.Add("http://testsource.com/v3/index.json", JsonData.IndexWithoutFlatContainer);

            var repo = StaticHttpHandler.CreateSource("http://testsource.com/v3/index.json", Repository.Provider.GetCoreV3(), responses);

            var resource = await repo.GetResourceAsync <PackageSearchResource>();

            // Act
            var packages = await resource.SearchAsync(
                "yabbadabbadoo",
                new SearchFilter(false),
                skip : 0,
                take : 1,
                log : NullLogger.Instance,
                cancellationToken : CancellationToken.None);

            // Assert
            Assert.Empty(packages);
        }
        public NuGetPackageSearchServiceTests(GlobalServiceProvider globalServiceProvider)
            : base(globalServiceProvider)
        {
            _installedPackages  = new List <IPackageReferenceContextInfo>();
            _transitivePackages = new List <IPackageReferenceContextInfo>();
            _projects           = new List <IProjectContextInfo>
            {
                new ProjectContextInfo(
                    Guid.NewGuid().ToString(),
                    ProjectModel.ProjectStyle.PackageReference,
                    NuGetProjectKind.PackageReference)
            };
            var testFeedUrl = "https://testsource.com/v3/index.json";
            var query       = "https://api-v2v3search-0.nuget.org/query";
            var responses   = new Dictionary <string, string>
            {
                { testFeedUrl, ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.index.json", GetType()) },
                { query + "?q=nuget&skip=0&take=26&prerelease=true&semVerLevel=2.0.0", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.nugetSearchPage1.json", GetType()) },
                { query + "?q=nuget&skip=25&take=26&prerelease=true&semVerLevel=2.0.0", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.nugetSearchPage2.json", GetType()) },
                { query + "?q=&skip=0&take=26&prerelease=true&semVerLevel=2.0.0", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.blankSearchPage.json", GetType()) },
                { "https://api.nuget.org/v3/registration3-gz-semver2/nuget.core/index.json", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.nugetCoreIndex.json", GetType()) },
                { "https://api.nuget.org/v3/registration3-gz-semver2/microsoft.extensions.logging.abstractions/index.json", ProtocolUtility.GetResource("NuGet.PackageManagement.VisualStudio.Test.compiler.resources.loggingAbstractions.json", GetType()) }
            };

            _sourceRepository = StaticHttpHandler.CreateSource(testFeedUrl, Repository.Provider.GetCoreV3(), responses);
        }
        public async Task PackagePrefixReservation_FromOneSource()
        {
            var solutionManager = Mock.Of <INuGetSolutionManagerService>();
            var uiContext       = new Mock <INuGetUIContext>();

            uiContext.Setup(x => x.SolutionManagerService)
            .Returns(solutionManager);

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

            // Arrange
            var responses = new Dictionary <string, string>
            {
                {
                    "https://api-v3search-0.nuget.org/query?q=EntityFramework&skip=0&take=26&prerelease=false&semVerLevel=2.0.0",
                    ProtocolUtility.GetResource("NuGet.PackageManagement.UI.Test.compiler.resources.EntityFrameworkSearch.json", GetType())
                },
                { "http://testsource.com/v3/index.json", JsonData.IndexWithoutFlatContainer }
            };

            var repo         = StaticHttpHandler.CreateSource("http://testsource.com/v3/index.json", Repository.Provider.GetCoreV3(), responses);
            var repositories = new List <SourceRepository>
            {
                repo
            };

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

            var packageFeed = new MultiSourcePackageFeed(repositories, logger: null, telemetryService: null);
            var loader      = new PackageItemLoader(context, packageFeed, "EntityFramework", includePrerelease: false);

            var loaded = new List <PackageItemListViewModel>();

            foreach (var page in Enumerable.Range(0, 5))
            {
                await loader.LoadNextAsync(progress : null, CancellationToken.None);

                while (loader.State.LoadingStatus == LoadingStatus.Loading)
                {
                    await Task.Delay(TimeSpan.FromSeconds(1));

                    await loader.UpdateStateAsync(progress : null, CancellationToken.None);
                }

                var items = loader.GetCurrent();
                loaded.AddRange(items);

                if (loader.State.LoadingStatus != LoadingStatus.Ready)
                {
                    break;
                }
            }

            // Resource only has one item
            var item = loaded.First();

            Assert.True(item.PrefixReserved);
        }
Пример #25
0
        public async Task GetDependencyInfoAsync_GetOriginalIdentity_IdNotInResponseAsync()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var serviceAddress = ProtocolUtility.CreateServiceAddress();
                var package        = await SimpleTestPackageUtility.CreateFullPackageAsync(workingDir, "WindowsAzure.Storage", "6.2.2-preview");

                var packageBytes = File.ReadAllBytes(package.FullName);

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        serviceAddress,
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(string.Empty)
                        })
                    },
                    {
                        serviceAddress + "FindPackagesById()?id='WINDOWSAZURE.STORAGE'&semVerLevel=2.0.0",
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageFindPackagesById.xml", GetType()))
                        })
                    },
                    {
                        "https://www.nuget.org/api/v2/package/WindowsAzure.Storage/6.2.2-preview",
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new ByteArrayContent(packageBytes)
                        })
                    }
                };

                var repo   = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);
                var logger = new TestLogger();

                using (var cacheContext = new SourceCacheContext())
                {
                    var resource = await repo.GetResourceAsync <FindPackageByIdResource>();

                    // Act
                    var info = await resource.GetDependencyInfoAsync(
                        "WINDOWSAZURE.STORAGE",
                        new NuGetVersion("6.2.2-PREVIEW"),
                        cacheContext,
                        logger,
                        CancellationToken.None);

                    // Assert
                    Assert.IsType <RemoteV2FindPackageByIdResource>(resource);
                    Assert.Equal("WindowsAzure.Storage", info.PackageIdentity.Id);
                    Assert.Equal("6.2.2-preview", info.PackageIdentity.Version.ToNormalizedString());
                }
            }
        }
        public async Task GetDependencyInfoAsync_GetOriginalIdentity_IdInResponse()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var serviceAddress = ProtocolUtility.CreateServiceAddress();
                var package        = SimpleTestPackageUtility.CreateFullPackage(workingDir, "xunit", "2.2.0-beta1-build3239");
                var packageBytes   = File.ReadAllBytes(package.FullName);

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        serviceAddress,
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(string.Empty)
                        })
                    },
                    {
                        serviceAddress + "FindPackagesById()?id='XUNIT'",
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml", GetType()))
                        })
                    },
                    {
                        "https://www.nuget.org/api/v2/package/xunit/2.2.0-beta1-build3239",
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new ByteArrayContent(packageBytes)
                        })
                    }
                };

                var repo   = StaticHttpHandler.CreateSource(serviceAddress, Repository.Provider.GetCoreV3(), responses);
                var logger = new TestLogger();

                using (var cacheContext = new SourceCacheContext())
                {
                    var resource = await repo.GetResourceAsync <FindPackageByIdResource>();

                    // Act
                    var info = await resource.GetDependencyInfoAsync(
                        "XUNIT",
                        new NuGetVersion("2.2.0-BETA1-build3239"),
                        cacheContext,
                        logger,
                        CancellationToken.None);

                    // Assert
                    Assert.IsType <RemoteV2FindPackageByIdResource>(resource);
                    Assert.Equal("xunit", info.PackageIdentity.Id);
                    Assert.Equal("2.2.0-beta1-build3239", info.PackageIdentity.Version.ToNormalizedString());
                }
            }
        }
Пример #27
0
        public void MaxLength()
        {
            using var reader = m_database.Connection.ExecuteReader(@"select coll.ID, cs.MAXLEN from information_schema.collations coll inner join information_schema.character_sets cs using(CHARACTER_SET_NAME);");
            while (reader.Read())
            {
                var characterSet = (CharacterSet)reader.GetInt32(0);
                var maxLength    = reader.GetInt32(1);

                Assert.Equal(maxLength, ProtocolUtility.GetBytesPerCharacter(characterSet));
            }
        }
Пример #28
0
        public void SplitAndResolveProtocolVerification()
        {
            string testPath1 = @"resources://test/Try-some.Unexpected Characters/soemthingelse.file";
            string testPath2 = @"file://*****:*****@"http://www.google.com";
            string testPath4 = @"assets://some/Asset.fbx";

            // Resolve should strip off the resources:// or assets://, but not file:// or http://
            Assert.IsFalse(ProtocolUtility.SplitAndResolve(testPath1).Second.StartsWith("resources"));
            Assert.IsTrue(ProtocolUtility.SplitAndResolve(testPath2).Second.StartsWith("file"));
            Assert.IsTrue(ProtocolUtility.SplitAndResolve(testPath3).Second.StartsWith("http"));
            Assert.IsFalse(ProtocolUtility.SplitAndResolve(testPath4).Second.StartsWith("assets"));
        }
Пример #29
0
        public async Task TestListDelistedPrereleaseAllVersions()
        {
            // Arrange
            var serviceAddress = ProtocolUtility.CreateServiceAddress() + "api/v2";

            var responses = new Dictionary <string, string>();

            responses.Add(
                serviceAddress + "/Search()?$orderby=Id&searchTerm='Windows.AzureStorage'&targetFramework=''" +
                "&includePrerelease=true&$skip=0&$top=30&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageSearchPackage30Entries.xml", GetType()));
            responses.Add(
                serviceAddress + "/Search()?$orderby=Id&searchTerm='Windows.AzureStorage'&targetFramework=''" +
                "&includePrerelease=true&$skip=30&$top=30&semVerLevel=2.0.0",
                ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.WindowsAzureStorageSearchPackage17Entries.xml", GetType()));
            responses.Add(serviceAddress, string.Empty);
            responses.Add(serviceAddress + "/$metadata",
                          ProtocolUtility.GetResource("NuGet.Protocol.Tests.compiler.resources.MetadataTT.xml", GetType()));

            var httpSource = new TestHttpSource(new PackageSource(serviceAddress), responses);

            var parser         = new V2FeedParser(httpSource, serviceAddress);
            var legacyResource = new LegacyFeedCapabilityResourceV2Feed(parser, serviceAddress);
            var resource       = new V2FeedListResource(parser, legacyResource, serviceAddress);


            var enumerable = await resource.ListAsync(searchTerm : "Windows.AzureStorage",
                                                      prerelease : true, allVersions : true, includeDelisted : true, logger : NullLogger.Instance, token : CancellationToken.None);

            //Only 2 packages are listed in this resource
            int ExpectedCount = 47;
            int ActualCount   = 0;
            var enumerator    = enumerable.GetEnumeratorAsync();


            while (await enumerator.MoveNextAsync())
            {
                if (enumerator.Current != null)
                {
                    ActualCount++;
                    Assert.True(ExpectedCount >= ActualCount, "Too many results");
                }
                else
                {
                    Assert.False(false, "Null Value, this shouldn't happen.");
                }
            }

            Assert.Equal(ExpectedCount, ActualCount);
        }
Пример #30
0
        public void SplitProtocolVerification()
        {
            string testPath1 = @"resources://test/Try-some.Unexpected Characters/soemthingelse.file";
            string testPath2 = @"file://*****:*****@"http://www.google.com";

            Assert.IsTrue(ProtocolUtility.SplitProtocol(testPath1).First == "resources");
            Assert.IsTrue(ProtocolUtility.SplitProtocol(testPath1).Second == "test/Try-some.Unexpected Characters/soemthingelse.file");

            Assert.IsTrue(ProtocolUtility.SplitProtocol(testPath2).First == "file");
            Assert.IsTrue(ProtocolUtility.SplitProtocol(testPath2).Second == "C:/Windows/System32/");

            Assert.IsTrue(ProtocolUtility.SplitProtocol(testPath3).First == "http");
            Assert.IsTrue(ProtocolUtility.SplitProtocol(testPath3).Second == "www.google.com");
        }