Пример #1
0
        public async Task CopyPackagesToOriginalCaseAsync_WhenPackageMustComeFromProvider_ConvertsPackages()
        {
            // Arrange
            using (var workingDirectory = TestDirectory.Create())
            {
                var packagesDirectory = Path.Combine(workingDirectory, "packages");
                var sourceDirectory   = Path.Combine(workingDirectory, "source");

                // Add the package to the source.
                var identity    = new PackageIdentity("PackageA", NuGetVersion.Parse("1.0.0-Beta"));
                var packagePath = SimpleTestPackageUtility.CreateFullPackage(
                    sourceDirectory,
                    identity.Id,
                    identity.Version.ToString());

                var logger = new TestLogger();
                var graph  = GetRestoreTargetGraph(identity, packagePath, logger);

                var request  = GetRestoreRequest(packagesDirectory, logger);
                var resolver = new VersionFolderPathResolver(packagesDirectory, isLowercase: false);

                var target = new OriginalCaseGlobalPackageFolder(request);

                // Act
                await target.CopyPackagesToOriginalCaseAsync(
                    new[] { graph },
                    CancellationToken.None);

                // Assert
                Assert.True(File.Exists(resolver.GetPackageFilePath(identity.Id, identity.Version)));
                Assert.Equal(1, logger.Messages.Count(x => x.Contains(identity.ToString())));
            }
        }
Пример #2
0
        public async Task PushCommand_AbsolutePathSource()
        {
            using (TestDirectory workingDir = TestDirectory.Create())
            {
                // Arrange (create a test package)
                DirectoryInfo packagePushDest = new DirectoryInfo(Path.Combine(workingDir, "packagePushDest"));
                packagePushDest.Create();

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

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

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

                // Assert
                string destFile = Path.Combine(packagePushDest.FullName, packageInfo.Name);
                Assert.Equal(true, File.Exists(destFile));
            }
        }
        public async Task PackageUpdateResource_PackageNotExistOnNuGetOrgPushing()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source = "https://nuget.smbsrc.net/";

                HttpRequestMessage symbolRequest = null;
                var apiKey = "serverapikey";

                var packageInfo       = SimpleTestPackageUtility.CreateFullPackage(workingDir, "test", "1.0.0");
                var symbolPackageInfo = SimpleTestPackageUtility.CreateSymbolPackage(workingDir, "test", "1.0.0");

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://nuget.smbsrc.net/api/v2/package/",
                        request =>
                        {
                            symbolRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://www.nuget.org/api/v2/package/create-verification-key/test/1.0.0",
                        request =>
                        {
                            var content  = new StringContent(String.Format(JsonData.tempApiKeyJsonData, "tempkey"), Encoding.UTF8, "application/json");
                            var response = new HttpResponseMessage(HttpStatusCode.OK);
                            response.Content = content;
                            return(Task.FromResult(response));
                        }
                    }
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                UserAgent.SetUserAgentString(new UserAgentStringBuilder("test client"));

                // Act
                await resource.Push(
                    packagePath : packageInfo.FullName,
                    symbolSource : null,
                    timeoutInSecond : 5,
                    disableBuffering : false,
                    getApiKey : _ => apiKey,
                    getSymbolApiKey : _ => null,
                    log : NullLogger.Instance);

                // Assert
                IEnumerable <string> apiValues;
                IEnumerable <string> symbolClientVersionValues;
                symbolRequest.Headers.TryGetValues(ApiKeyHeader, out apiValues);
                symbolRequest.Headers.TryGetValues(NuGetClientVersionHeader, out symbolClientVersionValues);

                Assert.Equal("tempkey", apiValues.First());
                Assert.NotNull(symbolClientVersionValues.First());
            }
        }
        public async Task DependencyTypeConstraint_RootProjectIsUsedOverPackage()
        {
            // Arrange
            var sources = new List <PackageSource>();

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

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

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

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

                var project1PackagePath = SimpleTestPackageUtility.CreateFullPackage(
                    packageSource.FullName,
                    "project1",
                    "1.0.0");

                await GlobalFolderUtility.AddPackageToGlobalFolderAsync(project1PackagePath, packagesDir);

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

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

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

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

                // Assert
                Assert.True(result.Success);
                Assert.Equal(0, lockFile.Libraries.Count);
            }
        }
