public void ListCommand_UnavailableV3()
        {
            var nugetexe = Util.GetNuGetExePath();

            using (var pathContext = new SimpleTestPathContext())
            {
                // Arrange
                // Server setup
                using (var serverV3 = new MockServer())
                {
                    serverV3.Get.Add("/", r =>
                    {
                        var path = serverV3.GetRequestUrlAbsolutePath(r);

                        if (path == "/index.json")
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.StatusCode = 404;
                                response.ContentType = "text/javascript";
                                MockServer.SetResponseContent(response, response.StatusCode.ToString());
                            }));
                        }

                        throw new Exception("This test needs to be updated to support: " + path);
                    });

                    serverV3.Start();

                    // Act
                    var args   = "list test -Source " + serverV3.Uri + "index.json";
                    var result = CommandRunner.Run(
                        nugetexe,
                        pathContext.SolutionRoot,
                        args,
                        waitForExit: true);

                    serverV3.Stop();

                    // Assert
                    Assert.True(result.Item1 != 0, result.Item2 + " " + result.Item3);

                    Assert.True(
                        result.Item3.Contains("404 (Not Found)"),
                        "Expected error message not found in " + result.Item3
                        );
                }
            }
        }
        public MockResponse BuildRegistrationIndexResponse(MockServer mockServer, KeyValuePair <PackageIdentity, bool>[] packageIdentityToListed)
        {
            var id       = packageIdentityToListed[0].Key.Id.ToLowerInvariant();
            var versions = packageIdentityToListed.Select(
                e => new KeyValuePair <string, bool>(
                    e.Key.Version.ToNormalizedString().ToLowerInvariant(),
                    e.Value));
            var registrationIndex = Util.CreatePackageRegistrationBlob(mockServer, id, versions);

            return(new MockResponse
            {
                ContentType = "text/javascript",
                Content = Encoding.UTF8.GetBytes(registrationIndex.ToString())
            });
        }
        public void DeleteCommand_WithApiKeyAsNamedArgument()
        {
            // Arrange
            var testApiKey = Guid.NewGuid().ToString();

            using (var server = new MockServer())
            {
                server.Delete.Add("/nuget/testPackage1/1.1", r =>
                {
                    var h = r.Headers[ApiKeyHeader];
                    if (!string.Equals(h, testApiKey, StringComparison.OrdinalIgnoreCase))
                    {
                        return(HttpStatusCode.Unauthorized);
                    }

                    return(HttpStatusCode.OK);
                });

                server.Start();

                // Act
                var args = new[]
                {
                    "delete",
                    "testPackage1",
                    "1.1.0",
                    "should-be-ignored",  // The named argument is preferred over the positional argument.
                    "-ApiKey",
                    testApiKey,
                    "-Source",
                    server.Uri + "nuget",
                    "-NonInteractive"
                };

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

                server.Stop();

                // Assert
                Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                Assert.Contains("testPackage1 1.1.0 was deleted successfully.", result.Item2);
            }
        }
示例#4
0
        /// <summary>
        /// Create a registration blob for a package
        /// </summary>
        public static JObject CreatePackageRegistrationBlob(MockServer server, string id, IEnumerable <KeyValuePair <string, bool> > versionToListedMap)
        {
            var indexUrl = string.Format(CultureInfo.InvariantCulture,
                                         "{0}reg/{1}/index.json", server.Uri, id);
            var lowerBound = "0.0.0";
            var upperBound = "9.0.0";
            var regBlob    = new JObject();

            regBlob.Add(new JProperty("@id", indexUrl));
            var typeArray = new JArray();

            regBlob.Add(new JProperty("@type", typeArray));
            typeArray.Add("catalog: CatalogRoot");
            typeArray.Add("PackageRegistration");
            typeArray.Add("catalog: Permalink");

            regBlob.Add(new JProperty("commitId", Guid.NewGuid()));
            regBlob.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z"));
            regBlob.Add(new JProperty("count", "1"));

            var pages = new JArray();

            regBlob.Add(new JProperty("items", pages));

            var page = new JObject();

            pages.Add(page);

            page.Add(new JProperty("@id", indexUrl + $"#page/{lowerBound}/{upperBound}"));
            page.Add(new JProperty("@type", indexUrl + "catalog:CatalogPage"));
            page.Add(new JProperty("commitId", Guid.NewGuid()));
            page.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z"));
            page.Add(new JProperty("count", versionToListedMap.Count()));
            page.Add(new JProperty("parent", indexUrl));
            page.Add(new JProperty("lower", lowerBound));
            page.Add(new JProperty("upper", upperBound));

            var items = new JArray();

            page.Add(new JProperty("items", items));
            foreach (var versionToListed in versionToListedMap)
            {
                var item = GetPackageRegistrationItem(server, id, version: versionToListed.Key, listed: versionToListed.Value, indexUrl);
                items.Add(item);
            }
            return(regBlob);
        }
示例#5
0
        public static void AddLegacyGalleryResource(JObject index, MockServer serverV2, string relativeUri = null)
        {
            var resourceUri = new Uri(serverV2.Uri);

            if (relativeUri != null)
            {
                resourceUri = new Uri(resourceUri, relativeUri);
            }

            var resource = new JObject
            {
                { "@id", resourceUri },
                { "@type", "LegacyGallery/2.0.0" }
            };

            var array = index["resources"] as JArray;

            array.Add(resource);
        }