Пример #5
0
        public async Task RestoreCommand_FindInV2FolderWithDifferentCasing()
        {
            // Arrange
            var sources = new List <PackageSource>();

            // Both TxMs reference packageA, but they are different types.
            // Verify that the reference does not show up under libraries.
            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.3"": {
                    ""dependencies"": {
                        ""PACKAGEA"": ""4.0.0""
                    }
                }
              }
            }";

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

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

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

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

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

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, "packageA", "4.0.0");

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

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

                // Assert
                Assert.True(result.Success);
                Assert.Equal(1, lockFile.Libraries.Count);
            }
        }
        public async Task HttpFileSystemBasedFindPackageById_GetOriginalIdentity()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source       = "http://testsource.com/v3-with-flat-container/index.json";
                var package      = SimpleTestPackageUtility.CreateFullPackage(workingDir, "DeepEqual", "1.4.0.1-rc");
                var packageBytes = File.ReadAllBytes(package.FullName);

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        source,
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(JsonData.IndexWithFlatContainer)
                        })
                    },
                    {
                        "https://api.nuget.org/v3-flatcontainer/deepequal/index.json",
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(JsonData.DeepEqualFlatContainerIndex)
                        })
                    },
                    {
                        "https://api.nuget.org/v3-flatcontainer/deepequal/1.4.0.1-rc/deepequal.1.4.0.1-rc.nupkg",
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new ByteArrayContent(packageBytes)
                        })
                    }
                };

                var repo   = StaticHttpHandler.CreateSource(source, 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(
                        "DEEPEQUAL",
                        new NuGetVersion("1.4.0.1-RC"),
                        cacheContext,
                        logger,
                        CancellationToken.None);

                    // Assert
                    Assert.IsType <HttpFileSystemBasedFindPackageByIdResource>(resource);
                    Assert.Equal("DeepEqual", info.PackageIdentity.Id);
                    Assert.Equal("1.4.0.1-rc", info.PackageIdentity.Version.ToNormalizedString());
                }
            }
        }
        public async Task GetDependencyInfoAsync_GetOriginalIdentity_IdNotInResponse()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var serviceAddress = ProtocolUtility.CreateServiceAddress();
                var package        = SimpleTestPackageUtility.CreateFullPackage(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'",
                        _ => 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());
                }
            }
        }
Пример #8
0
        public async Task RemoteV2FindPackageById_GetOriginalIdentity_IdInResponse()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var serviceAddress = TestUtility.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(TestUtility.GetResource("NuGet.Protocol.Core.v3.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 identity = await resource.GetOriginalIdentityAsync(
                        "XUNIT",
                        new NuGetVersion("2.2.0-BETA1-build3239"),
                        cacheContext,
                        logger,
                        CancellationToken.None);

                    // Assert
                    Assert.IsType <RemoteV2FindPackageByIdResource>(resource);
                    Assert.Equal("xunit", identity.Id);
                    Assert.Equal("2.2.0-beta1-build3239", identity.Version.ToNormalizedString());
                }
            }
        }
Пример #9
0
        public async Task RestoreCommand_PackageWithSameName()
        {
            // Arrange
            var sources = new List <PackageSource>();

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

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

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

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, "project1", "1.0.0");

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

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

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

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

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

                // Assert
                Assert.False(result.Success);
                Assert.Equal(1, result.GetAllUnresolved().Count);
                Assert.True(logger.ErrorMessages.Contains("Unable to resolve 'project1 (>= 1.0.0)' for '.NETFramework,Version=v4.5'."));
            }
        }
Пример #10
0
            internal static PluginFindPackageByIdResourceTest Create(
                MessageResponseCode responseCode = MessageResponseCode.Error)
            {
                var packageIdentity = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0"));
                var testDirectory   = TestDirectory.Create();
                var packageSource   = new PackageSource("http://unit.test");
                var package         = SimpleTestPackageUtility.CreateFullPackage(
                    testDirectory.Path,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString());
                var packageBytes = File.ReadAllBytes(package.FullName);
                var plugin       = new Mock <IPlugin>();
                var dispatcher   = new Mock <IMessageDispatcher>();
                var connection   = new Mock <IConnection>();

                dispatcher.SetupGet(x => x.RequestHandlers)
                .Returns(new RequestHandlers());

                connection.SetupGet(x => x.MessageDispatcher)
                .Returns(dispatcher.Object);

                var versions = responseCode == MessageResponseCode.Success ? new[] { "1.0.0", "2.0.0", "3.0.0" } : null;
                var response = new GetPackageVersionsResponse(responseCode, versions);

                connection.Setup(x => x.SendRequestAndReceiveResponseAsync <GetPackageVersionsRequest, GetPackageVersionsResponse>(
                                     It.Is <MessageMethod>(m => m == MessageMethod.GetPackageVersions),
                                     It.Is <GetPackageVersionsRequest>(
                                         c => string.Equals(c.PackageId, packageIdentity.Id, StringComparison.OrdinalIgnoreCase) &&
                                         c.PackageSourceRepository == packageSource.Source),
                                     It.IsAny <CancellationToken>()))
                .ReturnsAsync(response);

                plugin.SetupGet(x => x.Connection)
                .Returns(connection.Object);

                var utilities           = new Mock <IPluginMulticlientUtilities>();
                var credentialService   = new Mock <ICredentialService>();
                var credentialsProvider = new GetCredentialsRequestHandler(
                    plugin.Object,
                    proxy: null,
                    credentialService: credentialService.Object);

                var resource = new PluginFindPackageByIdResource(
                    plugin.Object,
                    utilities.Object,
                    packageSource);

                return(new PluginFindPackageByIdResourceTest(
                           resource,
                           package,
                           packageIdentity,
                           connection,
                           new SourceCacheContext(),
                           testDirectory));
            }
Пример #11
0
        public async Task RestoreCommand_PathInPackageLibrary()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir   = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var packageSource = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var project1      = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                packageSource.Create();
                project1.Create();

                var sources = new List <PackageSource>();
                sources.Add(new PackageSource(packageSource.FullName));

                var project1Json = @"
                {
                  ""frameworks"": {
                    ""netstandard1.0"": {
                      ""dependencies"": {
                        ""packageA"": ""1.0.0""
                      }
                    }
                  }
                }";

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

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

                var logger  = new TestLogger();
                var request = new TestRestoreRequest(spec1, sources, packagesDir.FullName, logger);
                request.LockFilePath = Path.Combine(project1.FullName, "project.lock.json");

                var packageAContext = new SimpleTestPackageContext("packageA");
                packageAContext.AddFile("lib/netstandard1.0/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext);

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

                var lockFile = result.LockFile;

                // Assert
                Assert.True(result.Success);
                var library = lockFile.Libraries.FirstOrDefault(l => l.Name == "packageA");
                Assert.NotNull(library);
                Assert.Equal("packagea/1.0.0", library.Path);
            }
        }
Пример #12
0
            public DownloadResourceResult InitializePackage()
            {
                var context = new SimpleTestPackageContext(PackageIdentity);

                context.PackageTypes.Clear();
                context.PackageTypes.AddRange(PackageTypes);

                var package = SimpleTestPackageUtility.CreateFullPackage(
                    TestDirectory,
                    context);

                return(new DownloadResourceResult(package.OpenRead()));
            }
Пример #13
0
        public async Task PackageUpdateResource_AllowsApiKeyWhenPushing()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source = "https://www.nuget.org/api/v2";
                HttpRequestMessage actualRequest = null;
                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://www.nuget.org/api/v2/",
                        request =>
                        {
                            actualRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    }
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                var apiKey = "SomeApiKey";

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

                // Act
                await resource.Push(
                    packagePath : packageInfo.FullName,
                    symbolSource : null,
                    timeoutInSecond : 5,
                    disableBuffering : false,
                    getApiKey : _ => apiKey,
                    getSymbolApiKey : _ => null,
                    noServiceEndpoint : false,
                    log : NullLogger.Instance);

                // Assert
                Assert.NotNull(actualRequest);
                Assert.Equal(HttpMethod.Put, actualRequest.Method);

                IEnumerable <string> values;
                actualRequest.Headers.TryGetValues(ProtocolConstants.ApiKeyHeader, out values);
                Assert.Equal(1, values.Count());
                Assert.Equal(apiKey, values.First());

                Assert.False(
                    actualRequest.GetOrCreateConfiguration().PromptOn403,
                    "When the API key is provided, the user should not be prompted on HTTP 403.");
            }
        }