示例#6
0
        private static JObject GetPackageRegistrationItem(MockServer server, string id, string version, bool listed, string indexUrl)
        {
            var item = new JObject();

            item.Add(new JProperty("@id",
                                   string.Format("{0}reg/{1}/{2}.json", server.Uri, id, version)));

            item.Add(new JProperty("@type", "Package"));
            item.Add(new JProperty("commitId", Guid.NewGuid()));
            item.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z"));

            var catalogEntry = new JObject();

            item.Add(new JProperty("catalogEntry", catalogEntry));
            item.Add(new JProperty("packageContent", $"{server.Uri}packages/{id}.{version}.nupkg"));
            item.Add(new JProperty("registration", indexUrl));

            catalogEntry.Add(new JProperty("@id",
                                           string.Format("{0}catalog/{1}/{2}.json", server.Uri, id, version)));

            catalogEntry.Add(new JProperty("@type", "PackageDetails"));
            catalogEntry.Add(new JProperty("authors", "test"));
            catalogEntry.Add(new JProperty("description", "test"));
            catalogEntry.Add(new JProperty("iconUrl", ""));
            catalogEntry.Add(new JProperty("id", id));
            catalogEntry.Add(new JProperty("language", "en-us"));
            catalogEntry.Add(new JProperty("licenseUrl", ""));
            catalogEntry.Add(new JProperty("listed", listed));
            catalogEntry.Add(new JProperty("minClientVersion", ""));
            catalogEntry.Add(new JProperty("projectUrl", ""));
            catalogEntry.Add(new JProperty("published", "2015-06-22T22:30:00.1487642Z"));
            catalogEntry.Add(new JProperty("requireLicenseAcceptance", false));
            catalogEntry.Add(new JProperty("summary", ""));
            catalogEntry.Add(new JProperty("title", ""));
            catalogEntry.Add(new JProperty("version", version));
            catalogEntry.Add(new JProperty("tags", new JArray()));

            return(item);
        }
        public void DeleteCommand_ShowsServerWarnings(string firstServerWarning, string secondServerWarning)
        {
            var serverWarnings = new[] { firstServerWarning, secondServerWarning };
            var nugetexe       = Util.GetNuGetExePath();

            // Arrange
            using (var server = new MockServer())
            {
                server.Start();

                server.Delete.Add("/nuget/testPackage1/1.1", request => HttpStatusCode.OK);

                server.AddServerWarnings(serverWarnings);

                // Act
                string[] args = new string[] {
                    "delete", "testPackage1", "1.1.0",
                    "-Source", server.Uri + "nuget", "-NonInteractive"
                };

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

                // Assert
                foreach (var serverWarning in serverWarnings)
                {
                    if (!string.IsNullOrEmpty(serverWarning))
                    {
                        Assert.Contains(serverWarning, r.Item2);
                    }
                }
            }
        }
示例#8
0
 public static void AddPublishSymbolsResource(JObject index, MockServer publishServer)
 {
     FeedUtilities.AddPublishSymbolsResource(index, publishServer.Uri);
 }
        public void ListCommand_WithAuthenticatedSource_AppliesCredentialsFromSettings()
        {
            var  expectedAuthHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:password"));
            var  listEndpoint       = Guid.NewGuid().ToString() + "/api/v2";
            bool serverReceiveProperAuthorizationHeader = false;

            using (var pathContext = new SimpleTestPathContext())
            {
                // Arrange
                var repo             = Path.Combine(pathContext.WorkingDirectory, "repo");
                var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", repo);
                var package1         = new ZipPackage(packageFileName1);

                // Server setup
                using (var serverV3 = new MockServer())
                {
                    var indexJson = Util.CreateIndexJson();
                    Util.AddFlatContainerResource(indexJson, serverV3);
                    Util.AddLegacyGalleryResource(indexJson, serverV3, listEndpoint);

                    serverV3.Get.Add("/", r =>
                    {
                        var h = r.Headers["Authorization"];
                        if (h == null)
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.StatusCode = 401;
                                response.AddHeader("WWW-Authenticate", @"Basic realm=""Test""");
                                MockServer.SetResponseContent(response, "401 Unauthenticated");
                            }));
                        }

                        if (expectedAuthHeader != h)
                        {
                            return(HttpStatusCode.Forbidden);
                        }

                        var path = serverV3.GetRequestUrlAbsolutePath(r);

                        if (path == "/index.json")
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.StatusCode = 200;
                                response.ContentType = "text/javascript";
                                MockServer.SetResponseContent(response, indexJson.ToString());
                            }));
                        }

                        if (path == $"/{listEndpoint}/$metadata")
                        {
                            return(Util.GetMockServerResource());
                        }

                        if (path == $"/{listEndpoint}/Search()")
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                                var feed = serverV3.ToODataFeed(new[] { package1 }, "Search");
                                MockServer.SetResponseContent(response, feed);
                            }));
                        }

                        serverReceiveProperAuthorizationHeader = true;
                        return("OK");
                    });

                    // Add source into NuGet.Config file
                    var settings = pathContext.Settings;
                    SimpleTestSettingsContext.RemoveSource(settings.XML, "source");

                    var source = serverV3.Uri + "index.json";
                    var packageSourcesSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "packageSources");
                    SimpleTestSettingsContext.AddEntry(packageSourcesSection, "vsts", source, additionalAtrributeName: "protocolVersion", additionalAttributeValue: "3");

                    //var packageSourceCredentialsSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "packageSourceCredentials");
                    SimpleTestSettingsContext.AddPackageSourceCredentialsSection(settings.XML, "vsts", "user", "password", clearTextPassword: true);
                    settings.Save();

                    serverV3.Start();

                    // Act
                    var result = CommandRunner.Run(
                        Util.GetNuGetExePath(),
                        pathContext.SolutionRoot,
                        $"list test -source {serverV3.Uri}index.json -configfile {pathContext.NuGetConfig} -verbosity detailed -noninteractive",
                        waitForExit: true);

                    serverV3.Stop();

                    // Assert
                    Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                    Assert.True(serverReceiveProperAuthorizationHeader);
                    Assert.Contains($"GET {serverV3.Uri}{listEndpoint}/Search()", result.Item2);
                    // verify that only package id & version is displayed
                    Assert.Matches(@"(?m)testPackage1\s+1\.1\.0", result.Item2);
                }
            }
        }
        [InlineData("{0}push")]       // delete package endpoint
        public void DeleteCommand_WithApiKeyFromConfig(string configKeyFormatString)
        {
            // Arrange
            Util.ClearWebCache();
            var testApiKey = Guid.NewGuid().ToString();

            using (var testFolder = TestDirectory.Create())
            {
                using (var server = new MockServer())
                {
                    // Server setup
                    var indexJson = Util.CreateIndexJson();

                    Util.AddFlatContainerResource(indexJson, server);
                    Util.AddPublishResource(indexJson, server);

                    server.Get.Add("/index.json", r =>
                    {
                        return(new Action <HttpListenerResponse>(response =>
                        {
                            response.StatusCode = 200;
                            response.ContentType = "text/javascript";
                            MockServer.SetResponseContent(response, indexJson.ToString());
                        }));
                    });

                    server.Delete.Add("/push/testPackage1/1.1", r =>
                    {
                        var h = r.Headers[ApiKeyHeader];
                        if (!string.Equals(h, testApiKey, StringComparison.OrdinalIgnoreCase))
                        {
                            return(HttpStatusCode.Unauthorized);
                        }

                        return(HttpStatusCode.OK);
                    });

                    server.Start();

                    var configKey = string.Format(configKeyFormatString, server.Uri);

                    var config = $@"<?xml version='1.0' encoding='utf-8'?>
<configuration>
    <packageSources>
        <add key='MockServer' value='{server.Uri}index.json' protocolVersion='3' />
    </packageSources>
    <apikeys>
        <add key='{configKey}' value='{Configuration.EncryptionUtility.EncryptString(testApiKey)}' />
    </apikeys>
</configuration>";

                    var configFileName = Path.Combine(testFolder, "nuget.config");
                    File.WriteAllText(configFileName, config);

                    // Act
                    var args = new[]
                    {
                        "delete",
                        "testPackage1",
                        "1.1.0",
                        "-Source",
                        "MockServer",
                        "-ConfigFile",
                        configFileName,
                        "-NonInteractive"
                    };

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

                    server.Stop();

                    // Assert
                    Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                    Assert.Contains("testPackage1 1.1.0 was deleted successfully.", result.Item2);
                }
            }
        }
示例#11
0
        public void ListCommand_WithAuthenticatedSource_AppliesCredentialsFromSettings()
        {
            Util.ClearWebCache();
            var  expectedAuthHeader = "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes("user:password"));
            var  listEndpoint       = Guid.NewGuid().ToString() + "/api/v2";
            bool serverReceiveProperAuthorizationHeader = false;

            using (var randomTestFolder = TestDirectory.Create())
            {
                // Arrange
                var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", randomTestFolder);
                var package1         = new ZipPackage(packageFileName1);

                // Server setup
                using (var serverV3 = new MockServer())
                {
                    var indexJson = Util.CreateIndexJson();
                    Util.AddFlatContainerResource(indexJson, serverV3);
                    Util.AddLegacyGalleryResource(indexJson, serverV3, listEndpoint);

                    serverV3.Get.Add("/", r =>
                    {
                        var h = r.Headers["Authorization"];
                        if (h == null)
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.StatusCode = 401;
                                response.AddHeader("WWW-Authenticate", @"Basic realm=""Test""");
                                MockServer.SetResponseContent(response, "401 Unauthenticated");
                            }));
                        }

                        if (expectedAuthHeader != h)
                        {
                            return(HttpStatusCode.Forbidden);
                        }

                        var path = serverV3.GetRequestUrlAbsolutePath(r);

                        if (path == "/index.json")
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.StatusCode = 200;
                                response.ContentType = "text/javascript";
                                MockServer.SetResponseContent(response, indexJson.ToString());
                            }));
                        }

                        if (path == $"/{listEndpoint}/$metadata")
                        {
                            return(Util.GetMockServerResource());
                        }

                        if (path == $"/{listEndpoint}/Search()")
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                                var feed = serverV3.ToODataFeed(new[] { package1 }, "Search");
                                MockServer.SetResponseContent(response, feed);
                            }));
                        }

                        serverReceiveProperAuthorizationHeader = true;
                        return("OK");
                    });

                    var config         = $@"<?xml version='1.0' encoding='utf-8'?>
                                <configuration>
                                  <packageSources>
                                    <add key='vsts' value='{serverV3.Uri}index.json' protocolVersion='3' />
                                  </packageSources>
                                  <packageSourceCredentials>
                                    <vsts>
                                      <add key='Username' value='user' />
                                      <add key='ClearTextPassword' value='password' />
                                    </vsts>
                                  </packageSourceCredentials>
                                 </configuration>";
                    var configFileName = Path.Combine(randomTestFolder, "nuget.config");
                    File.WriteAllText(configFileName, config);

                    serverV3.Start();

                    // Act
                    var result = CommandRunner.Run(
                        Util.GetNuGetExePath(),
                        Directory.GetCurrentDirectory(),
                        $"list test -source {serverV3.Uri}index.json -configfile {configFileName} -verbosity detailed -noninteractive",
                        waitForExit: true);
                    serverV3.Stop();
                    // Assert
                    Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                    Assert.True(serverReceiveProperAuthorizationHeader);
                    Assert.Contains($"GET {serverV3.Uri}{listEndpoint}/Search()", result.Item2);
                    // verify that only package id & version is displayed
                    Assert.Matches(@"(?m)testPackage1\s+1\.1\.0", result.Item2);
                }
            }
        }
示例#12
0
        [InlineData("{0}push")]       // delete package endpoint
        public void DeleteCommand_WithApiKeyFromConfig(string configKeyFormatString)
        {
            // Arrange
            var testApiKey = Guid.NewGuid().ToString();

            using (var pathContext = new SimpleTestPathContext())
                using (var server = new MockServer())
                {
                    // Server setup
                    var indexJson = Util.CreateIndexJson();

                    Util.AddFlatContainerResource(indexJson, server);
                    Util.AddPublishResource(indexJson, server);

                    server.Get.Add("/index.json", r =>
                    {
                        return(new Action <HttpListenerResponse>(response =>
                        {
                            response.StatusCode = 200;
                            response.ContentType = "text/javascript";
                            MockServer.SetResponseContent(response, indexJson.ToString());
                        }));
                    });

                    server.Delete.Add("/push/testPackage1/1.1", r =>
                    {
                        var h = r.Headers[ApiKeyHeader];
                        if (!string.Equals(h, testApiKey, StringComparison.OrdinalIgnoreCase))
                        {
                            return(HttpStatusCode.Unauthorized);
                        }
                        return(HttpStatusCode.OK);
                    });

                    server.Start();

                    // Add the source and apikeys into NuGet.Config file
                    var settings = pathContext.Settings;
                    SimpleTestSettingsContext.RemoveSource(settings.XML, "source");

                    var source = server.Uri + "index.json";
                    var packageSourcesSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "packageSources");
                    SimpleTestSettingsContext.AddEntry(packageSourcesSection, $"MockServer", source);

                    var configKey      = string.Format(configKeyFormatString, server.Uri);
                    var configValue    = Configuration.EncryptionUtility.EncryptString(testApiKey);
                    var apikeysSection = SimpleTestSettingsContext.GetOrAddSection(settings.XML, "apikeys");
                    SimpleTestSettingsContext.AddEntry(apikeysSection, configKey, configValue);
                    settings.Save();

                    // Act
                    var args = new[]
                    {
                        "delete",
                        "testPackage1",
                        "1.1.0",
                        "-Source",
                        "MockServer",
                        "-ConfigFile",
                        pathContext.NuGetConfig,
                        "-NonInteractive"
                    };

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

                    server.Stop();

                    // Assert
                    Assert.True(0 == result.Item1, $"{result.Item2} {result.Item3}");
                    Assert.Contains("testPackage1 1.1.0 was deleted successfully.", result.Item2);
                }
        }