Пример #14
0
            internal static HttpFileSystemBasedFindPackageByIdResourceTest Create()
            {
                var packageIdentity = new PackageIdentity(id: "DeepEqual", version: NuGetVersion.Parse("1.4.0"));
                var testDirectory   = TestDirectory.Create();
                var packageSource   = new PackageSource("http://unit.test/v3-flatcontainer");
                var package         = SimpleTestPackageUtility.CreateFullPackage(
                    testDirectory.Path,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString());
                var packageBytes = File.ReadAllBytes(package.FullName);

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        $"{packageSource.Source}/deepequal/index.json",
                        request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(JsonData.DeepEqualFlatContainerIndex)
                        })
                    },
                    {
                        $"{packageSource.Source}/deepequal/1.4.0/deepequal.1.4.0.nupkg",
                        _ => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new ByteArrayContent(packageBytes)
                        })
                    },
                    {
                        $"{packageSource.Source}/a/index.json",
                        request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound))
                    }
                };

                var baseUris = new List <Uri>()
                {
                    packageSource.SourceUri
                };
                var httpSource = new TestHttpSource(packageSource, responses);
                var resource   = new HttpFileSystemBasedFindPackageByIdResource(
                    baseUris,
                    httpSource);

                return(new HttpFileSystemBasedFindPackageByIdResourceTest(
                           resource,
                           package,
                           packageIdentity,
                           new SourceCacheContext(),
                           httpSource,
                           testDirectory));
            }
            internal static LocalV3FindPackageByIdResourceTest Create(bool createFiles = false)
            {
                var packageIdentity  = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0"));
                var testDirectory    = TestDirectory.Create();
                var packageDirectory = Directory.CreateDirectory(
                    Path.Combine(
                        testDirectory.Path,
                        packageIdentity.Id,
                        packageIdentity.Version.ToNormalizedString()));
                var      packageSource = new PackageSource(testDirectory.Path);
                FileInfo package       = null;

                // Only a few tests have outcomes that rely on the presence of these files,
                // so only create them if necessary.
                if (createFiles)
                {
                    package = SimpleTestPackageUtility.CreateFullPackage(
                        packageDirectory.FullName,
                        packageIdentity.Id,
                        packageIdentity.Version.ToNormalizedString());

                    File.WriteAllText(
                        Path.Combine(packageDirectory.FullName, $"{packageIdentity.Id}.nuspec"),
                        $@"<?xml version=""1.0"" encoding=""utf-8""?>
                        <package>
                            <metadata>
                                <id>{packageIdentity.Id}</id>
                                <version>{packageIdentity.Version.ToNormalizedString()}</version>
                                <title />
                                <frameworkAssemblies>
                                    <frameworkAssembly assemblyName=""System.Runtime"" />
                                </frameworkAssemblies>
                            </metadata>
                        </package>");

                    File.WriteAllText(
                        Path.Combine(
                            packageDirectory.FullName,
                            $"{packageIdentity.Id}.{packageIdentity.Version.ToNormalizedString()}.nupkg.sha512"),
                        string.Empty);
                }

                var resource = new LocalV3FindPackageByIdResource(packageSource);

                return(new LocalV3FindPackageByIdResourceTest(
                           resource,
                           package,
                           packageIdentity,
                           testDirectory));
            }
Пример #16
0
        public async Task PackageUpdateResource_NoServiceEndpointOnCustomServer_ShouldAddEndpoint()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source = "https://nuget.customsrc.net/";

                HttpRequestMessage sourceRequest = null;
                var apiKey = "serverapikey";

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

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://nuget.customsrc.net/api/v2/package/",
                        request =>
                        {
                            sourceRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    }
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                UserAgent.SetUserAgentString(new UserAgentStringBuilder("test client"));

                // Act
                await resource.Push(
                    packagePath : packageInfo.FullName,
                    symbolSource : null,
                    timeoutInSecond : 5,
                    disableBuffering : false,
                    getApiKey : _ => apiKey,
                    getSymbolApiKey : _ => null,
                    noServiceEndpoint : false,
                    log : NullLogger.Instance);

                // Assert
                Assert.NotNull(sourceRequest);
                Assert.Equal(HttpMethod.Put, sourceRequest.Method);
                Assert.Equal(source + "api/v2/package/", sourceRequest.RequestUri.AbsoluteUri);
            }
        }
            internal static LocalV2FindPackageByIdResourceTest Create()
            {
                var packageIdentity   = new PackageIdentity(id: "a", version: NuGetVersion.Parse("1.0.0"));
                var testDirectory     = TestDirectory.Create();
                var packagesDirectory = Directory.CreateDirectory(Path.Combine(testDirectory.Path, "packages"));
                var packageSource     = new PackageSource(testDirectory.Path);
                var package           = SimpleTestPackageUtility.CreateFullPackage(
                    packagesDirectory.FullName,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString());
                var packageBytes = File.ReadAllBytes(package.FullName);
                var resource     = new LocalV2FindPackageByIdResource(packageSource);

                return(new LocalV2FindPackageByIdResourceTest(
                           resource,
                           package,
                           packageIdentity,
                           testDirectory));
            }
Пример #18
0
        public async Task CopyPackagesToOriginalCaseAsync_DoesNothingIfPackageIsAlreadyInstalled()
        {
            // Arrange
            using (var workingDirectory = TestDirectory.Create())
            {
                var packagesDirectory = Path.Combine(workingDirectory, "packages");
                var sourceDirectory   = Path.Combine(workingDirectory, "source");

                var identity    = new PackageIdentity("PackageA", NuGetVersion.Parse("1.0.0-Beta"));
                var packagePath = SimpleTestPackageUtility.CreateFullPackage(
                    sourceDirectory,
                    identity.Id,
                    identity.Version.ToString());

                var logger = new TestLogger();
                var graph  = GetRestoreTargetGraph(identity, packagePath, logger);

                var request  = GetRestoreRequest(packagesDirectory, logger);
                var resolver = new VersionFolderPathResolver(packagesDirectory, isLowercase: false);

                var hashPath = resolver.GetHashPath(identity.Id, identity.Version);
                Directory.CreateDirectory(Path.GetDirectoryName(hashPath));

                // The hash file is what determines if the package is installed or not.
                File.WriteAllText(hashPath, string.Empty);

                var target = new OriginalCaseGlobalPackageFolder(request);

                // Act
                await target.CopyPackagesToOriginalCaseAsync(
                    new[] { graph },
                    CancellationToken.None);

                // Assert
                Assert.True(File.Exists(resolver.GetHashPath(identity.Id, identity.Version)));
                Assert.Equal(0, logger.Messages.Count(x => x.Contains(identity.ToString())));
            }
        }
            public TestContext(TestDirectory testDirectory)
            {
                TestDirectory = testDirectory;
                Identity      = new PackageIdentity("PackageA", NuGetVersion.Parse("1.0.0-Beta"));

                var packageDirectory = Path.Combine(testDirectory, "packages");
                var package          = SimpleTestPackageUtility.CreateFullPackage(
                    packageDirectory,
                    Identity.Id,
                    Identity.Version.ToString());

                ExpectedContent = File.ReadAllBytes(package.FullName);

                PackageSource      = new PackageSource("http://foo/index.json");
                NupkgUrl           = "http://foo/package.nupkg";
                RequestCount       = 0;
                HttpCacheDirectory = Path.Combine(testDirectory, "httpCache");
                StatusCode         = HttpStatusCode.OK;

                Logger            = new TestLogger();
                DestinationStream = new MemoryStream();

                Initialize();
            }