示例#13
0
        /// <summary>
        /// Create a registration blob for a single package
        /// </summary>
        public static JObject CreateSinglePackageRegistrationBlob(MockServer server, string id, string version)
        {
            var indexUrl = string.Format(CultureInfo.InvariantCulture,
                                         "{0}reg/{1}/index.json", server.Uri, id);

            JObject regBlob = new JObject();

            regBlob.Add(new JProperty("@id", indexUrl));
            var typeArray = new JArray();

            regBlob.Add(new JProperty("@type", typeArray));
            typeArray.Add("catalog: CatalogRoot");
            typeArray.Add("PackageRegistration");
            typeArray.Add("catalog: Permalink");

            regBlob.Add(new JProperty("commitId", Guid.NewGuid()));
            regBlob.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z"));
            regBlob.Add(new JProperty("count", "1"));

            var pages = new JArray();

            regBlob.Add(new JProperty("items", pages));

            var page = new JObject();

            pages.Add(page);

            page.Add(new JProperty("@id", indexUrl + "#page/0.0.0/9.0.0"));
            page.Add(new JProperty("@type", indexUrl + "catalog:CatalogPage"));
            page.Add(new JProperty("commitId", Guid.NewGuid()));
            page.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z"));
            page.Add(new JProperty("count", "1"));
            page.Add(new JProperty("parent", indexUrl));
            page.Add(new JProperty("lower", "0.0.0"));
            page.Add(new JProperty("upper", "9.0.0"));

            var items = new JArray();

            page.Add(new JProperty("items", items));

            var item = new JObject();

            items.Add(item);

            item.Add(new JProperty("@id",
                                   string.Format("{0}reg/{1}/{2}.json", server.Uri, id, version)));

            item.Add(new JProperty("@type", "Package"));
            item.Add(new JProperty("commitId", Guid.NewGuid()));
            item.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z"));

            var catalogEntry = new JObject();

            item.Add(new JProperty("catalogEntry", catalogEntry));
            item.Add(new JProperty("packageContent", $"{server.Uri}packages/{id}.{version}.nupkg"));
            item.Add(new JProperty("registration", indexUrl));

            catalogEntry.Add(new JProperty("@id",
                                           string.Format("{0}catalog/{1}/{2}.json", server.Uri, id, version)));

            catalogEntry.Add(new JProperty("@type", "PackageDetails"));
            catalogEntry.Add(new JProperty("authors", "test"));
            catalogEntry.Add(new JProperty("description", "test"));
            catalogEntry.Add(new JProperty("iconUrl", ""));
            catalogEntry.Add(new JProperty("id", id));
            catalogEntry.Add(new JProperty("language", "en-us"));
            catalogEntry.Add(new JProperty("licenseUrl", ""));
            catalogEntry.Add(new JProperty("listed", true));
            catalogEntry.Add(new JProperty("minClientVersion", ""));
            catalogEntry.Add(new JProperty("projectUrl", ""));
            catalogEntry.Add(new JProperty("published", "2015-06-22T22:30:00.1487642Z"));
            catalogEntry.Add(new JProperty("requireLicenseAcceptance", false));
            catalogEntry.Add(new JProperty("summary", ""));
            catalogEntry.Add(new JProperty("title", ""));
            catalogEntry.Add(new JProperty("version", version));
            catalogEntry.Add(new JProperty("tags", new JArray()));

            return(regBlob);
        }
示例#14
0
        public void ListCommand_SimpleV3()
        {
            Util.ClearWebCache();

            var nugetexe = Util.GetNuGetExePath();

            using (var packageDirectory = TestDirectory.Create())
            {
                // Arrange
                var packageFileName1 = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                var packageFileName2 = Util.CreateTestPackage("testPackage2", "2.1", packageDirectory);
                var package1         = new ZipPackage(packageFileName1);
                var package2         = new ZipPackage(packageFileName2);

                // Server setup
                var indexJson = Util.CreateIndexJson();
                using (var serverV3 = new MockServer())
                {
                    serverV3.Get.Add("/", r =>
                    {
                        var path = serverV3.GetRequestUrlAbsolutePath(r);

                        if (path == "/index.json")
                        {
                            return(new Action <HttpListenerResponse>(response =>
                            {
                                response.StatusCode = 200;
                                response.ContentType = "text/javascript";
                                MockServer.SetResponseContent(response, indexJson.ToString());
                            }));
                        }

                        throw new Exception("This test needs to be updated to support: " + path);
                    });

                    using (var serverV2 = new MockServer())
                    {
                        Util.AddFlatContainerResource(indexJson, serverV3);
                        Util.AddLegacyGalleryResource(indexJson, serverV2);
                        string searchRequest = string.Empty;

                        serverV2.Get.Add("/", r =>
                        {
                            var path = serverV2.GetRequestUrlAbsolutePath(r);

                            if (path == "/")
                            {
                                return("OK");
                            }

                            if (path == "/$metadata")
                            {
                                return(Util.GetMockServerResource());
                            }

                            if (path == "/Search()")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    searchRequest = r.Url.ToString();
                                    response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                                    string feed = serverV2.ToODataFeed(new[] { package1, package2 }, "Search");
                                    MockServer.SetResponseContent(response, feed);
                                }));
                            }

                            throw new Exception("This test needs to be updated to support: " + path);
                        });

                        serverV3.Start();
                        serverV2.Start();

                        // Act
                        var args   = "list test -Source " + serverV3.Uri + "index.json";
                        var result = CommandRunner.Run(
                            nugetexe,
                            Directory.GetCurrentDirectory(),
                            args,
                            waitForExit: true);

                        serverV2.Stop();
                        serverV3.Stop();

                        // Assert
                        Assert.True(result.Item1 == 0, result.Item2 + " " + result.Item3);

                        // verify that only package id & version is displayed
                        var expectedOutput = "testPackage1 1.1.0" + Environment.NewLine +
                                             "testPackage2 2.1.0" + Environment.NewLine;
                        Assert.Equal(expectedOutput, result.Item2);

                        Assert.Contains("$filter=IsLatestVersion", searchRequest);
                        Assert.Contains("searchTerm='test", searchRequest);
                        Assert.Contains("includePrerelease=false", searchRequest);
                    }
                }
            }
        }
示例#15
0
        private Action <HttpListenerResponse> ServerHandlerV3(
            HttpListenerRequest request,
            MockServer server,
            JObject indexJson,
            string repositoryPath)
        {
            try
            {
                var path  = server.GetRequestUrlAbsolutePath(request);
                var parts = request.Url.AbsolutePath.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                if (path == "/index.json")
                {
                    return(new Action <HttpListenerResponse>(response =>
                    {
                        response.StatusCode = 200;
                        response.ContentType = "text/javascript";
                        MockServer.SetResponseContent(response, indexJson.ToString());
                    }));
                }
                else if (path.StartsWith("/flat/") && path.EndsWith("/index.json"))
                {
                    return(new Action <HttpListenerResponse>(response =>
                    {
                        response.ContentType = "text/javascript";

                        var versionsJson = JObject.Parse(@"{ ""versions"": [] }");
                        var array = versionsJson["versions"] as JArray;

                        var id = parts[parts.Length - 2];

                        foreach (var pkg in LocalFolderUtility.GetPackagesV2(repositoryPath, id, new TestLogger()))
                        {
                            array.Add(pkg.Identity.Version.ToNormalizedString());
                        }

                        MockServer.SetResponseContent(response, versionsJson.ToString());
                    }));
                }
                else if (path.StartsWith("/flat/") && path.EndsWith(".nupkg"))
                {
                    var file = new FileInfo(Path.Combine(repositoryPath, parts.Last()));

                    if (file.Exists)
                    {
                        return(new Action <HttpListenerResponse>(response =>
                        {
                            response.ContentType = "application/zip";
                            using (var stream = file.OpenRead())
                            {
                                var content = stream.ReadAllBytes();
                                MockServer.SetResponseContent(response, content);
                            }
                        }));
                    }
                    else
                    {
                        return(new Action <HttpListenerResponse>(response =>
                        {
                            response.StatusCode = 404;
                        }));
                    }
                }
                else if (path == "/nuget")
                {
                    return(new Action <HttpListenerResponse>(response =>
                    {
                        response.StatusCode = 200;
                    }));
                }

                throw new Exception("This test needs to be updated to support: " + path);
            }
            catch (Exception)
            {
                // Debug here
                throw;
            }
        }
示例#16
0
        public void FeedPackagePruning_GivenThatAV3FeedPrunesAPackageDuringRestoreVerifyRestoreRecovers()
        {
            // Arrange
            using (var server = new MockServer())
                using (var pathContext = new SimpleTestPathContext())
                {
                    // Set up solution, project, and packages
                    var testLogger     = new TestLogger();
                    var solution       = new SimpleTestSolutionContext(pathContext.SolutionRoot);
                    var serverRepoPath = Path.Combine(pathContext.WorkingDirectory, "serverPackages");

                    var packageX100 = new SimpleTestPackageContext("x", "1.0.0");
                    var packageX200 = new SimpleTestPackageContext("x", "2.0.0");

                    SimpleTestPackageUtility.CreatePackages(
                        serverRepoPath,
                        packageX100,
                        packageX200);

                    var projectA = SimpleTestProjectContext.CreateNETCore(
                        "a",
                        pathContext.SolutionRoot,
                        NuGetFramework.Parse("net45"));
                    projectA.AddPackageToAllFrameworks(packageX200);
                    solution.Projects.Add(projectA);

                    var projectB = SimpleTestProjectContext.CreateNETCore(
                        "b",
                        pathContext.SolutionRoot,
                        NuGetFramework.Parse("net45"));
                    projectB.AddPackageToAllFrameworks(packageX100);
                    solution.Projects.Add(projectB);

                    solution.Create(pathContext.SolutionRoot);

                    // Server setup
                    var indexJson = Util.CreateIndexJson();
                    Util.AddFlatContainerResource(indexJson, server);
                    Util.AddRegistrationResource(indexJson, server);

                    server.Get.Add("/", request =>
                    {
                        return(ServerHandlerV3(request, server, indexJson, serverRepoPath));
                    });

                    server.Start();

                    var feedUrl = server.Uri + "index.json";

                    // Restore x 2.0.0 and populate the http cache
                    var r = Util.Restore(pathContext, projectA.ProjectPath, 0, "-Source", feedUrl);

                    // Delete x 1.0.0
                    File.Delete(LocalFolderUtility.GetPackageV2(serverRepoPath, packageX100.Identity, testLogger).Path);

                    // Act
                    // Restore x 1.0.0
                    r = Util.Restore(pathContext, projectB.ProjectPath, 0, "-Source", feedUrl);

                    var xLib = projectB.AssetsFile.Libraries.SingleOrDefault(e => e.Name == "x");

                    // Assert
                    Assert.Equal("2.0.0", xLib.Version.ToNormalizedString());
                }
        }