Пример #20
0
        public async Task RestoreCommand_VerifyRuntimeSpecificAssetsAreNotIncludedForCompile_RuntimeAndRef()
        {
            // Arrange
            var sources = new List<PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.5"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0""
                    }
                }
              },
              ""runtimes"": {
                ""win7-x64"": {}
              }
            }";

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

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

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

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

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

                var packageAContext = new SimpleTestPackageContext("packageA");
                packageAContext.AddFile("ref/netstandard1.5/a.dll");
                packageAContext.AddFile("runtimes/win7-x64/lib/netstandard1.5/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext);

                // Act
                var command = new RestoreCommand(request);
                var result = await command.ExecuteAsync();
                var lockFile = result.LockFile;
                await result.CommitAsync(logger, CancellationToken.None);

                var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), "win7-x64")
                    .Libraries
                    .Single(library => library.Name == "packageA");

                // Assert
                Assert.True(result.Success);
                Assert.Equal("ref/netstandard1.5/a.dll", targetLib.CompileTimeAssemblies.Single());
                Assert.Equal("runtimes/win7-x64/lib/netstandard1.5/a.dll", targetLib.RuntimeAssemblies.Single());
            }
        }
        public async Task PackageUpdateResource_GetErrorFromCreateKeyPushing()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source       = "https://www.myget.org/api/v2";
                var symbolSource = "https://nuget.smbsrc.net/";
                HttpRequestMessage sourceRequest = null;
                HttpRequestMessage symbolRequest = null;
                var apiKey = "serverapikey";

                var packageInfo       = SimpleTestPackageUtility.CreateFullPackage(workingDir, "test", "1.0.0");
                var symbolPackageInfo = SimpleTestPackageUtility.CreateSymbolPackage(workingDir, "test", "1.0.0");

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://www.myget.org/api/v2/",
                        request =>
                        {
                            sourceRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://nuget.smbsrc.net/api/v2/package/",
                        request =>
                        {
                            symbolRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://www.nuget.org/api/v2/package/create-verification-key/test/1.0.0",
                        request =>
                        {
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.InternalServerError)));
                        }
                    }
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                UserAgent.SetUserAgentString(new UserAgentStringBuilder("test client"));

                // Act
                var ex = await Assert.ThrowsAsync <HttpRequestException>(
                    async() => await resource.Push(
                        packagePath: packageInfo.FullName,
                        symbolSource: symbolSource,
                        timeoutInSecond: 5,
                        disableBuffering: false,
                        getApiKey: _ => apiKey,
                        getSymbolApiKey: _ => apiKey,
                        log: NullLogger.Instance));

                // Assert
                Assert.True(ex.Message.Contains("Response status code does not indicate success: 500 (Internal Server Error)"));
            }
        }
Пример #22
0
        public async Task PackageUpdateResource_NuGetOrgSourceOnlyPushing()
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var source       = "https://www.nuget.org/api/v2";
                var symbolSource = "https://other.smbsrc.net/";
                HttpRequestMessage sourceRequest = null;
                HttpRequestMessage symbolRequest = null;
                var apiKey = "serverapikey";

                var packageInfo       = SimpleTestPackageUtility.CreateFullPackage(workingDir, "test", "1.0.0");
                var symbolPackageInfo = SimpleTestPackageUtility.CreateSymbolPackage(workingDir, "test", "1.0.0");

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        "https://www.nuget.org/api/v2/",
                        request =>
                        {
                            sourceRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                    {
                        "https://other.smbsrc.net/api/v2/package/",
                        request =>
                        {
                            symbolRequest = request;
                            return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)));
                        }
                    },
                };

                var repo     = StaticHttpHandler.CreateSource(source, Repository.Provider.GetCoreV3(), responses);
                var resource = await repo.GetResourceAsync <PackageUpdateResource>();

                UserAgent.SetUserAgentString(new UserAgentStringBuilder("test client"));

                // Act
                await resource.Push(
                    packagePath : packageInfo.FullName,
                    symbolSource : symbolSource,
                    timeoutInSecond : 5,
                    disableBuffering : false,
                    getApiKey : _ => apiKey,
                    getSymbolApiKey : _ => apiKey,
                    noServiceEndpoint : false,
                    log : NullLogger.Instance);

                // Assert
                IEnumerable <string> apiValues;
                IEnumerable <string> symbolClientVersionValues;
                IEnumerable <string> sourceClientVersionValues;
                symbolRequest.Headers.TryGetValues(ApiKeyHeader, out apiValues);
                symbolRequest.Headers.TryGetValues(NuGetClientVersionHeader, out symbolClientVersionValues);
                sourceRequest.Headers.TryGetValues(NuGetClientVersionHeader, out sourceClientVersionValues);

                Assert.Equal("serverapikey", apiValues.First());
                Assert.NotNull(symbolClientVersionValues.First());
                Assert.NotNull(sourceClientVersionValues.First());
            }
        }