示例#17
0
        public void RestoreRetry_ProjectJsonRetryOnFailingV3Source()
        {
            // Arrange
            var nugetexe = Util.GetNuGetExePath();

            using (var workingDirectory = TestDirectory.Create())
                using (var packageDirectory = TestDirectory.Create())
                {
                    var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                    var package         = new ZipPackage(packageFileName);

                    var projectJsonContent = @"{
                    ""dependencies"": {
                        ""testPackage1"": ""1.1.0""
                    },
                    ""frameworks"": {
                                ""net45"": { }
                                }
                  }";

                    var nugetConfigContent = @"<?xml version=""1.0"" encoding=""utf-8""?>
                        <configuration>
                          <config>
                            <add key=""globalPackagesFolder"" value=""globalPackages"" />
                          </config>
                        </configuration>";

                    var projectFile = Util.CreateUAPProject(workingDirectory, projectJsonContent, "a", nugetConfigContent);

                    // Server setup
                    var indexJson = Util.CreateIndexJson();

                    using (var server = new MockServer())
                    {
                        Util.AddFlatContainerResource(indexJson, server);
                        Util.AddRegistrationResource(indexJson, server);
                        var hitsByUrl = new ConcurrentDictionary <string, int>();

                        server.Get.Add("/", r =>
                        {
                            var path = server.GetRequestUrlAbsolutePath(r);

                            // track hits on the url
                            var urlHits = hitsByUrl.AddOrUpdate(path, 1, (s, i) => i + 1);

                            // Fail on the first 2 requests for every url
                            if (urlHits < 3)
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.StatusCode = 503;
                                }));
                            }

                            if (path == "/index.json")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.StatusCode = 200;
                                    response.ContentType = "text/javascript";
                                    MockServer.SetResponseContent(response, indexJson.ToString());
                                }));
                            }
                            else if (path == "/flat/testpackage1/1.1.0/testpackage1.1.1.0.nupkg")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "application/zip";
                                    using (var stream = package.GetStream())
                                    {
                                        var content = stream.ReadAllBytes();
                                        MockServer.SetResponseContent(response, content);
                                    }
                                }));
                            }
                            else if (path == "/flat/testpackage1/index.json")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "text/javascript";

                                    MockServer.SetResponseContent(response, @"{
                              ""versions"": [
                                ""0.1.0"",
                                ""0.3.0"",
                                ""0.4.0"",
                                ""0.5.0"",
                                ""1.0.0"",
                                ""1.1.0"",
                                ""1.2.0""
                              ]
                            }");
                                }));
                            }

                            throw new Exception("This test needs to be updated to support: " + path);
                        });

                        server.Start();

                        // The minimum time is the number of urls x 3 waits x 200ms
                        var minTime = TimeSpan.FromMilliseconds(hitsByUrl.Count * 3 * 200);

                        // Act
                        var args = string.Format(
                            "restore {0} -SolutionDirectory . -Source {1}index.json -NoCache",
                            projectFile,
                            server.Uri);

                        var timer = new Stopwatch();
                        timer.Start();

                        var r1 = CommandRunner.Run(
                            nugetexe,
                            workingDirectory,
                            args,
                            waitForExit: true);

                        timer.Stop();

                        server.Stop();

                        // Assert
                        Assert.True(Util.IsSuccess(r1), r1.Item2 + " " + r1.Item3);

                        Assert.True(
                            File.Exists(
                                Path.Combine(workingDirectory,
                                             "globalPackages/testpackage1/1.1.0/testpackage1.1.1.0.nupkg")));

                        Assert.True(
                            File.Exists(
                                Path.Combine(workingDirectory,
                                             "globalPackages/testpackage1/1.1.0/testPackage1.1.1.0.nupkg.sha512")));

                        Assert.True(File.Exists(Path.Combine(workingDirectory, "project.lock.json")));

                        // Everything should be hit 3 times
                        foreach (var url in hitsByUrl.Keys)
                        {
                            Assert.True(hitsByUrl[url] == 3, url);
                        }

                        Assert.True(timer.Elapsed > minTime);
                    }
                }
        }
示例#18
0
        public void RestoreRetry_ProjectJsonRetryOnFailingV2Source()
        {
            // Arrange
            var nugetexe = Util.GetNuGetExePath();

            using (var workingDirectory = TestDirectory.Create())
                using (var packageDirectory = TestDirectory.Create())
                {
                    var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                    var package         = new ZipPackage(packageFileName);

                    var projectJson = @"{
                    ""dependencies"": {
                        ""testPackage1"": ""1.1.0""
                    },
                    ""frameworks"": {
                                ""net45"": { }
                                }
                  }";

                    var config = @"<?xml version=""1.0"" encoding=""utf-8""?>
                        <configuration>
                          <config>
                            <add key=""globalPackagesFolder"" value=""globalPackages"" />
                          </config>
                        </configuration>";

                    var projectFile = Util.CreateUAPProject(workingDirectory, projectJson, "a", config);

                    // Server setup
                    using (var server = new MockServer())
                    {
                        var hitsByUrl = new ConcurrentDictionary <string, int>();

                        server.Get.Add("/", r =>
                        {
                            var path = server.GetRequestUrlPathAndQuery(r);

                            // track hits on the url
                            var urlHits = hitsByUrl.AddOrUpdate(path, 1, (s, i) => i + 1);

                            // Fail on the first 2 requests for every url
                            if (urlHits < 3)
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.StatusCode = 503;
                                }));
                            }

                            if (path == "/nuget/$metadata")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    MockServer.SetResponseContent(response, Util.GetMockServerResource());
                                }));
                            }
                            else if (path == "/package/testPackage1/1.1.0")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "application/zip";
                                    using (var stream = package.GetStream())
                                    {
                                        var content = stream.ReadAllBytes();
                                        MockServer.SetResponseContent(response, content);
                                    }
                                }));
                            }
                            else if (path == "/nuget/FindPackagesById()?id='testPackage1'")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                                    string feed = server.ToODataFeed(new[] { package }, "FindPackagesById");
                                    MockServer.SetResponseContent(response, feed);
                                }));
                            }
                            else if (path == "/nuget")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.StatusCode = 200;
                                }));
                            }

                            throw new Exception("This test needs to be updated to support: " + path);
                        });

                        server.Start();

                        // Act
                        var args = string.Format(
                            "restore {0} -SolutionDirectory . -Source {1}nuget -NoCache",
                            projectFile,
                            server.Uri);

                        var timer = new Stopwatch();
                        timer.Start();

                        var r1 = CommandRunner.Run(
                            nugetexe,
                            workingDirectory,
                            args,
                            waitForExit: true);

                        timer.Stop();

                        server.Stop();

                        // Assert
                        Assert.True(Util.IsSuccess(r1), r1.Item2 + " " + r1.Item3);

                        Assert.True(
                            File.Exists(
                                Path.Combine(workingDirectory,
                                             "globalPackages/testpackage1/1.1.0/testpackage1.1.1.0.nupkg")));

                        Assert.True(
                            File.Exists(
                                Path.Combine(workingDirectory,
                                             "globalPackages/testpackage1/1.1.0/testPackage1.1.1.0.nupkg.sha512")));

                        Assert.True(File.Exists(Path.Combine(workingDirectory, "project.lock.json")));

                        // Everything should be hit 3 times
                        foreach (var url in hitsByUrl.Keys)
                        {
                            Assert.True(hitsByUrl[url] == 3, url);
                        }
                    }
                }
        }