Пример #23
0
        public async Task RestoreRunner_BasicRestore_VerifyFailureWritesFiles()
        {
            // Arrange
            var sources = new List <PackageSource>();

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

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

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

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

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

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

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

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

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

                var yPath = SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageY);
                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageX);

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

                var providerCache = new RestoreCommandProvidersCache();

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

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

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

                    var summary = summaries.Single();

                    var targets = TargetsUtility.GetMSBuildPackageImports(targetsPath);

                    // Assert
                    Assert.False(summary.Success);
                    Assert.True(File.Exists(lockPath), lockPath);
                    Assert.True(File.Exists(targetsPath));
                    Assert.False(File.Exists(propsPath));
                    Assert.Equal(1, targets.Count);
                }
            }
        }
Пример #24
0
        public async Task RestoreCommand_WhenSwitchingBetweenLowercaseSettings_LockFileAlwaysRespectsLatestSetting(bool isLowercase)
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                sourceDir.Create();
                projectDir.Create();

                var resolverA = new VersionFolderPathResolver(packagesDir.FullName, !isLowercase);
                var resolverB = new VersionFolderPathResolver(packagesDir.FullName, isLowercase);

                var sources = new List<string>();
                sources.Add(sourceDir.FullName);

                var projectJson = @"
                {
                  ""frameworks"": {
                    ""netstandard1.0"": {
                      ""dependencies"": {
                        ""PackageA"": ""1.0.0-Beta""
                      }
                    }
                  }
                }";

                File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson);

                var specPath = Path.Combine(projectDir.FullName, "project.json");
                var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath);

                var logger = new TestLogger();
                var lockFilePath = Path.Combine(projectDir.FullName, "project.lock.json");
                var lockFileFormat = new LockFileFormat();

                var packageId = "PackageA";
                var packageVersion = "1.0.0-Beta";
                var packageAContext = new SimpleTestPackageContext(packageId, packageVersion);
                packageAContext.AddFile("lib/netstandard1.0/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext);

                // Act
                // Execute the first restore with the opposite lowercase setting.
                var requestA = new TestRestoreRequest(
                    spec,
                    sources.Select(x => Repository.Factory.GetCoreV3(x)),
                    packagesDir.FullName,
                    Enumerable.Empty<string>(),
                    logger)
                {
                    LockFilePath = lockFilePath,
                    IsLowercasePackagesDirectory = !isLowercase
                };
                var commandA = new RestoreCommand(requestA);
                var resultA = await commandA.ExecuteAsync();
                await resultA.CommitAsync(logger, CancellationToken.None);

                // Execute the second restore with the request lowercase setting.
                var requestB = new TestRestoreRequest(
                    spec,
                    sources.Select(x => Repository.Factory.GetCoreV3(x)),
                    packagesDir.FullName,
                    Enumerable.Empty<string>(),
                    logger)
                {
                    LockFilePath = lockFilePath,
                    IsLowercasePackagesDirectory = isLowercase,
                    ExistingLockFile = lockFileFormat.Read(lockFilePath)
                };
                var commandB = new RestoreCommand(requestB);
                var resultB = await commandB.ExecuteAsync();
                await resultB.CommitAsync(logger, CancellationToken.None);

                // Assert
                // Commands should have succeeded.
                Assert.True(resultA.Success);
                Assert.True(resultB.Success);

                // The lock file library path should match the requested case.
                var libraryA = resultA
                    .LockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);
                Assert.NotNull(libraryA);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolverA.GetPackageDirectory(packageId, libraryA.Version)),
                    libraryA.Path);
                Assert.True(File.Exists(resolverA.GetPackageFilePath(packageId, libraryA.Version)));

                var libraryB = resultB
                    .LockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);
                Assert.NotNull(libraryB);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)),
                    libraryB.Path);
                Assert.True(File.Exists(resolverB.GetPackageFilePath(packageId, libraryB.Version)));

                // The lock file on disk should match the second restore's library.
                var diskLockFile = lockFileFormat.Read(lockFilePath);
                var lockFileLibrary = diskLockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);
                Assert.NotNull(lockFileLibrary);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolverB.GetPackageDirectory(packageId, libraryB.Version)),
                    libraryB.Path);
                Assert.Equal(libraryB, lockFileLibrary);
            }
        }
            internal static RemoteV2FindPackageByIdResourceTest Create()
            {
                var serviceAddress  = ProtocolUtility.CreateServiceAddress();
                var packageIdentity = new PackageIdentity(
                    id: "xunit",
                    version: NuGetVersion.Parse("2.2.0-beta1-build3239"));
                var testDirectory = TestDirectory.Create();
                var packageSource = new PackageSource(serviceAddress);
                var package       = SimpleTestPackageUtility.CreateFullPackage(
                    testDirectory.Path,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString());
                var packageBytes = File.ReadAllBytes(package.FullName);

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

                var httpSource = new TestHttpSource(packageSource, responses);
                var resource   = new RemoteV2FindPackageByIdResource(
                    packageSource,
                    httpSource);

                return(new RemoteV2FindPackageByIdResourceTest(
                           resource,
                           packageSource,
                           package,
                           packageIdentity,
                           new SourceCacheContext(),
                           httpSource,
                           testDirectory));
            }
        public async Task DependencyTypeConstraint_PackagesDependOnProject()
        {
            // Arrange
            var sources = new List <PackageSource>();

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

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

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

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

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

                var packageAPath = SimpleTestPackageUtility.CreateFullPackage(
                    packageSource.FullName,
                    "packageA",
                    "1.0.0",
                    new Packaging.Core.PackageDependency[]
                {
                    new Packaging.Core.PackageDependency("packageB", VersionRange.Parse("1.0.0"))
                });

                await GlobalFolderUtility.AddPackageToGlobalFolderAsync(packageAPath, packagesDir);

                var logger = new TestLogger();

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

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

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

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

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

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

                // Assert
                Assert.True(result.Success);
                var packageBLib = lockFile.GetLibrary("packageB", NuGetVersion.Parse("1.0.0"));
                Assert.NotNull(packageBLib);
                Assert.Equal(LibraryType.Project, packageBLib.Type);
            }
        }
        public async Task DependencyTypeConstraint_TargetPackage()
        {
            // Arrange
            var sources = new List <PackageSource>();

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

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

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

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

                var project1ProjPath = Path.Combine(project1.FullName, "project1.xproj");
                File.WriteAllText(project1ProjPath, string.Empty);
                File.WriteAllText(Path.Combine(packageAProject.FullName, "packageA.xproj"), string.Empty);

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

                var packageAPath = SimpleTestPackageUtility.CreateFullPackage(
                    packageSource.FullName,
                    "packageA",
                    "1.0.0");

                await GlobalFolderUtility.AddPackageToGlobalFolderAsync(packageAPath, packagesDir);

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

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

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

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

                var packageALib = lockFile.GetLibrary("packageA", NuGetVersion.Parse("1.0.0"));

                var packageATarget = lockFile.GetTarget(
                    FrameworkConstants.CommonFrameworks.Net45,
                    runtimeIdentifier: null)
                                     .Libraries
                                     .Single(lib => lib.Name == "packageA");

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

                Assert.Equal(LibraryType.Package, packageALib.Type);
                Assert.Equal(LibraryType.Package, packageATarget.Type);
            }
        }