示例#19
0
 public static void AddLegacyGalleryResource(JObject index, MockServer serverV2, string relativeUri = null)
 {
     FeedUtilities.AddLegacyGalleryResource(index, serverV2.Uri, relativeUri);
 }
示例#20
0
 public static void AddRegistrationResource(JObject index, MockServer server)
 {
     FeedUtilities.AddRegistrationResource(index, server.Uri);
 }
示例#21
0
 public static void AddFlatContainerResource(JObject index, MockServer server)
 {
     FeedUtilities.AddFlatContainerResource(index, server.Uri);
 }
示例#22
0
        public void RestoreRetry_PackagesConfigRetryOnFailingV2Source()
        {
            // Arrange
            var nugetexe = Util.GetNuGetExePath();

            using (var workingDirectory = TestDirectory.Create())
                using (var packageDirectory = TestDirectory.Create())
                {
                    var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                    var package         = new ZipPackage(packageFileName);

                    Util.CreateFile(
                        workingDirectory,
                        "packages.config",
                        @"<packages>
                        <package id=""testPackage1"" version=""1.1.0"" />
                    </packages>");

                    // Server setup
                    using (var server = new MockServer())
                    {
                        var hitsByUrl = new ConcurrentDictionary <string, int>();

                        server.Get.Add("/", r =>
                        {
                            var path = server.GetRequestUrlPathAndQuery(r);

                            // track hits on the url
                            var urlHits = hitsByUrl.AddOrUpdate(path, 1, (s, i) => i + 1);

                            if (path == "/nuget/$metadata")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    MockServer.SetResponseContent(response, Util.GetMockServerResource());
                                }));
                            }
                            else if (path == "/package/testPackage1/1.1.0")
                            {
                                // Fail on the first two requests for this download
                                if (urlHits < 3)
                                {
                                    return(new Action <HttpListenerResponse>(response =>
                                    {
                                        response.StatusCode = 503;
                                    }));
                                }

                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "application/zip";
                                    using (var stream = package.GetStream())
                                    {
                                        var content = stream.ReadAllBytes();
                                        MockServer.SetResponseContent(response, content);
                                    }
                                }));
                            }
                            else if (path == "/nuget/Packages(Id='testPackage1',Version='1.1.0')")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                                    var odata = server.ToOData(package);
                                    MockServer.SetResponseContent(response, odata);
                                }));
                            }
                            else if (path == "/nuget")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.StatusCode = 200;
                                }));
                            }

                            throw new Exception("This test needs to be updated to support: " + path);
                        });

                        server.Start();

                        // Act
                        var args = string.Format(
                            "restore packages.config -SolutionDirectory . -Source {0}nuget -NoCache",
                            server.Uri);

                        var timer = new Stopwatch();
                        timer.Start();

                        var r1 = CommandRunner.Run(
                            nugetexe,
                            workingDirectory,
                            args,
                            waitForExit: true);

                        timer.Stop();
                        server.Stop();

                        // Assert
                        Assert.True(Util.IsSuccess(r1), r1.Item2 + " " + r1.Item3);

                        Assert.True(
                            File.Exists(
                                Path.Combine(workingDirectory,
                                             "packages/testpackage1.1.1.0/testpackage1.1.1.0.nupkg")));
                    }
                }
        }
示例#23
0
 /// <summary>
 /// Create a registration blob for a single package
 /// </summary>
 public static JObject CreateSinglePackageRegistrationBlob(MockServer server, string id, string version)
 {
     return(FeedUtilities.CreatePackageRegistrationBlob(server.Uri, id, new KeyValuePair <string, bool>[] { new KeyValuePair <string, bool>(version, true) }));
 }