Пример #28
0
        public async Task RestoreCommand_ObservesLowercaseFlag(bool isLowercase)
        {
            // Arrange
            using (var workingDir = TestDirectory.Create())
            {
                var packagesDir = new DirectoryInfo(Path.Combine(workingDir, "globalPackages"));
                var sourceDir = new DirectoryInfo(Path.Combine(workingDir, "packageSource"));
                var projectDir = new DirectoryInfo(Path.Combine(workingDir, "projects", "project1"));
                packagesDir.Create();
                sourceDir.Create();
                projectDir.Create();

                var resolver = new VersionFolderPathResolver(packagesDir.FullName, isLowercase);

                var sources = new List<string>();
                sources.Add(sourceDir.FullName);

                var projectJson = @"
                {
                  ""frameworks"": {
                    ""netstandard1.0"": {
                      ""dependencies"": {
                        ""PackageA"": ""1.0.0-Beta""
                      }
                    }
                  }
                }";

                File.WriteAllText(Path.Combine(projectDir.FullName, "project.json"), projectJson);

                var specPath = Path.Combine(projectDir.FullName, "project.json");
                var spec = JsonPackageSpecReader.GetPackageSpec(projectJson, "project1", specPath);

                var logger = new TestLogger();
                var request = new TestRestoreRequest(
                    spec,
                    sources.Select(x => Repository.Factory.GetCoreV3(x)),
                    packagesDir.FullName,
                    Enumerable.Empty<string>(),
                    logger)
                {
                    IsLowercasePackagesDirectory = isLowercase
                };
                request.LockFilePath = Path.Combine(projectDir.FullName, "project.lock.json");

                var packageId = "PackageA";
                var packageVersion = "1.0.0-Beta";
                var packageAContext = new SimpleTestPackageContext(packageId, packageVersion);
                packageAContext.AddFile("lib/netstandard1.0/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(sourceDir.FullName, packageAContext);

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

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

                var library = lockFile
                    .Libraries
                    .FirstOrDefault(l => l.Name == packageId && l.Version.ToNormalizedString() == packageVersion);

                Assert.NotNull(library);
                Assert.Equal(
                    PathUtility.GetPathWithForwardSlashes(resolver.GetPackageDirectory(packageId, library.Version)),
                    library.Path);
                Assert.True(File.Exists(resolver.GetPackageFilePath(packageId, library.Version)));
            }
        }
Пример #29
0
            internal static RemoteV3FindPackageByIdResourceTest Create()
            {
                var serviceAddress  = TestUtility.CreateServiceAddress();
                var packageIdentity = new PackageIdentity(
                    id: "xunit",
                    version: NuGetVersion.Parse("2.2.0-beta1-build3239"));
                var testDirectory = TestDirectory.Create();
                var packageSource = new PackageSource(serviceAddress);

                var dependencyInfoResourceProvider = new Mock <INuGetResourceProvider>();
                var dependencyInfoResource         = new Mock <DependencyInfoResource>();
                var remoteSourceDependencyInfo     = new RemoteSourceDependencyInfo(
                    packageIdentity,
                    listed: true,
                    dependencyGroups: Enumerable.Empty <PackageDependencyGroup>(),
                    contentUri: serviceAddress + "api/v2/package/xunit/2.2.0-beta1-build3239");

                dependencyInfoResource.Setup(x => x.ResolvePackages(
                                                 It.Is <string>(id => id == packageIdentity.Id),
                                                 It.IsNotNull <ILogger>(),
                                                 It.IsAny <CancellationToken>()))
                .ReturnsAsync(new[] { remoteSourceDependencyInfo });

                dependencyInfoResourceProvider.SetupGet(x => x.Before)
                .Returns(Enumerable.Empty <string>());
                dependencyInfoResourceProvider.SetupGet(x => x.After)
                .Returns(Enumerable.Empty <string>());
                dependencyInfoResourceProvider.SetupGet(x => x.ResourceType)
                .Returns(typeof(DependencyInfoResource));
                dependencyInfoResourceProvider.SetupGet(x => x.Name)
                .Returns("DependencyInfoResourceProvider");
                dependencyInfoResourceProvider.Setup(
                    x => x.TryCreate(It.IsNotIn <SourceRepository>(), It.IsAny <CancellationToken>()))
                .ReturnsAsync(new Tuple <bool, INuGetResource>(true, dependencyInfoResource.Object));

                var sourceRepository = new SourceRepository(
                    packageSource,
                    new[] { dependencyInfoResourceProvider.Object });
                var package = SimpleTestPackageUtility.CreateFullPackage(
                    testDirectory.Path,
                    packageIdentity.Id,
                    packageIdentity.Version.ToNormalizedString());
                var packageBytes = File.ReadAllBytes(package.FullName);

                var responses = new Dictionary <string, Func <HttpRequestMessage, Task <HttpResponseMessage> > >
                {
                    {
                        serviceAddress,
                        request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(string.Empty)
                        })
                    },
                    {
                        serviceAddress + $"FindPackagesById()?id='{packageIdentity.Id}'",
                        request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(
                                TestUtility.GetResource(
                                    "NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml",
                                    typeof(RemoteV3FindPackageByIdResourceTest)))
                        })
                    },
                    {
                        serviceAddress + $"FindPackagesById()?id='{packageIdentity.Id.ToUpper()}'",
                        request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new TestContent(
                                TestUtility.GetResource(
                                    "NuGet.Protocol.Tests.compiler.resources.XunitFindPackagesById.xml",
                                    typeof(RemoteV3FindPackageByIdResourceTest)))
                        })
                    },
                    {
                        serviceAddress + "api/v2/package/xunit/2.2.0-beta1-build3239",
                        request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                        {
                            Content = new ByteArrayContent(packageBytes)
                        })
                    },
                    {
                        serviceAddress + $"FindPackagesById()?id='a'",
                        request => Task.FromResult(new HttpResponseMessage(HttpStatusCode.NoContent))
                    }
                };

                var httpSource = new TestHttpSource(packageSource, responses);
                var resource   = new RemoteV3FindPackageByIdResource(
                    sourceRepository,
                    httpSource);

                return(new RemoteV3FindPackageByIdResourceTest(
                           resource,
                           sourceRepository,
                           package,
                           packageIdentity,
                           new SourceCacheContext(),
                           httpSource,
                           testDirectory));
            }
Пример #30
0
        public async Task RestoreSemVer_RestorePackageWithMetadata_DifferentMetadataDoesNotMatter()
        {
            // Arrange
            var sources = new List <PackageSource>();

            var project1Json = @"
            {
              ""version"": ""1.0.0"",
              ""description"": """",
              ""authors"": [ ""author"" ],
              ""tags"": [ """" ],
              ""projectUrl"": """",
              ""licenseUrl"": """",
              ""frameworks"": {
                ""netstandard1.5"": {
                    ""dependencies"": {
                        ""packageA"": ""1.0.0+1""
                    }
                }
              }
            }";

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

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

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

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

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

                var packageAContext = new SimpleTestPackageContext("packageA")
                {
                    Version = "1.0.0+B"
                };

                packageAContext.AddFile("lib/netstandard1.5/a.dll");

                SimpleTestPackageUtility.CreateFullPackage(packageSource.FullName, packageAContext);

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

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

                var targetLib = lockFile.GetTarget(NuGetFramework.Parse("netstandard1.5"), null)
                                .Libraries
                                .Single(library => library.Name == "packageA");

                var compile = targetLib.CompileTimeAssemblies.Single();

                // Assert
                Assert.True(result.Success);
                Assert.Equal("lib/netstandard1.5/a.dll", compile.Path);
                Assert.Equal("1.0.0", targetLib.Version.ToNormalizedString());
            }
        }