示例#24
0
        public void RestoreRetry_PackagesConfigRetryOnFailingV3Source()
        {
            // Arrange
            var nugetexe = Util.GetNuGetExePath();

            using (var workingDirectory = TestDirectory.Create())
                using (var packageDirectory = TestDirectory.Create())
                {
                    var packageFileName = Util.CreateTestPackage("testPackage1", "1.1.0", packageDirectory);
                    var package         = new ZipPackage(packageFileName);

                    Util.CreateFile(
                        workingDirectory,
                        "packages.config",
                        @"<packages>
                    <package id=""testPackage1"" version=""1.1.0"" />
                  </packages>");

                    Util.CreateFile(
                        workingDirectory,
                        "nuget.config",
                        @"<?xml version=""1.0"" encoding=""utf-8""?>
                        <configuration>
                            <config>
                            <add key=""globalPackagesFolder"" value=""globalPackages"" />
                            </config>
                        </configuration>");

                    // Server setup
                    var indexJson = Util.CreateIndexJson();

                    using (var server = new MockServer())
                    {
                        Util.AddFlatContainerResource(indexJson, server);
                        Util.AddRegistrationResource(indexJson, server);
                        var hitsByUrl = new ConcurrentDictionary <string, int>();

                        server.Get.Add("/", r =>
                        {
                            var path = server.GetRequestUrlAbsolutePath(r);

                            // track hits on the url
                            var urlHits = hitsByUrl.AddOrUpdate(path, 1, (s, i) => i + 1);

                            // Fail on the first 2 requests for every url
                            if (urlHits < 3)
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.StatusCode = 503;
                                }));
                            }

                            if (path == "/index.json")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.StatusCode = 200;
                                    response.ContentType = "text/javascript";
                                    MockServer.SetResponseContent(response, indexJson.ToString());
                                }));
                            }
                            else if (path == "/flat/testpackage1/1.1.0/testpackage1.1.1.0.nupkg")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "application/zip";
                                    using (var stream = package.GetStream())
                                    {
                                        var content = stream.ReadAllBytes();
                                        MockServer.SetResponseContent(response, content);
                                    }
                                }));
                            }
                            else if (path == "/reg/testpackage1/index.json")
                            {
                                return(new Action <HttpListenerResponse>(response =>
                                {
                                    response.ContentType = "text/javascript";

                                    string json = null;

                                    json = @"{
                    ""@id"": ""{0}/reg/testPackage1/index.json"",
                    ""@type"": [
                    ""catalog:CatalogRoot"",
                    ""PackageRegistration"",
                    ""catalog:Permalink""
                    ],
                    ""commitId"": ""6d2d2375-b263-49ee-9a46-fd6b2d77e592"",
                    ""commitTimeStamp"": ""2015-06-22T22:30:00.1487642Z"",
                    ""count"": 1,
                    ""items"": [
                    {
                        ""@id"": ""{0}reg/testPackage1/index.json#page/0.0.0/9.0.0"",
                        ""@type"": ""catalog:CatalogPage"",
                        ""commitId"": ""6d2d2375-b263-49ee-9a46-fd6b2d77e592"",
                        ""commitTimeStamp"": ""2015-06-22T22:30:00.1487642Z"",
                        ""count"": 1,
                        ""items"": [
                        {
                            ""@id"": ""{0}reg/testPackage1/1.1.0.json"",
                            ""@type"": ""Package"",
                            ""commitId"": ""1fa214b1-6a03-4b4e-a16e-4925f994057f"",
                            ""commitTimeStamp"": ""2015-04-01T20:27:37.8431747Z"",
                            ""catalogEntry"": {
                            ""@id"": ""{0}catalog0/data/2015.02.01.06.24.15/testPackage1.1.1.0.json"",
                            ""@type"": ""PackageDetails"",
                            ""authors"": ""test master"",
                            ""description"": ""test one"",
                            ""iconUrl"": """",
                            ""id"": ""testPackage1"",
                            ""language"": ""en-US"",
                            ""licenseUrl"": """",
                            ""listed"": true,
                            ""minClientVersion"": """",
                            ""projectUrl"": """",
                            ""published"": ""2012-01-01T22:12:57.713Z"",
                            ""requireLicenseAcceptance"": false,
                            ""summary"": ""stuffs"",
                            ""tags"": [
                                """"
                            ],
                            ""title"": """",
                            ""version"": ""1.1.0""
                            },
                            ""packageContent"": ""{0}packages/testPackage1.1.1.0.nupkg"",
                            ""registration"": ""{0}reg/testPackage1/index.json""
                        }],
                ""parent"": ""{0}reg/testPackage1/index.json"",
                        ""lower"": ""0.0.0"",
                        ""upper"": ""9.0.0""
                    }
                    ]}".Replace("{0}", server.Uri);

                                    var jObject = JObject.Parse(json);

                                    MockServer.SetResponseContent(response, jObject.ToString());
                                }));
                            }

                            throw new Exception("This test needs to be updated to support: " + path);
                        });

                        server.Start();

                        // The minimum time is the number of urls x 3 waits x 200ms
                        var minTime = TimeSpan.FromMilliseconds(hitsByUrl.Count * 3 * 200);

                        // Act
                        var args = string.Format(
                            "restore packages.config -SolutionDirectory . -Source {0}index.json -NoCache",
                            server.Uri);

                        var timer = new Stopwatch();
                        timer.Start();

                        var r1 = CommandRunner.Run(
                            nugetexe,
                            workingDirectory,
                            args,
                            waitForExit: true);

                        timer.Stop();

                        server.Stop();

                        // Assert
                        Assert.True(Util.IsSuccess(r1), r1.Item2 + " " + r1.Item3);

                        Assert.True(
                            File.Exists(
                                Path.Combine(workingDirectory,
                                             "packages/testpackage1.1.1.0/testpackage1.1.1.0.nupkg")));

                        // Everything should be hit 3 times
                        foreach (var url in hitsByUrl.Keys)
                        {
                            Assert.True(hitsByUrl[url] == 3, url);
                        }

                        Assert.True(timer.Elapsed > minTime);
                    }
                }
        }
示例#25
0
        /// <summary>
        /// Creates a mock server that contains the specified list of packages
        /// </summary>
        public static MockServer CreateMockServer(IList <IPackage> packages)
        {
            var server = new MockServer();

            server.Get.Add("/nuget/$metadata", r =>
                           Util.GetMockServerResource());
            server.Get.Add("/nuget/FindPackagesById()", r =>
                           new Action <HttpListenerResponse>(response =>
            {
                response.ContentType = "application/atom+xml;type=feed;charset=utf-8";
                string feed          = server.ToODataFeed(packages, "FindPackagesById");
                MockServer.SetResponseContent(response, feed);
            }));

            foreach (var package in packages)
            {
                var url = string.Format(
                    CultureInfo.InvariantCulture,
                    "/nuget/Packages(Id='{0}',Version='{1}')",
                    package.Id,
                    package.Version);
                server.Get.Add(url, r =>
                               new Action <HttpListenerResponse>(response =>
                {
                    response.ContentType = "application/atom+xml;type=entry;charset=utf-8";
                    var p1 = server.ToOData(package);
                    MockServer.SetResponseContent(response, p1);
                }));

                // download url
                url = string.Format(
                    CultureInfo.InvariantCulture,
                    "/package/{0}/{1}",
                    package.Id,
                    package.Version);
                server.Get.Add(url, r =>
                               new Action <HttpListenerResponse>(response =>
                {
                    response.ContentType = "application/zip";
                    using (var stream = package.GetStream())
                    {
                        var content = stream.ReadAllBytes();
                        MockServer.SetResponseContent(response, content);
                    }
                }));
            }

            // fall through to "package not found"
            server.Get.Add("/nuget/Packages(Id='", r =>
                           new Action <HttpListenerResponse>(response =>
            {
                response.StatusCode = 404;
                MockServer.SetResponseContent(response, @"<?xml version=""1.0"" encoding=""utf-8""?>
<m:error xmlns:m=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"">
  <m:code />
  <m:message xml:lang=""en-US"">Resource not found for the segment 'Packages'.</m:message>
</m:error>");
            }));

            server.Get.Add("/nuget", r =>
                           new Action <HttpListenerResponse>(response =>
            {
                response.StatusCode = 404;
            }));

            return(server);
        }